public override void Decode(byte[] buffer, int offset, int length) { BEncodedValue val; using (RawReader reader = new RawReader(new MemoryStream(buffer, offset, length, false), false)) { BEncodedDictionary d = BEncodedDictionary.Decode <BEncodedDictionary>(reader); int totalSize = 0; if (d.TryGetValue(MessageTypeKey, out val)) { messageType = (eMessageType)((BEncodedNumber)val).Number; } if (d.TryGetValue(PieceKey, out val)) { piece = (int)((BEncodedNumber)val).Number; } if (d.TryGetValue(TotalSizeKey, out val)) { totalSize = (int)((BEncodedNumber)val).Number; metadata = new byte[Math.Min(totalSize - piece * BlockSize, BlockSize)]; reader.Read(metadata, 0, metadata.Length); } } }
public override void Decode(byte[] buffer, int offset, int length) { BEncodedValue val; BEncodedDictionary d = BEncodedDictionary.Decode <BEncodedDictionary>(buffer, offset, length, false); if (d.TryGetValue(MaxRequestKey, out val)) { maxRequests = (int)((BEncodedNumber)val).Number; } if (d.TryGetValue(VersionKey, out val)) { version = ((BEncodedString)val).Text; } if (d.TryGetValue(PortKey, out val)) { LocalPort = (int)((BEncodedNumber)val).Number; } LoadSupports((BEncodedDictionary)d[SupportsKey]); if (d.TryGetValue(MetadataSizeKey, out val)) { metadataSize = (int)((BEncodedNumber)val).Number; } }
private void Assign() { TM.PieceHashed += (a, b) => { //if the PieceMap is null, this was a magnet link torrent but we know the map now if (PieceMap == null) { PieceMap = new bool[TM.Torrent.Pieces.Count]; } lock (PieceMap) { PieceMap[b.PieceIndex] = b.HashPassed; } PiecemapUpdate(this, new PiecemapEventArgs(Map, b.PieceIndex)); }; TM.PieceManager.BlockReceived += (a, b) => { PieceMap[b.Piece.Index] = true; PiecemapUpdate(this, new PiecemapEventArgs(Map, b.Piece.Index)); }; var RecoveryFile = Environment.ExpandEnvironmentVariables(TORRENT_DIR + $"\\{TM.InfoHash.ToHex()}.rec"); if (File.Exists(RecoveryFile)) { TM.LoadFastResume(new FastResume((BEncodedDictionary)BEncodedDictionary.Decode(File.ReadAllBytes(RecoveryFile)))); } CE.Register(TM); }
static FastResume?Load(Stream s) { try { var data = (BEncodedDictionary)BEncodedDictionary.Decode(s); return(new FastResume(data)); } catch { } return(null); }
public void DecodeDictionary() { string data = "d5:test15:test2e"; BEncodedDictionary encoding = new BEncodedDictionary(data); encoding.Decode(); Assert.AreEqual(1, encoding.Value.Count); //Assert.AreEqual(encoding.Value.ContainsKey("test1"), true); //Assert.AreEqual(encoding.Value.ContainsValue("test2"), true); }
/// <param name="fast_load">Indicate wither to stop loading at the first torrent found</param> public void Load(bool fast_load = false) { foreach (string dir in uTorrentDirs) { string p = Path.Combine(dir, "resume.dat"); if (File.Exists(p)) { using (var fs = new FileStream(p, FileMode.Open)) { try { var val = BEncodedDictionary.Decode(fs); BEncodedDictionary dict = val as BEncodedDictionary; foreach (var pair in dict) { try { string key = pair.Key.ToString(); if (key != ".fileguard") // special case { TorrentListing tl = new TorrentListing(); tl.Path = Path.Combine(dir, key); BEncodedDictionary values = pair.Value as BEncodedDictionary; tl.Name = values[new BEncodedString("caption")].ToString(); tl.SavePath = values[new BEncodedString("path")].ToString(); tl.Import = true; list.Add(tl); if (fast_load) { fs.Close(); return; } } } catch { } } } catch (BEncodingException) { //this exception may be thrown by the Decode function if the format is for some reason not recognized (maybe a later format?) //no matter what, let's not crash because of it, and just exit out in a safe manner. } } } } App.Current.Dispatcher.Invoke(new Action(() => { torrents.Items.Refresh(); })); }
/// <summary> /// Called from either Load(stream) or Load(string). /// </summary> /// <param name="stream"></param> /// <param name="path"></param> /// <returns></returns> private static Torrent Load(Stream stream, string path) { Check.Stream(stream); Check.Path(path); try { Torrent t = Torrent.LoadCore((BEncodedDictionary)BEncodedDictionary.Decode(stream)); t.torrentPath = path; return(t); } catch (BEncodingException ex) { throw new TorrentException("Invalid torrent file specified", ex); } }
public static bool TryLoad(string fastResumeFilePath, out FastResume fastResume) { try { if (File.Exists(fastResumeFilePath)) { var data = (BEncodedDictionary)BEncodedDictionary.Decode(File.ReadAllBytes(fastResumeFilePath)); fastResume = new FastResume(data); } else { fastResume = null; } } catch { fastResume = null; } return(fastResume != null); }
internal BEncodedDictionary Create(TorrentFile[] files, PieceWriter writer, string name) { // Clone the base dictionary and fill the remaining data into the clone var torrentDict = BEncodedDictionary.Decode <BEncodedDictionary>(dict.Encode()); Array.Sort <TorrentFile>(files, delegate(TorrentFile a, TorrentFile b) { return(String.CompareOrdinal(a.Path, b.Path)); }); if (Directory.Exists(Path)) { Logger.Log(null, "Creating multifile torrent from: {0}", Path); CreateMultiFileTorrent(torrentDict, files, writer, name); } else { Logger.Log(null, "Creating singlefile torrent from: {0}", Path); CreateSingleFileTorrent(torrentDict, files, writer, name); } return(torrentDict); }
/// <summary> /// 解码连接到接入点时收到的字节数组,并应用这些信息。 /// </summary> /// <param name="data">收到的数据。</param> ///// <param name="sendPeerEnter">解码过程中是否应该广播 PeerEnterNetwork 消息。</param> /// <exception cref="System.FormatException">解码失败时发生。</exception> /// <remarks> /// 需要发送 PeerEnterNetwork 消息的情况会发生于:A开启客户端和μT,B开启客户端和μT,A(用户列表非空)再尝试连接B,此时如果B并没有保存全网的用户列表,那么A就要广播 PeerEnterNetwork。 /// </remarks> private void DecodeTargetInformation(byte[] data) { // 如果对方发过来的是空,那么就肯定不会有数据啦 if (data.Length > 0) { BEncodedDictionary dictionary = BEncodedDictionary.Decode(data) as BEncodedDictionary; if (dictionary == null) { throw new FormatException("无法解码。"); } BEncodedList connList = dictionary["connections"] as BEncodedList; BEncodedDictionary peersDict = dictionary["peers"] as BEncodedDictionary; // 规范 v1.2 // 先确认自己,同时 if ... 是兼容老版的通信 if (dictionary.ContainsKey("your endpoint")) { BEncodedDictionary yourEndPoint = dictionary["your endpoint"] as BEncodedDictionary; var ip = new IPAddress((yourEndPoint["ip"] as BEncodedString).TextBytes); var port = BitConverter.ToUInt16((yourEndPoint["port"] as BEncodedString).TextBytes, 0); // 分别设置 KClient、TrackerServer 和 BT 客户端的自己 SetLocalEndPoint(new IPEndPoint(ip, port)); TrackerServer.SetLocalEndPoint(new IPEndPoint(ip, TrackerServer.LocalEndPoint.Port)); TrackerServer.SetMyself(new IPEndPoint(ip, TrackerServer.Myself.EndPoint.GetPortNumber())); this.FreeToGo = true; TrackerServer.FreeToGo = true; } // ... lock (ConnectionList) { foreach (var item in connList) { var d = item as BEncodedDictionary; KEndPoint kep = KEndPoint.Empty; kep.SetAddress((d["ip"] as BEncodedString).TextBytes); kep.SetPort((int)BitConverter.ToUInt16((d["port"] as BEncodedString).TextBytes, 0)); try { AddToConnectionList(kep); } catch (Exception) { } } } // 如果已经有用户登记了,那么应该广播 if (TrackerServer.Seeds.Count > 0) { lock (TrackerServer.Seeds) { foreach (var kv in TrackerServer.Seeds) { // 广播消息 BroadcastMyselfAddAsPeer(kv.Key); } } } lock (TrackerServer.Seeds) { foreach (var kv in peersDict) { InfoHash infoHash = InfoHash.FromByteArray(kv.Key.TextBytes); List <Peer> peers = new List <Peer>((kv.Value as BEncodedList).Count); foreach (var item in (kv.Value as BEncodedList)) { var d = item as BEncodedDictionary; KEndPoint kep = KEndPoint.Empty; kep.SetAddress((d["ip"] as BEncodedString).TextBytes); kep.SetPort((int)BitConverter.ToUInt16((d["port"] as BEncodedString).TextBytes, 0)); Peer peer = Peer.Create(kep); peers.Add(peer); } try { TrackerServer.Seeds.Add(infoHash, peers); } catch (Exception) { } } } } else { Logger.Log("待解码的数据为空,这意味着对方客户端目前持有的连接列表和用户列表为空。"); } }
private void ImportTorrents() { var patchy = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), ".patchy"); var torrentcache = Path.Combine(patchy, "torrentcache"); var uTorrent = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "uTorrent"); var transmission = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "transmission"); var serializer = new JsonSerializer(); Directory.CreateDirectory(patchy); Directory.CreateDirectory(Path.Combine(patchy, torrentcache)); if (uTorrentImportCheckBox.IsChecked.Value) { try { if (Directory.Exists(uTorrent)) { var torrents = Directory.GetFiles(uTorrent, "*.torrent"); BEncodedDictionary dictionary; if (File.Exists(Path.Combine(uTorrent, "resume.dat"))) { using (var stream = File.OpenRead(Path.Combine(uTorrent, "resume.dat"))) dictionary = (BEncodedDictionary)BEncodedDictionary.Decode(stream); foreach (var key in dictionary.Keys) { if (key.Text.EndsWith(".torrent")) { if (File.Exists(Path.Combine(uTorrent, key.Text))) { // Add torrent var torrent = Path.Combine(uTorrent, key.Text); var info = new TorrentInfo { Label = new TorrentLabel("µTorrent", "#00853F") { Foreground = "#FFFFFF" }, Path = ((BEncodedDictionary)dictionary[key.Text])["path"].ToString(), UploadSlots = 4, IsRunning = true }; if (!File.Exists(Path.Combine(torrentcache, Path.GetFileName(torrent)))) { using (var json = new StreamWriter(Path.Combine(torrentcache, Path.GetFileNameWithoutExtension(torrent) + ".info"))) serializer.Serialize(new JsonTextWriter(json), info); File.Copy(torrent, Path.Combine(torrentcache, Path.GetFileName(torrent))); } } } } } } } catch { MessageBox.Show("Failed to import from uTorrent.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } if (transmissionImportCheckBox.IsChecked.Value) { try { if (Directory.Exists(transmission)) { var torrents = Directory.GetFiles(Path.Combine(transmission, "Torrents"), "*.torrent"); var dictionaries = Path.Combine(transmission, "Resume"); foreach (var torrent in torrents) { if (File.Exists(Path.Combine(dictionaries, Path.GetFileNameWithoutExtension(torrent) + ".resume"))) { BEncodedDictionary dictionary; using (var stream = File.OpenRead(Path.Combine(dictionaries, Path.GetFileNameWithoutExtension(torrent) + ".resume"))) dictionary = (BEncodedDictionary)BEncodedDictionary.Decode(stream); // Add torrent var name = dictionary["name"].ToString(); var info = new TorrentInfo { Label = new TorrentLabel("Transmission", "#DA0000") { Foreground = "#FFFFFF" }, Path = dictionary["destination"].ToString(), UploadSlots = 4, IsRunning = true }; using (var json = new StreamWriter(Path.Combine(torrentcache, name + ".info"))) serializer.Serialize(new JsonTextWriter(json), info); File.Copy(torrent, Path.Combine(torrentcache, name + ".torrent")); } } } } catch { MessageBox.Show("Failed to import from Transmission.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } }