Exemplo n.º 1
0
        private void ParseData(NetIncomingMessage mes)
        {
            MessageType messageType = (MessageType)mes.ReadByte();

            switch (messageType)
            {
            case MessageType.NewClient:
                // mes.SenderEndPoint.Address.GetHashCode() != Peer.Configuration.LocalAddress.GetHashCode()
                //    && mes.SenderEndPoint.GetHashCode() != Peer.Socket.RemoteEndPoint.GetHashCode()
                //    &&
                int        ipLength          = mes.ReadInt32();
                IPAddress  clientIP          = new IPAddress(mes.ReadBytes(ipLength));
                int        clientPort        = mes.ReadInt32();
                IPEndPoint newClientEndpoint = new IPEndPoint(clientIP, clientPort);

                if (newClientEndpoint != Peer.Socket.LocalEndPoint)
                {
                    Peer.Connect(newClientEndpoint, Peer.CreateMessage());
                }
                Logman.Log("Successfully connected to a new client.");

                break;

            case MessageType.UpdateTorrentList:
                Logman.Log($"Received new torrent list from {mes.SenderEndPoint.ToString()}");
                Torrent[] newTorrents = TorrentSerializer.Deserialize(mes.Data);
                if (TorrentListReceived != null)
                {
                    TorrentListReceived.Invoke(newTorrents);
                }
                break;
            }
        }
Exemplo n.º 2
0
        public static Torrent[] Load()
        {
            if (!File.Exists("torrents.dat"))
            {
                return(null);
            }
            List <Torrent> retArr;

            using (MemoryStream mS = new MemoryStream(File.ReadAllBytes("torrents.dat")))
            {
                using (BinaryReader bR = new BinaryReader(mS))
                {
                    int tCount = bR.ReadInt32();
                    retArr = new List <Torrent>(tCount);
                    for (int i = 0; i < tCount; i++)
                    {
                        string   hash     = bR.ReadString();
                        string   name     = bR.ReadString();
                        int      trackLen = bR.ReadInt32();
                        string[] trackers = new string[trackLen];
                        for (int j = 0; j < trackLen; j++)
                        {
                            trackers[j] = bR.ReadString();
                        }
                        Torrent retTor = new Torrent(hash, name, trackers);
                        retArr.Add(retTor);
                    }
                }
            }
            Logman.Log($"Loaded local database containing {retArr.Count} torrents.");
            return(retArr.ToArray());
        }
Exemplo n.º 3
0
        public void Parse(NetIncomingMessage mes)
        {
            switch (mes.MessageType)
            {
            case NetIncomingMessageType.ConnectionApproval:
                mes.SenderConnection.Approve();
                break;

            case NetIncomingMessageType.WarningMessage:
                Logman.Log(mes.ReadString());
                break;

            case NetIncomingMessageType.StatusChanged:
                NetConnectionStatus stat = (NetConnectionStatus)mes.ReadByte();
                Logman.Log(mes.SenderEndPoint.Address.ToString() + ": " + stat.ToString(), LOG_TYPE.WARNING);
                if (stat == NetConnectionStatus.Connected)
                {
                    Logman.Log("New client connected, broadcasting connection.");
                    BroadcastNewConnection(mes.SenderConnection);
                    if (NewClientConnected != null)
                    {
                        NewClientConnected.Invoke(mes.SenderConnection);
                    }
                }
                break;

            case NetIncomingMessageType.Data:
                ParseData(mes);
                break;
            }
        }
Exemplo n.º 4
0
        public async void Test()
        {
            try
            {
                NatDevice dev = await DiscoverDevice();

                IPAddress ip = await dev.GetExternalIPAsync();

                Logman.Log($"Found NAT device on {ip.ToString()}.");
                Mapping oldMap = await dev.GetSpecificMappingAsync(Protocol.Udp, 57300);

                if (oldMap?.PrivatePort != 57300)
                {
                    await dev.CreatePortMapAsync(new Mapping(Protocol.Udp, 57300, 57300, "OpenTorrent"));

                    Logman.Log($"Opened port 57300");
                }
                else
                {
                    Logman.Log("Already opened");
                }
            }
            catch (NatDeviceNotFoundException ex)
            {
                Logman.Log("Could not find a suitable UPnP device. Please enable UPnP or forward port 57300 manually.", LOG_TYPE.ERROR);
            }
            catch (Exception e)
            {
                Logman.Log("Unknown UPnP error, kys.", LOG_TYPE.ERROR);
            }
        }
Exemplo n.º 5
0
 private static void NetworkManager_NewClientConnected(Lidgren.Network.NetConnection con)
 {
     if (torrentManager.torrentList.Count == 0)
     {
         return;
     }
     Logman.Log("Sending torrent database to new client.");
     networkManager.SendTorrentListUpdate(torrentManager.torrentList.ToArray(), con);
 }
Exemplo n.º 6
0
        public NetworkManager()
        {
            Conf = new NetPeerConfiguration("P2P");
            Conf.EnableMessageType(NetIncomingMessageType.UnconnectedData);
            Conf.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
            Conf.AcceptIncomingConnections = true;
            Conf.Port = 57300;
            Peer      = new NetPeer(Conf);

            m_SyncContext = new SynchronizationContext();
            SynchronizationContext.SetSynchronizationContext(m_SyncContext);

            Peer.RegisterReceivedCallback(new SendOrPostCallback(OnMessageReceived), SynchronizationContext.Current);

            Peer.Start();
            Logman.Log("Network manager done loading. Ready to receive messages.");
        }
Exemplo n.º 7
0
        public void AddTorrent(string path)
        {
            string ext = Path.GetExtension(path);

            if (!File.Exists(path) || Path.GetExtension(path) != ".torrent")
            {
                Logman.Log("Incorrect torrent file specified. Check the path and extension of the file.", LOG_TYPE.WARNING);
                return;
            }
            TorrentFile torrent    = Bencode.DecodeTorrentFile(path);
            Torrent     newTorrent = new Torrent(torrent.CalculateInfoHash(), Path.GetFileNameWithoutExtension(path), torrent.Announce);

            torrentList.Add(newTorrent);
            newTorrentList.Add(newTorrent);

            Logman.Log("Torrent added to database.");
            Database.Save(torrentList.ToArray());
            if (TorrentUpdateThresholdReached != null)
            {
                TorrentUpdateThresholdReached.Invoke(newTorrentList.ToArray());
            }
        }
Exemplo n.º 8
0
 public void Connect(string IP, int port)
 {
     Peer.Connect(IP, port, Peer.CreateMessage());
     Logman.Log("Connected");
 }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            networkManager = new NetworkManager();
            torrentManager = new TorrentManager();
            UPnPManager    = new Upnp();

            Task testUPNP = new Task(UPnPManager.Test);

            testUPNP.Start();
            testUPNP.Wait();

            networkManager.TorrentListReceived           += NetworkManager_TorrentListReceived;
            networkManager.NewClientConnected            += NetworkManager_NewClientConnected;
            torrentManager.TorrentUpdateThresholdReached += TorrentManager_TorrentUpdateThresholdReached;

            Torrent[] loadedTorrents = Database.Load();
            if (loadedTorrents != null)
            {
                torrentManager.torrentList.AddRange(loadedTorrents);
            }

            if (Directory.Exists("bulk"))
            {
                Logman.Log("Found a bulk/ folder, import all torrents inside ? (y/*)");
                if (Console.ReadLine().ToLower() == "y")
                {
                    BulkLoad();
                }
            }

            Logman.Log("Waiting for input, type ? or help to see a list of commands.");
            while (Running)
            {
                //Console.Write("> ");
                string[] userInput = Console.ReadLine().Split(' ');
                switch (userInput[0])
                {
                case "exit":
                case "quit":
                case "stop":
                    Running = false;
                    break;

                case "?":
                case "help":
                    Console.WriteLine("No help for now.");
                    break;

                case "add":
                case "send":
                    string torrentPath = string.Join(" ", userInput.Skip(1));
                    torrentManager.AddTorrent(torrentPath);
                    break;

                case "manualupdate":
                    networkManager.SendTorrentListUpdate(torrentManager.newTorrentList.ToArray());
                    torrentManager.newTorrentList.Clear();
                    Logman.Log("Sent new torrent list.");
                    break;

                case "debugconnect":
                    Logman.Log($"Trying to connect to {userInput[1]}:57300");
                    networkManager.Connect(userInput[1], 57300);
                    break;

                case "list":
                case "dir":
                    int torrentCount = torrentManager.torrentList.Count;
                    if (torrentCount == 0)
                    {
                        Logman.Log("No torrent found ! Try adding some or check your nodes.");
                        break;
                    }

                    int pageNumber = (userInput.Length > 1) ? int.Parse(userInput[1]) - 1 : 0;
                    Logman.Log($"Viewing page {pageNumber + 1} of {(torrentCount / 15) + 1}");

                    for (int i = 15 * pageNumber; i < 15 * (pageNumber + 1); i++)
                    {
                        if (i < torrentCount)
                        {
                            Logman.Log($"{i}: {torrentManager.torrentList[i].Name}");
                        }
                    }
                    break;

                case "get":
                    int torrentID = int.Parse(userInput[1]);
                    if (torrentID > torrentManager.torrentList.Count)
                    {
                        Logman.Log("No corresponding torrent found", LOG_TYPE.WARNING);
                    }
                    else
                    {
                        Process.Start(torrentManager.torrentList[torrentID].GetMagnet());
                    }
                    break;

                case "save":
                    Database.Save(torrentManager.torrentList.ToArray());
                    Logman.Log("Database successfully saved.");
                    break;
                }
                Thread.Sleep(1);
            }
            Logman.Log("Exited main loop. Press any key to exit.", LOG_TYPE.WARNING);
            Console.ReadLine();
        }
Exemplo n.º 10
0
 private static void NetworkManager_TorrentListReceived(Torrent[] torrents)
 {
     torrentManager.UpdateTorrentList(torrents);
     Database.Save(torrentManager.torrentList.ToArray());
     Logman.Log("Received torrent list update.");
 }
Exemplo n.º 11
0
 private static void TorrentManager_TorrentUpdateThresholdReached(Torrent[] newTors)
 {
     Logman.Log("Hit automatic update threshold. Sending new torrent list.");
     networkManager.SendTorrentListUpdate(newTors);
 }