Beispiel #1
0
        public static Metainfo FromBytes(byte[] bytes)
        {
            BencodedValue decoded  = Bencoder.Decode(bytes);
            Metainfo      metainfo = DecodeMetainfo(decoded);

            return(metainfo);
        }
Beispiel #2
0
 public void AddSession(Metainfo metainfo)
 {
     if (metainfo == null)
     {
         throw new ArgumentNullException(nameof(metainfo));
     }
 }
Beispiel #3
0
 public RepositorySession(Metainfo metainfo, RepositoryService service, IFileSandbox sandbox, RepositoryData data)
 {
     this.metainfo = metainfo;
     this.service  = service;
     this.sandbox  = sandbox;
     this.data     = data;
 }
        internal TorrentDownloadManager(PeerId localPeerId,
                                        IMainLoop mainLoop,
                                        IApplicationProtocol <PeerConnection> applicationProtocol,
                                        ITracker tracker,
                                        Metainfo description)
        {
            this.localPeerId    = localPeerId;
            this.mainLoop       = mainLoop;
            ApplicationProtocol = applicationProtocol;
            Description         = description;
            Tracker             = tracker;
            State                     = DownloadState.Pending;
            Downloaded                = 0;
            DownloadRateMeasurer      = new RateMeasurer();
            UploadRateMeasurer        = new RateMeasurer();
            progress                  = new Progress <StatusUpdate>();
            progress.ProgressChanged += ProgressChanged;

            pipeline = new PipelineBuilder()
                       .AddStage <VerifyDownloadedPiecesStage>()
                       .AddStage <DownloadPiecesStage>()
                       .Build();

            stageInterrupt = new StageInterrupt();
        }
Beispiel #5
0
        public FileStorage(Metainfo metaInfo, int blockLength)
        {
            if (metaInfo == null)
            {
                throw new ArgumentNullException("metaInfo");
            }

            _cache       = new MemCachedPieceStorage(CacheSize, blockLength, metaInfo.PieceLength);
            _metainfo    = metaInfo;
            _fileStreams = new List <FileStreamInfo>(metaInfo.Files.Count);
            foreach (var file in metaInfo.Files)
            {
                string     filePath = file.Path != null ? file.Path[0] : file.Name;
                FileStream fs       = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
                fs.SetLength(file.Length);
                _fileStreams.Add(new FileStreamInfo()
                {
                    Stream = fs,
                    File   = file
                });
            }
            _piecesHash = _metainfo.PiecesHash;
            _pieceLen   = _metainfo.PieceLength;
            _blockLen   = blockLength;

            _piecesHave = GetValidPieces();
        }
Beispiel #6
0
        internal PeerConnection(
            Metainfo meta,
            PeerId peerId,
            IReadOnlyList <byte> reservedBytes,
            ProtocolExtension supportedExtensions,
            IPeerMessageHandler messageHandler,
            ITransportStream transportStream)
        {
            this.messageHandler  = messageHandler;
            this.transportStream = transportStream;
            customValues         = new Dictionary <IModule, Dictionary <string, object> >();
            PeerId                = peerId;
            ReservedBytes         = reservedBytes;
            SupportedExtensions   = supportedExtensions;
            InfoHash              = meta.InfoHash;
            reader                = new BigEndianBinaryReader(transportStream.Stream);
            writer                = new BigEndianBinaryWriter(transportStream.Stream);
            Available             = new Bitfield(meta.Pieces.Count);
            RequestedByRemotePeer = new HashSet <BlockRequest>();
            Requested             = new HashSet <BlockRequest>();

            IsRemotePeerInterested   = false;
            IsInterestedInRemotePeer = false;
            IsChokedByRemotePeer     = true;
            IsChokingRemotePeer      = true;
        }
            public void Execute(RepositoryContext context, RepositoryTaskCallback onCompleted)
            {
                algorithm.Push(read.Buffer.Data, read.Buffer.Offset, Math.Min(read.Buffer.Count, read.Count));

                Metainfo metainfo = context.Metainfo;

                byte[] expected = metainfo.Pieces[read.Piece].ToBytes();

                byte[] hash   = algorithm.Complete();
                bool   result = Bytes.Equals(hash, expected);

                bitfield[read.Piece] = result;
                algorithm.Dispose();

                int  next   = Next(scope, read.Piece + 1);
                bool exists = context.View.Exists(next, 0);

                if (exists)
                {
                    context.Queue.Add(new Start(bitfield, scope, next, block));
                }
                else
                {
                    block.Release();
                    onCompleted.Invoke(this);

                    context.Bitfile.Write(bitfield);
                    context.Hooks.CallDataVerified(metainfo.Hash, bitfield);
                }
            }
Beispiel #8
0
        public override void Handle(MetafileCompletedNotification notification)
        {
            Console.WriteLine();
            Console.WriteLine(notification);

            metainfo = notification.Metainfo;
        }
 public PeerConnectionArgs(
     PeerId localPeerId,
     Metainfo metainfo)
 {
     LocalPeerId = localPeerId;
     Metainfo    = metainfo;
 }
        public void Setup()
        {
            var fileHandler = new Mock <IFileHandler>();

            _file1Stream = new MemoryStream();
            fileHandler.Setup(x => x.GetFileStream("File1.txt"))
            .Returns(_file1Stream);

            _file2Stream = new MemoryStream();
            fileHandler.Setup(x => x.GetFileStream("File2.txt"))
            .Returns(_file2Stream);

            var metainfo = new Metainfo("test",
                                        Sha1Hash.Empty,
                                        new[]
            {
                new ContainedFile("File1.txt", 100),
                new ContainedFile("File2.txt", 50),
            },
                                        new[]
            {
                new Piece(0, 50, Sha1Hash.Empty),
                new Piece(50, 50, Sha1Hash.Empty),
                new Piece(100, 50, Sha1Hash.Empty),
            },
                                        new IEnumerable <Uri> [0],
                                        new byte[0]);

            _blockDataHandler = new BlockDataHandler(fileHandler.Object, metainfo);
        }
        public void Setup()
        {
            writtenData = new List <Tuple <long, byte[]> >();

            Sha1Hash hash;

            using (var sha1 = SHA1.Create())
                hash = new Sha1Hash(sha1.ComputeHash(Enumerable.Repeat((byte)0, 50).ToArray()));

            var metainfo = new Metainfo("test",
                                        Sha1Hash.Empty,
                                        new[]
            {
                new ContainedFile("File1.txt", 100),
            },
                                        new[]
            {
                new Piece(0, 50, hash),
                new Piece(50, 50, hash),
            },
                                        new IEnumerable <Uri> [0],
                                        new byte[0]);

            var baseHandler = new Mock <IBlockDataHandler>();

            baseHandler.Setup(x => x.Metainfo)
            .Returns(metainfo);
            baseHandler.Setup(x => x.WriteBlockData(It.IsAny <long>(),
                                                    It.IsAny <byte[]>()))
            .Callback <long, byte[]>((offset, data) => writtenData.Add(Tuple.Create(offset, data)));

            pieceChecker = new PieceCheckerHandler(baseHandler.Object);
        }
Beispiel #12
0
 public static void HandleMetafileVerified(this RepositoryService service, Metainfo metainfo)
 {
     service.Handle(new MetafileVerified
     {
         Hash     = service.Hash,
         Metainfo = metainfo
     });
 }
 public PeerConnectionArgs(
     PeerId localPeerId,
     Metainfo metainfo,
     IPeerMessageHandler messageHandler)
 {
     LocalPeerId    = localPeerId;
     Metainfo       = metainfo;
     MessageHandler = messageHandler;
 }
Beispiel #14
0
 public MetafileSession(IFileSandbox sandbox, Metainfo metainfo, string path, byte[] data, MetafileService service, Task onVerified)
 {
     this.sandbox    = sandbox;
     this.metainfo   = metainfo;
     this.path       = path;
     this.data       = data;
     this.service    = service;
     this.onVerified = onVerified;
 }
Beispiel #15
0
        public FileHash ToHash()
        {
            BencodedValue entries = Build();

            byte[] bytes = Bencoder.Encode(entries);

            Metainfo metainfo = MetainfoFactory.FromBytes(bytes);
            FileHash hash     = metainfo.Hash;

            return(hash);
        }
Beispiel #16
0
        private Metainfo.File FindFileInMeta(Metainfo meta, string fileName)
        {
            foreach (var file in meta.Files)
            {
                if (file.Path.Last().Contains(fileName))
                {
                    return(file);
                }
            }

            throw new System.IO.FileNotFoundException($"File {fileName} does not found");
        }
Beispiel #17
0
        public SequentialPieceRqStrategyOneFile(Metainfo meta, string fileName)
        {
            Metainfo.File file = FindFileInMeta(meta, fileName);
            _initialOffset = CalcFileStartOffset(meta, file) / meta.PieceLength;
            _pieces        = new BitField(meta.PiecesCount);

            _piecesCount = file.Length / meta.PieceLength;
            for (int i = _initialOffset; i < _piecesCount; i++)
            {
                _pieces[i] = false;
            }
        }
Beispiel #18
0
        public static MetainfoFile FromFile(string path)
        {
            byte[]        bytes   = File.ReadAllBytes(path);
            BencodedValue decoded = Bencoder.Decode(bytes);
            BencodedValue info    = decoded.Find("info", x => x);

            Metainfo metainfo = DecodeMetainfo(info);

            string[] trackers = FindTrackers(decoded);

            return(new MetainfoFile(metainfo, trackers));
        }
Beispiel #19
0
        /// <summary>
        /// Reads the incoming message from the specified reader.
        /// </summary>
        /// <param name="meta">Metainfo for the download.</param>
        /// <param name="reader">The data reader to read from.</param>
        /// <param name="messageLength">The length of the incoming message.</param>
        /// <param name="messageId">The message ID of the incoming message.</param>
        public static CommonPeerMessage ReadMessage(Metainfo meta, BinaryReader reader, int messageLength, byte messageId)
        {
            Func <Metainfo, CommonPeerMessage> creationDelegate;

            if (MessageDelegates.TryGetValue(messageId, out creationDelegate))
            {
                CommonPeerMessage message = creationDelegate(meta);
                message.Receive(reader, messageLength);
                return(message);
            }

            return(null);
        }
Beispiel #20
0
        internal TorrentDownload Add(Metainfo metainfo, ITracker tracker, IFileHandler fileHandler)
        {
            var dataHandler = new PieceCheckerHandler(new BlockDataHandler(fileHandler, metainfo));
            var bitTorrentApplicationProtocol = new BitTorrentApplicationProtocol <BitTorrentPeerInitiator.IContext>(LocalPeerId, metainfo, peerInitiator, m => new QueueingMessageHandler(mainLoop, m), moduleManager, dataHandler);
            var downloadManager = new TorrentDownloadManager(LocalPeerId,
                                                             mainLoop,
                                                             bitTorrentApplicationProtocol,
                                                             tracker,
                                                             metainfo);

            var download = new TorrentDownload(downloadManager);

            downloads.Add(metainfo.InfoHash, download);
            return(download);
        }
Beispiel #21
0
        private int CalcFileStartOffset(Metainfo meta, Metainfo.File file)
        {
            int offset = 0;

            foreach (var metaFile in meta.Files)
            {
                if (file.Path.Last().Equals(metaFile.Path.Last()))
                {
                    break;
                }

                offset += file.Length;
            }

            return(offset);
        }
        internal TorrentDownload Add(Metainfo metainfo, ITracker tracker, IFileHandler fileHandler)
        {
            // Create a new scope for this download
            var scope       = _services.CreateScope();
            var dataHandler = ActivatorUtilities.CreateInstance <PieceCheckerHandler>(scope.ServiceProvider, new BlockDataHandler(fileHandler, metainfo));
            var applicationProtocolFactory = scope.ServiceProvider.GetRequiredService <IApplicationProtocolFactory>();
            var applicationProtocol        = applicationProtocolFactory.Create(metainfo, dataHandler);
            var pipelineRunner             = ActivatorUtilities.CreateInstance <PipelineRunner>(scope.ServiceProvider, applicationProtocol, tracker);

            _peerInitiator.OnApplicationProtocolAdded(pipelineRunner.ApplicationProtocol);

            var download = new TorrentDownload(pipelineRunner);

            _downloads.Add(metainfo.InfoHash, download);
            return(download);
        }
 public BitTorrentApplicationProtocol(
     ILogger <BitTorrentApplicationProtocol> logger,
     PeerId localPeerId,
     Metainfo metainfo,
     IApplicationProtocolPeerInitiator peerInitiator,
     IEnumerable <IModule> modules,
     IPieceDataHandler dataHandler)
 {
     _logger                     = logger;
     _localPeerId                = localPeerId;
     _peerInitiator              = peerInitiator;
     _modules                    = modules.ToList().AsReadOnly();
     DataHandler                 = dataHandler;
     dataHandler.PieceCompleted += PieceCompleted;
     dataHandler.PieceCorrupted += PieceCorrupted;
     Metainfo                    = metainfo;
     _blockRequests              = new BlockRequestManager();
 }
Beispiel #24
0
 public BitTorrentApplicationProtocol(
     PeerId localPeerId,
     Metainfo metainfo,
     IApplicationProtocolPeerInitiator <PeerConnection, TConnectionContext, PeerConnectionArgs> peerInitiator,
     Func <IPeerMessageHandler, IPeerMessageHandler> messageHandlerFactory,
     IModuleManager modules,
     IPieceDataHandler dataHandler)
 {
     this.localPeerId           = localPeerId;
     this.peerInitiator         = peerInitiator;
     this.messageHandlerFactory = messageHandlerFactory;
     this.modules = modules;
     DataHandler  = dataHandler;
     dataHandler.PieceCompleted += PieceCompleted;
     dataHandler.PieceCorrupted += PieceCorrupted;
     Metainfo      = metainfo;
     blockRequests = new BlockRequestManager();
 }
            public void Execute(RepositoryContext context, RepositoryTaskCallback onCompleted)
            {
                algorithm.Push(read.Buffer.Data, read.Buffer.Offset, Math.Min(read.Buffer.Count, read.Count));

                Metainfo metainfo = context.Metainfo;

                byte[] expected = metainfo.Pieces[piece.Index].ToBytes();

                byte[] hash   = algorithm.Complete();
                bool   result = Bytes.Equals(hash, expected);

                AcceptIfRequired(context, result);
                RejectIfRequired(context, result);

                algorithm.Dispose();
                block.Release();

                onCompleted.Invoke(this);
            }
Beispiel #26
0
        public MetafileSession Start(bool completed = false)
        {
            Metainfo metainfo = null;

            byte[] data = null;

            using (IFileSandbox temp = new FileSandbox(new EmptyFileLocator()))
            {
                MetainfoBuilder builder = new MetainfoBuilder(temp.Directory);
                string          path    = temp.CreateFile("debian-8.5.0-amd64-CD-1.iso");

                File.WriteAllBytes(path, Bytes.Random(20000));
                builder.AddFile(path);

                metainfo = builder.ToMetainfo(out data);
            }

            IFileSandbox sandbox     = new FileSandbox(new EmptyFileLocator());
            string       destination = Path.Combine(sandbox.Directory, metainfo.Hash.ToString());

            if (completed)
            {
                File.WriteAllBytes(destination, data);
            }

            MetafileService service =
                new MetafileBuilder()
                .WithHash(metainfo.Hash)
                .WithDestination(destination)
                .WithFiles(files)
                .WithPipeline(pipeline)
                .Build();

            TaskCompletionSource <bool> onVerified = new TaskCompletionSource <bool>();

            service.Hooks.OnMetafileVerified += _ => onVerified.SetResult(true);

            return(new MetafileSession(sandbox, metainfo, destination, data, service, onVerified.Task));
        }
Beispiel #27
0
        public void CalcInfoHash()
        {
            Metainfo mf = new Metainfo(File.ReadAllBytes("infHash.torrent"), Encoding.ASCII);

            CollectionAssert.AreEqual(mf.InfoHash, ParseTest.ConvertHexStringToByteArray("139f69de76a07790ec3ad31cbc3bd5d905871600"));
        }
Beispiel #28
0
 public TorrentDownload Add(Metainfo metainfo, string downloadDirectory)
 {
     return(Add(metainfo, new AggregatedTracker(trackerClientFactory, metainfo.Trackers), new DiskFileHandler(downloadDirectory)));
 }
Beispiel #29
0
 public MetafileCompletedNotification(Metainfo metainfo)
 {
     this.metainfo = metainfo;
 }
Beispiel #30
0
 public OmnibusSession(Metainfo metainfo, OmnibusService service)
 {
     this.metainfo = metainfo;
     this.service  = service;
 }