Example #1
0
        /** TODO prefere call CRAWL packet to get a fresh list
         * FIrst check in the cache if we have something
         * If not , call the Gwebcache service to bootstrap into gnutella2 network
         * */
        public NodePeer ConnectToRandomHub()
        {
            NodePeer p = null;

            do
            {
                while (GHubCache.Instance.HubCacheSize > 0 && (p = ConnectToHubInCache()) == null)
                {
                }
                if (p != null)
                {
                    break;
                }
                p = Bootstrap();
                if (p == null)
                {
                    GWebCache.Instance.ForceRefresh = true; // if we have bootstrap one time and no answer is good, we force the refresh
                }
            } while (p == null);
            if (p != null)
            {
                G2Log.Write("G2Network : Connected to " + p.ToString());
            }
            return(p);
        }
Example #2
0
        private void HandleErrorHeader(HttpHeader h)
        {
            List <NodePeer> hubs = h.getHubList();

            hubs.ForEach(x => GHubCache.Instance.AddHub(x));
            G2Log.Write("ParseErrorHeader() : Retrieved " + hubs.Count + " hubs");
        }
Example #3
0
 public static void ReadSettings()
 {
     try
     {
         string   path = Directory.GetCurrentDirectory() + "\\" + CONFIG_FILE_NAME;
         FileInfo info = new FileInfo(path);
         if (!info.Exists)
         {
             G2Log.Write("Settings : Config File Not Found . Default values ...");
             return;
         }
         using (StreamReader reader = new StreamReader(info.FullName))
         {
             string line = null;
             while ((line = reader.ReadLine()) != null)
             {
                 ParseLine(line);
             }
         }
     }
     catch (Exception e)
     {
         G2Log.Write("Settings : Error while parsing config file ... " + e.ToString());
     }
 }
Example #4
0
        public List <NodePeer> GetPeerList()
        {
            if (!MustRefresh())
            {
                return(pList);
            }
            else
            {
                RefreshPeerList();
            }

            List <NodePeer> PeerList = null;

            foreach (string url in getUrlList())
            {
                G2Log.Write("GWebCache: Try retrieve from " + url + "...");
                bool DownloadSuccess = downloadPeerListFile(url);
                if (!DownloadSuccess)
                {
                    RefreshPeerList();                      // delete file and update datetime
                    continue;
                }
                PeerList = ParsePeerList();
                if (PeerList != null)
                {
                    break;
                }
            }
            return(PeerList);
        }
Example #5
0
        /**
         * Return a list of peer in G2 network (simple leaf or ultra peer)
         * from the file downloaded precedently
         * */
        private List <NodePeer> ParsePeerList()
        {
            if (!fileExists())
            {
                return(null);
            }

            List <NodePeer> peers = new List <NodePeer> ();
            StreamReader    file  = new StreamReader(FileName);
            string          line  = "";
            int             count = 0;

            while ((line = file.ReadLine()) != null)
            {
                try {
                    NodePeer h = NodePeer.Parse(line);
                    peers.Add(h);
                    count++;
                } catch (FormatException e) {
                                        #if DEBUG
                    //Console.Error.WriteLine (e);
                                        #endif
                }
            }
            if (peers.Count == 0)
            {
                Console.Error.WriteLine("No peer found");
                return(null);
            }

            G2Log.Write("GWebCache : Found " + peers.Count + " peers ...");
            return(peers);
        }
Example #6
0
        // True if connected to a hub
        // false if attempted to connect to a leaf ( but has certainly retrieved many hubs )
        public bool TryConnect()
        {
            try {
                bool success = false;
                G2Log.Write("GHandshake : Try to connect to " + remote_host.ToString());
                var isConnected = tcp.Connect();
                if (!isConnected)
                {
                    return(false);
                }
                OnConnected();
                success = OnResponse();
                if (success)
                {
                    //bool connected = tcp.CheckConnection();
                    //Log.Write("GHandshake : Connected ? " + connected);
                    OnReply();
                }
                else
                {
                    tcp.Close();
                }

                return(success);
            } catch (Exception e) {
                tcp.Close();
                return(false);
            }
        }
Example #7
0
 /** Remove the hub from the connected hub cache and close its connection */
 public void RemoveConnectedHub(NodePeer hub)
 {
     lock (ConnectedHub_) {
         ConnectedHub_.Remove(hub);
         hub.Close();
         G2Log.Write("Cache : Removing hub " + hub.ToString() + " ... ");
     }
 }
Example #8
0
 /**
  * Add the hub to the list of connected hub
  * and remove it from the list of available hubs
  * */
 public void AddConnectedHub(NodePeer hub)
 {
     lock (ConnectedHub_) {
         RemoveHub(hub);
         ConnectedHub_.Add(hub);
         G2Log.Write("GHUBCACHE : ADDED CONNECTED HUB " + hub.ToString());
     }
 }
Example #9
0
 /** Terminates connection with each connected peers */
 public void CloseHubConnections()
 {
     lock (ConnectedHub_) {
         G2Log.Write("Cache : Closing  HUB connections ... ");
         foreach (NodePeer p in ConnectedHub_)
         {
             p.Close();
         }
         ConnectedHub_.Clear();
     }
 }
Example #10
0
        /**
         * Launch the sockets thread and the processing threads
         * */
        public void StartNetwork()
        {
            G2Log.Write("G2Network : Starting network processes ... ");
            process = ProcessingThread.Instance;

            cache = GHubCache.Instance;
            process.Start();
            // start a few connections
            for (int i = 0; i < Settings.PEER_DISPATCH_QUERY; i++)
            {
                ConnectToRandomHub();
            }
        }
Example #11
0
 private static void WriteFile(string message)
 {
     lock (locker) {
         try {
             using (StreamWriter wr = System.IO.File.AppendText(Settings.LOG_OUTPUT_FILE))
             {
                 wr.WriteLine(message);
             }
         } catch (Exception e) {
             G2Log.WriteConsole("LOG : " + e.ToString());
         }
     }
 }
Example #12
0
        public void ReadPackets()
        {
            using (StreamReader fileStream = new StreamReader(fileToRead))
            {
                var str = fileStream.ReadToEnd();
                G2Log.Write("File : " + str);
                byte[] bytes = StringToByteArray(str);

                NodePeer       p      = new NodePeer(IPAddress.Parse("127.0.0.1"), 16546, 0, false);
                G2PacketReader reader = new G2PacketReader(p);
                reader.Read(bytes, bytes.Length);
                G2Log.Write("G2PacketTest: ReadPacket file " + fileToRead);
                G2Packet pack = p.Buffer.PollPacketToReceive();
                G2Log.Write(pack.ToString());
                //if(pack.type == G2PacketType.LNI) testLNI (pack);
            }
        }
Example #13
0
        /**
         * When the response of the hub is successful, we terminate the handshake
         * */
        private void OnReply()
        {
            try {
                HttpHeader h = new HttpHeader();
                h[HttpHeader.PROTOCOL_KEY]     = "GNUTELLA/0.6 200 OK";
                h[HttpHeader.CONTENT_TYPE_KEY] = HttpHeader.CONTENT_TYPE_G2_VALUE;
                h[HttpHeader.IS_HUB_KEY]       = "False";
                //h[HttpHeader.IS_ULTRA_PEER_KEY] = "False";
//				/** TODO check if encoding is present **/
                setEncoding(h);
                byte[] msg       = System.Text.Encoding.ASCII.GetBytes(h.ToString());
                bool   byte_sent = tcp.Send(new ByteBuffer(msg));
            } catch (ArgumentNullException ane) {
                throw new ArgumentNullException("GHandshakeOnReply() : {0}", ane.ToString());
            } catch (SocketException se) {
                throw new NetException("GHandshakeOnReply() : " + se.ToString());
            } catch (Exception e) {
                G2Log.Write("GHandshake ERROR OnReply() : " + e.ToString());
            }
        }
Example #14
0
        public void SearchKeyword(SearchTransaction searchTransaction)
        {
            queueKeywords = new System.Collections.Queue();

            try
            {
                //pour chaque keyword on lance le search dans un thread séparé
                foreach (Keyword k in searchTransaction.Keywords)
                {
                    KeywordCollection keyword     = null;
                    SearchTransaction searchTrans = null;
                    keyword = new KeywordCollection();
                    keyword.Add(k);
                    searchTrans = new SearchTransaction(searchTransaction.IdTransaction, keyword, searchTransaction.MinFileFromPeerFilter, searchTransaction.IpAcceptRangeCollection);
                    queueKeywords.Enqueue(searchTrans);
                }

                // regrouping of results for this transaction
                // will raise the CompletResultHandler event when we received one results for each keyword
                G2SearchResultRegrouping searchRegrouping = new G2SearchResultRegrouping(searchTransaction, searchTransaction.Keywords.Count, false);
                searchRegrouping.CompletResult += new CompletResultHandler(searchRegrouping_CompletResult);
                searchResultRegroupingKeyword_.Add(searchRegrouping);



                while (queueKeywords.Count > 0)
                {
                    SearchTransaction srchTrans = (SearchTransaction)queueKeywords.Dequeue();

                    G2Log.Write("Starting Transaction - Keyword :" + srchTrans.Keywords[0].KeywordName.ToString());
                    searchManager.NewSearch(srchTrans);

                    // on attends 30sec ?????????????????????????
                    //System.Threading.Thread.Sleep(30000);
                }
            }
            catch
            {
                G2Log.Write("Erreur niveau manager.....");
            }
        }
Example #15
0
        /**
         * When results arrive, they are stacked  and regrouped
         * */
        public void SearchKeywordResult(SearchResult searchResult)
        {
            G2SearchResultRegrouping search = null;

            try
            {
                string id = searchResult.SearchTransaction.IdTransaction;
                search = (G2SearchResultRegrouping)searchResultRegroupingKeyword_.Find(searchResult.SearchTransaction.IdTransaction);
                search.AddGlobalResult(searchResult); // Rajoute ces résultats aux résultats globaux
                string word = searchResult.SearchTransaction.Keywords[0].KeywordName;
                G2Log.Write("G2MANAGER : Received results for " + word + " => " + searchResult.PeerCollection.Count
                            + " Peers & " + searchResult.FileCollection.Count + " Files ...");
            }
            catch (Exception ex)
            {
                G2Log.Write("Error AddGlobalResult" + ex.Message, G2Log.ERROR_FILE);
                G2Log.Write("Erreur server_NewResult = " + ex.Message
                            + "\n" + "Erreur server_NewResult, source= " + ex.Source
                            + "\n" + "Erreur server_NewResult, stack= " + ex.StackTrace, G2Log.ERROR_FILE);
            }
        }
Example #16
0
        /**
         * Download the file associated with the GWebCache url
         * return false if error
         * true if went well
         * ATTENTION : true doesn't mean file content is right
         * server can respond with an error, to check with parse file
         * */
        private bool downloadPeerListFile(string url)
        {
            try
            {
                var client = new WebClient();
                client.DownloadFile(url, FileName);
            }
            catch (Exception e)
            {
                G2Log.Write("GWebCache : " + e.ToString());
            }
            finally
            {
            }
            if (fileExists())
            {
                return(true);
            }

            Console.Error.WriteLine("GWebCache : Could not retrieve Peer file");
            return(false);
        }
Example #17
0
        private void Process()
        {
            while (continueProcess)
            {
                // wait 'till there is something to do
                network.WaitNewActions();
                if (!continueProcess)
                {
                    break;
                }

                // check actions to take for each connected peers
                // TO UPGRADE TO MORE EFFIENCY VERSION
                foreach (NodePeer hub in cache.ConnectedHubs)
                {
                    //if new message received
                    OnNewMessage(hub);
                    // HERE put search actions
                }
            }
            G2Log.Write("ProcessingThread : Stopping thread ...");
        }
Example #18
0
        public void testLNI(G2Packet packTest)
        {
            G2PacketLNI rLNI = (G2PacketLNI)packTest;
            G2PacketGU  rGU  = (G2PacketGU)rLNI.getFirstChildPacket(G2PacketType.GU);
            G2PacketNA  rNA  = (G2PacketNA)rLNI.getFirstChildPacket(G2PacketType.NA);
            G2PacketV   rV   = (G2PacketV)rLNI.getFirstChildPacket(G2PacketType.V);

            G2Packet lni = new G2PacketLNI();

            lni.AddChild(new G2PacketNA(rNA.node));
            lni.AddChild(new G2PacketGU(rGU.nodeGuid));
            lni.AddChild(new G2PacketV(rV.Str));
            lni.FinalizePacket();
            G2Log.Write(lni.ToString());
            MemoryStream s1 = new MemoryStream((int)rLNI.getTotalPacketLength());
            MemoryStream s2 = new MemoryStream((int)lni.getTotalPacketLength());

            rLNI.Write(s1);
            lni.Write(s2);

            byte[] b1 = s1.ToArray();
            byte[] b2 = s2.ToArray();

            if (b1.Length != b2.Length)
            {
                G2Log.Write(" NOT EQUAL");
                return;
            }
            for (int i = 0; i < b1.Length; i++)
            {
                if (b1 [i] != b2 [i])
                {
                    G2Log.Write("NOT EQUAL");
                    return;
                }
            }
            G2Log.Write("EQUAL !!");
        }
Example #19
0
        public void testReader()
        {
            G2Network.Instance.SelfAddress = System.Net.IPAddress.Parse("127.0.0.1");
            G2Packet lni = Settings.SmartLNIPacket();
            G2Packet na  = new G2PacketNA(new NodeAddress(System.Net.IPAddress.Parse("127.0.0.1"), 6345));

            for (int i = 0; i < 300; i++)
            {
                lni.AddChild(na);
            }
            lni.FinalizePacket();
            G2Log.Write(lni.ToString());
            ByteBuffer     b      = lni.ToBuffer();
            G2PacketReader reader = new G2PacketReader(new NodePeer(System.Net.IPAddress.Parse("127.0.0.1"), 6346, 0, false));
            int            nb     = 3;

            byte[][] bytes = new byte[nb][];
            int      start = 0;
            int      div   = b.Length / nb;

            for (int i = 0; i < nb; i++)
            {
                if (i == nb - 1)
                {
                    div += b.Length % nb;
                }
                bytes [i] = new byte[div];
                Array.Copy(b.Bytes, start, bytes [i], 0, div);
                start += div;
            }


            for (int i = 0; i < nb; i++)
            {
                bool enough = reader.Read(bytes [i], bytes[i].Length);
                if (enough)
                {
                    G2Log.Write("PacketReader Test Success");
                    break;
                }
            }
            G2Packet   lni2 = Settings.SmartLNIPacket();
            ByteBuffer b2   = lni2.ToBuffer();
            bool       succ = reader.Read(b2.Bytes, b2.DataOffset);

            if (succ)
            {
                G2Log.Write("PacketReader Test Unit Packet Success");
            }
            else
            {
                G2Log.Write("PacketReader Test Unit Packet FAILED");
            }


            b.Append(b2);
            succ = reader.Read(b.Bytes, b.DataOffset);
            if (succ)
            {
                G2Log.Write("PacketReader Test Sequential Packet Success");
            }
            else
            {
                G2Log.Write("PacketReader TEst Sequential Packet FAILED");
            }
        }