コード例 #1
0
ファイル: TCPClient.cs プロジェクト: nikkolasg/gnutella2
        public bool Connect()
        {
            Thread t = new Thread(new ThreadStart(ConnectTimeOut));

            t.IsBackground = true;
            t.Start();
            t.Join(CONNECT_TIMEOUT);
            if (sock == null || !sock.Connected)
            {
                t.Abort();
                if (exception != null)
                {
                    G2Log.Write(exception.ToString());
                }
                return(false);
            }

            sock.ReceiveTimeout = 5000;


            stream              = new NetworkStream(sock, true);
            stream.ReadTimeout  = IO_TIMEOUT;
            stream.WriteTimeout = IO_TIMEOUT;
            if (!stream.CanRead)
            {
                Console.Error.WriteLine("NetworkStream cannot read");
                return(false);
            }
            if (!stream.CanWrite)
            {
                Console.Error.WriteLine("NetworkStream cannot write");
                return(false);
            }
            return(true);
        }
コード例 #2
0
        public void Close()
        {
            G2Log.Write("HubSocket : " + this.peer.ToString() + " Closing ... ");
            shouldStop_ = true;
            if (Receiver.ThreadState == ThreadState.Running)
            {
                bool succ = Receiver.Join(JOIN_WAIT_TIME);
                if (!succ)
                {
                    Receiver.Abort();
                }
            }
            G2Log.Write("\tHubSocket : =======> closed Receiver Thread (" + this.peer.ToString() + ") ...");
            // no check for sender because it can be in waitsleep join , or running, or waking ...
            bool success = Sender.Join(JOIN_WAIT_TIME);

            if (!success)
            {
                Sender.Abort();
            }

            G2Log.Write("\tHubSocket : =======> closed Sender Thread (" + this.peer.ToString() + ") ...");
            if (sock != null && sock.Connected)
            {
                stream.Close();
                stream.Dispose();
                //sock.Shutdown (SocketShutdown.Both);
            }
        }
コード例 #3
0
ファイル: Datagrams.cs プロジェクト: nikkolasg/gnutella2
 public void Stop()
 {
     if (Receiver != null)
     {
         Receiver.Abort();
     }
     G2Log.Write(ToString());
 }
コード例 #4
0
 /**
  * Push a packet just received, to be analyzed further
  * */
 public void PushPacketToReceive(G2Packet pack)
 {
     lock (ReceiveBuffer) {
         ReceiveBuffer.Enqueue(pack);
         var type = pack.packetHeader.type;
         type += pack.type == G2PacketType.DEFAULT ? " (unknown) " : "";
         G2Log.Write("PacketBuffer : Enqueued incoming packet " + type + " to receive  from " + pack.RemotePeer.ToString());
     }
 }
コード例 #5
0
        public static Metadata ParseMetadata(string xmlString)
        {
            Metadata data = new Metadata();

            if (xmlString.Length == 0)
            {
                return(data);
            }
            try
            {
                XElement xml = XElement.Parse(xmlString);

                data.Type = xml.Name.ToString();

                XAttribute attr = null;
                attr = xml.Attribute(TITLE_ATTR); // getting the title
                if (attr != null)
                {
                    data.Title = attr.Value;
                }

                if ((attr = xml.Attribute(SECONDS_ATTR)) != null) // getting length in seconds or minute
                {
                    data.Length = Int32.Parse(attr.Value);
                }
                else if ((attr = xml.Attribute(MINUTE_ATTR)) != null)
                {
                    string str     = attr.Value.Replace('.', ',');
                    double minutes = Double.Parse(str); // can be in xx.yy format ...
                    data.Length = ((int)minutes) * 60;
                }

                if ((attr = xml.Attribute(ARTIST_ATTR)) != null) // getting artist name
                {
                    data.Artist = attr.Value;
                }

                if ((attr = xml.Attribute(YEAR_ATTR)) != null) // getting year
                {
                    data.Year = attr.Value;
                }

                if ((attr = xml.Attribute(CODEC_ATTR)) != null) // if video getting codec
                {
                    data.Codec = attr.Value;
                }
                if ((attr = xml.Attribute(DESCR_ATTR)) != null)
                {
                    data.Description = attr.Value;
                }
            }
            catch (Exception e)
            {
                G2Log.Write("ERROR Parsing metadata " + xmlString + "\n" + e.ToString());
            }
            return(data);
        }
コード例 #6
0
 public bool Connect()
 {
     try {
         sock.Connect(new IPEndPoint(peer.Address, (int)peer.Port));
     } catch (Exception e) {
         G2Log.Write("TCP " + peer.ToString() + " => " + e.ToString());
         return(false);
     }
     return(true);
 }
コード例 #7
0
 /**
  * Push a packet to the buffer to be sent by the connection of the peer
  * */
 public void PushPacketToSend(G2Packet pack)
 {
     lock (SendBuffer) {
         SendBuffer.Enqueue(pack);
         var type = pack.packetHeader.type;
         type += pack.type == G2PacketType.DEFAULT ? " (unknown) " : "";
         G2Log.Write("PacketBuffer : Enqueued packet " + type + " to send to " + pack.RemotePeer.ToString());
         Monitor.Pulse(SendBuffer);
     }
 }
コード例 #8
0
        /**
         * Send the request to connected hubs .
         * */
        private void DispatchRequest(G2PacketQ2 pack)
        {
            int      count = 0;
            NodePeer hub   = null;

            while (count < Settings.PEER_DISPATCH_QUERY)
            {
                hub = G2Network.Instance.getQueryableHub();
                hub.DontQueryBefore(Settings.SEARCH_TIME_OUT_MS);
                hub.SendPacket(pack);
                G2Log.Write("G2SearchManager : Sent Query " + getTermsByGUID(pack.guid) + " on " + hub.ToString());
                count++;
            }
        }
コード例 #9
0
ファイル: TCPClient.cs プロジェクト: nikkolasg/gnutella2
        private bool sendIdentity(ByteBuffer b)
        {
            bool ret = true;

            try{
                stream.Write(b.Bytes, 0, b.DataOffset);
            } catch (IOException e) {
                G2Log.Write("ERROR TCPConnection : sendIdentity " + e.ToString());
                ret = false;
            } catch (Exception e) {
                G2Log.Write("ERROR TCPConnection : unknow error " + e.ToString());
                ret = false;
            }
            return(ret);
        }
コード例 #10
0
 private void SearchResultThread()
 {
     while (ContinueRegrouping)
     {
         // take a packet from the buffer
         G2PacketQH2 resultPack = PollResultPacket();
         if (resultPack == null)
         {
             continue;
         }
         // append it to the global result of this search
         AppendResult(resultPack);
     }
     G2Log.Write("SearchResult (" + SearchedWord + ") STOPPING .....");
 }
コード例 #11
0
ファイル: G2BrowseSearch.cs プロジェクト: nikkolasg/gnutella2
        public void StartBrowsing()
        {
            TCPConnection con = TCPConnection.getPeerConnection(Peer);

            if (!con.Connect())
            {
                G2Log.Write("G2BrowseSearch could not connect to Peer " + this.Peer.ToString());
                if (EndSearch != null)
                {
                    EndSearch(referenceToPeer, referenceToSearchResults, packetResults);
                }
                return;
            }
            if (!SendHttpRequest(con))
            {
                if (EndSearch != null)
                {
                    EndSearch(referenceToPeer, referenceToSearchResults, packetResults);
                }
                Peer.Close();
                return;
            }

            bool streaming = ReadResponseHeader(con);

            if (!streaming)
            {
                if (EndSearch != null)
                {
                    EndSearch(referenceToPeer, referenceToSearchResults, packetResults);
                }
                Peer.Close();
                return;
            }

            // start to  read the flow of packets
            this.Peer.connection = new HubSocket(this.Peer, con.sock, reader);
            this.Peer.connection.Start();


            G2Log.Write("G2BrowseSearch : browsing peer " + Peer.ToString() + " ...");
            SearchTimer           = new Timer(Settings.WAIT_TIME_BROWSING_MS);
            SearchTimer.Elapsed  += new ElapsedEventHandler(SearchTimeOut);
            SearchTimer.AutoReset = false;

            SearchTimer.Start();
        }
コード例 #12
0
ファイル: TCPClient.cs プロジェクト: nikkolasg/gnutella2
        private bool sendDeflate(ByteBuffer b)
        {
            bool ret = true;

            using (DeflateStream deflate = new DeflateStream(stream, CompressionMode.Compress, true)) {
                try {
                    deflate.Write(b.Bytes, 0, b.DataOffset);
                } catch (IOException e) {
                    G2Log.Write("ERROR TCPConnection : can not write deflate, " + e.ToString());
                    ret = false;
                } catch (Exception e) {
                    G2Log.Write("ERROR TCPConnection : unknown error writing deflate " + e.ToString());
                    ret = false;
                }
            }
            return(ret);
        }
コード例 #13
0
ファイル: TCPClient.cs プロジェクト: nikkolasg/gnutella2
        public ByteBuffer readIdentity()
        {
            int byteRead = 0;

            byte[]     bytes = new byte[BUFF_SIZE];
            ByteBuffer b     = new ByteBuffer(bytes);

            try{
                byteRead     = stream.Read(bytes, 0, bytes.Length);
                b.DataOffset = byteRead;
            }catch (IOException e) {
                G2Log.Write("ERROR TCPConnection : readIdentity " + e.ToString());
                return(null);
            } catch (Exception e) {
                G2Log.Write("ERROR TCPConnection : readIdentity Unknown Exception " + e.ToString());
                return(null);
            }
            return(b);
        }
コード例 #14
0
ファイル: NodePeer.cs プロジェクト: nikkolasg/gnutella2
 public void PingTimerOut(Object sender, EventArgs e)
 {
     // Peers doesn't respond to our ping , so we close the connection
     if (closed || LastPing.AddMilliseconds(MAX_PING_ATTEMPT * PING_TIMEOUT_MS) < DateTime.Now)
     {
         G2Log.Write("PEER Does not respond ... Disconnecting");
         PingTimer.AutoReset = false;
         PingTimer.Enabled   = false;
         PingTimer.Stop();
         GHubCache.Instance.RemoveConnectedHub(this);
     }
     else
     {
         // Here are two cases :
         // 1 - we just send a new ping to assure us that peer is still up
         // 2 - we still leave some time to the peer to respond to a previous ping packet
         SendPacket(new G2PacketPI());
     }
 }
コード例 #15
0
        /**
         * Check incoming data from socket every time and push it
         * into buffer if data present
         * */
        public void ReceiveThread()
        {
            byte[] buffer = new byte[BUFF_SIZE];
            // ShutdownEvent is a ManualResetEvent signaled by
            // Client when its time to close the socket.
            var count = 0;

            while (!shouldStop_)
            {
                try
                { count++;
                  // We could use the ReadTimeout property and let Read()
                  // block.  However, if no data is received prior to the
                  // timeout period expiring, an IOException occurs.
                  // While this can be handled, it leads to problems when
                  // debugging if we are wanting to break when exceptions
                  // are thrown (unless we explicitly ignore IOException,
                  // which I always forget to do).
                  if (!stream.DataAvailable)
                  {
                      // Give up the remaining time slice.
                      Thread.Sleep(10);
                  }
                  else
                  {
                      int bRead = stream.Read(buffer, 0, buffer.Length);                           // see if something is there
                      if (bRead > 0)
                      {
                          //G2Log.Write("HubSocket: Received " + bRead + " bytes !");
                          Reader.Read(buffer, bRead);
                          buffer = new byte[BUFF_SIZE];
                      }
                      else
                      {
                          G2Log.Write("HubSocket: Connection killed ? " + this.peer.ToString());                               // connection closed
                      }
                  } }
                catch (IOException ex)
                {
                    G2Log.Write("ReceiveThread exception : " + ex.ToString());
                }
            }
        }
コード例 #16
0
ファイル: Datagrams.cs プロジェクト: nikkolasg/gnutella2
        public void ReceiveThread()
        {
            IPEndPoint any = new IPEndPoint(IPAddress.Any, 0);

            byte[] bytes;
            while (true)
            {
                try{
                    bytes = udp.Receive(ref any);
                    if (bytes.Length > 0)
                    {
                        G2Log.Write("UDP : Received " + bytes.Length + " bytes ...");
                        //StorePacket (bytes, any);
                        bytes = new byte[BUFF_SIZE];
                    }
                    Thread.Sleep(1);
                } catch (IOException e) {
                    G2Log.Write("Datagrams: Receive : " + e.ToString());
                }
            }
        }
コード例 #17
0
        /**
         * Get the results from browsing and put it into the sharedFileList folder of the peer.
         * Should maybe change the key to a Peer , but since implementation is unknown
         * no assurance that hashcode will be the same ...
         * */
        public void BrowsingTerminated(Peer peer, SearchResult Results, List <G2PacketQH2> resultPackets)
        {
            if (resultPackets.Count == 0)
            {
                RegroupResults(Results); // if no results from browsing directly sends results
                return;
            }
            Results.PeerCollection.Add(peer);
            Peer p = Results.PeerCollection.Find(peer);


            int fileCount = 0;

            // add results !!
            foreach (G2PacketQH2 qh2 in resultPackets)
            {
                foreach (G2Packet child in qh2.children)
                {
                    if (!child.type.Equals(G2PacketType.H))
                    {
                        continue;
                    }
                    G2PacketH hit  = child as G2PacketH;
                    G2File    file = G2File.ParseHit(hit, FileLocationFound.SharedLocalComputer);
                    if (file == null)
                    {
                        continue;
                    }
                    p.SharedLocalfilesList.Add(file);
                    file.PeerDiffusedFiles.Add(p);
                    SharedTotalFiles++;
                    fileCount++;
                }
            }

            G2Log.Write("SearchResults : New Browsing Result from " + p.Ip + ":" + p.Port + " ==> " + p.Files.Count + " files && " + p.SharedLocalfilesList.Count + " shared files ...");

            RegroupResults(Results);
        }
コード例 #18
0
 /**
  * Take a search related packets i.e. QA (ack) or QH2 (hit)
  * and stores it into SearchResults class
  * */
 public void EnqueueResultPacket(NodePeer p, G2Packet pack)
 {
     // a hub packet ACK a query
     if (pack.type == G2PacketType.QA)
     {
         G2PacketQA      qa     = pack as G2PacketQA;
         G2SearchResults res    = null;
         bool            exists = SearchResults.TryGetValue(qa.guid, out res);
         if (!exists)  // no entry => not a search we initiated
         {
             G2Log.Write("G2SearchManager : Received ACK of non asked Query");
         }
         else
         {
             res.SetAcknowledgement(qa);
             G2Log.Write("G2SearchManager Received ACK of search " + SearchDB[qa.guid].Keywords[0]);
         }
     }
     // Hit packet !
     else if (pack.type == G2PacketType.QH2)
     {
         G2PacketQH2     qh2    = pack as G2PacketQH2;
         G2SearchResults res    = null;
         bool            exists = SearchResults.TryGetValue(qh2.searchGuid, out res);
         if (exists)
         { // a new result packet coming for a requested query
             res.PushResultPacket(qh2);
             //if (res.TotalFiles > MAX_RESULTS)
             //    G2Network.Instance.StopNetwork();
         }
         else // got a response for a query we did not ask ?
         {
             G2Log.Write("G2SearchManager : Received a Hit on a NON ASKED Query");
         }
     }
 }
コード例 #19
0
ファイル: NodePeer.cs プロジェクト: nikkolasg/gnutella2
 /* Becomes queriable again
  * */
 private void QueryStop(Object sender, EventArgs e)
 {
     isQueryable_ = true;
     SearchTimer.Stop();
     G2Log.Write(this.ToString() + " is queryable free again ...");
 }
コード例 #20
0
ファイル: HttpHeader.cs プロジェクト: nikkolasg/gnutella2
        public static HttpHeader ParseHandshake(string msg)
        {
            HttpHeader headers = new HttpHeader();
            Match      regex;

            regex = Regex.Match(msg, @"^(GNUTELLA)/(\d\.\d) (\d{3})", RegexOptions.Multiline | RegexOptions.IgnoreCase);
            if (!regex.Success)
            {
                throw new HeaderException("No match for client/version/code");
            }

            headers[PROTOCOL_KEY]         = regex.Groups [1].Value;
            headers[PROTOCOL_VERSION_KEY] = regex.Groups [2].Value;
            headers[PROTOCOL_CODE_KEY]    = regex.Groups [3].Value;

            if (regex.Groups [3].Value.Equals("503"))
            {
                G2Log.Write("ParseHandshake HttpHeader : 503 Code found !");
                ParseTryHub(msg, headers);
                return(headers);
            }

            // is hub check
            regex = Regex.Match(msg, @"(X-Hub|X-Ultrapeer): (True|False)", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            if (!regex.Success)
            {
                throw new HeaderException("No match for hub detection");
            }


            bool _isHub = regex.Groups [2].Value.Equals("True") ? true : false;

            headers[IS_HUB_KEY] = regex.Groups [2].Value;
            // it is a leaf
            if (!_isHub)
            {
                ParseTryHub(msg, headers);
            }
            // it is a hub
            else
            {
                // retrieve hub's ip + port
                regex = Regex.Match(msg, @"^Listen-IP: (.*:.*)$", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                if (regex.Success)
                {
                    var info = regex.Groups [1].Value;
                    headers[LISTEN_IP_KEY]   = info.Split(':') [0];
                    headers[LISTEN_PORT_KEY] = info.Split(':') [1];
                }
                else
                {
                    throw new HeaderException("HttpHeader : hub ip / port not found.");
                }

                ParseEncoding(msg, headers);

                // retrieve our self ip
                regex = Regex.Match(msg, @"Remote-IP: (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                if (!regex.Success)
                {
                    throw new HeaderException("HttpHeader : Parsing remote ip failed");
                }
                headers[REMOTE_IP_KEY] = regex.Groups [1].Value;
            }

            // content-type check
            regex = Regex.Match(msg, @"Content-Type: (.*)", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            if (!regex.Success)
            {
                G2Log.Write("ERROR HttpHeader : No Content Type Found");
            }
            var contentType = regex.Groups [1].Value.TrimEnd('\r', '\n');

            if (!contentType.Equals(CONTENT_TYPE_G2_VALUE))
            {
                throw new HeaderException("HttpHeader : Content Type error comparing :\n" + regex.Groups [1].Value + " vs " + CONTENT_TYPE_G2_VALUE);
            }
            else
            {
                headers [CONTENT_TYPE_KEY] = contentType;
            }

            return(headers);
        }
コード例 #21
0
 /**
  * Simply start the analytic thread and the timer
  * */
 public void StartSearchResult()
 {
     StopSearchTimer.Start();
     RegroupingThread.Start();
     G2Log.Write("G2Search Result (" + SearchedWord + ") => STARTING....");
 }
コード例 #22
0
        private void AppendResult(G2PacketQH2 res)
        {
            G2Peer g2peer = G2Peer.ParseG2Peer(res);

            if (g2peer == null)
            {
                return;
            }

            /** Create a new search result from the hub ip  and the search transaction */
            SearchResult Results = new SearchResult(new System.Net.IPEndPoint(res.RemotePeer.Address, res.RemotePeer.Port), Transaction);

            bool          PeerBrowsable = false;
            bool          isFirewalled  = false;
            int           fileCount     = 0;
            List <G2File> files         = new List <G2File>();

            // add the files to the collections.
            foreach (G2Packet child in res.children)
            {
                if (child.type.Equals(G2PacketType.BH))
                {
                    PeerBrowsable = true;
                    continue;
                }
                if (child.type.Equals(G2PacketType.FW))
                {
                    isFirewalled = true;
                    continue;
                }
                if (!child.type.Equals(G2PacketType.H))
                {
                    continue;
                }


                G2PacketH hit  = child as G2PacketH;
                G2File    file = G2File.ParseHit(hit, FileLocationFound.ServerIndex);
                if (file == null)
                {
                    continue;
                }
                files.Add(file);

                fileCount += 1;
            }
            if (fileCount == 0)
            {
                return;                 // may have some hosts having only partial file,so no file for the application ...
            }
            Results.PeerCollection.Add(g2peer);
            Peer p = Results.PeerCollection.Find(g2peer); // to get the right object reference may not be needed .. ?

            if (p.Ip.StartsWith("192.168"))
            {
                return;
            }
            foreach (G2File file in files)
            {
                p.Files.Add(file);
                file.PeerDiffusedFiles.Add(p); // ?? necessary or wrong ?
                Results.FileCollection.Add(file);
            }
            files.Clear();
            files = null;

            TotalFiles += fileCount;


            G2Log.Write("SearchResults : New result from " + res.RemotePeer.ToString() + " for " + SearchedWord + " ==> " + fileCount + " files");

            // try to see if we already have launched an browsing research on this peer or not
            bool notAlreadySearched = !PeersBrowsed.Contains(p);
            // make sure that the browsing will not increase the waiting time of the application for the result
            bool notTooLate = StartSearchTime.AddMilliseconds(Settings.WAIT_TIME_BROWSING_MS)
                              < StartSearchTime.AddMilliseconds(Settings.SEARCH_TIME_OUT_MS + 100); // +100 to make sure browsing has time to regroup all
            bool notConnectedHub = res.RemotePeer.Address.ToString() != p.Ip;

            // verify that we dont search the hub, taht the peer is browsable and NOT firewalled
            // TODO can send a PUSH packet to the hub that will bring the peer to establish a connection to us
            if (notConnectedHub && PeerBrowsable && !isFirewalled && notAlreadySearched && notTooLate)
            {
                PeersBrowsed.Add(p);
                G2BrowseSearch browser = new G2BrowseSearch(p, Results);
                browser.EndSearch += new BrowseSearchEnd(BrowsingTerminated);
                browser.StartBrowsing();
            }
            else // sends results to application
            {
                RegroupResults(Results);
            }
        }
コード例 #23
0
        public override int ReadPayload(System.IO.MemoryStream stream, int length)
        {
            int bread = base.ReadPayload(stream, length);

            this.profile = new G2UserProfile();
            try
            {
                XElement   xml   = XElement.Parse(base.Str);
                XElement   child = null;
                XAttribute attr  = null;

                child = xml.Element("gnutella"); // get GUID
                if (child != null)
                {
                    profile.Guid = new GUID(child.Value);
                }
                child = null;

                child = xml.Element("identity");
                if (child != null)
                {
                    attr = child.Element("handle").Attribute("primary"); // get nickname
                }
                if (attr != null)
                {
                    profile.Nickname = attr.Value;
                }
                attr = null;

                child = xml.Element("identity");
                if (child != null)
                {
                    child = child.Element("name");
                    if (child != null)
                    {
                        attr = child.Attribute("first"); // get first name
                        if (attr != null)
                        {
                            profile.FirstName = attr.Value;
                        }
                        attr = null;
                        attr = child.Attribute("last"); // get last name
                        if (attr != null)
                        {
                            profile.LastName = attr.Value;
                        }
                        attr  = null;
                        child = null;
                    }
                }
                child = xml.Element("location");
                if (child != null)
                {
                    child = child.Element("political");
                    if (child != null)
                    {
                        attr = child.Attribute("city"); // get city
                        if (attr != null)
                        {
                            profile.City = attr.Value;
                        }

                        attr = child.Attribute("country"); // getcountry
                        if (attr != null)
                        {
                            profile.Country = attr.Value;
                        }
                    }
                }
            } catch (Exception e) {
                G2Log.Write("UPROD parsing " + base.Str + " : " + e.ToString());
            }
            return(bread);
        }