// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } var log = new InMemoryLog(); var fsm = new InMemoryStateMachine(); var settings = new InMemorySettings(1000, 3500, 50, 5000); var _peers = new List <IPeer>(); var peer1 = new NodePeer(); _peers.Add(new NodePeer() { }); var peersProvider = new InMemoryPeersProvider(_peers); var node = new Node(fsm, log, settings, peersProvider, loggerFactory); node.Start(new NodeId("gsw" + DateTime.Now.ToString("HHmmssfff"))); app.UseMvc(); }
/** * 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); }
/** * 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"); } }
public Runtime(Lazy <ICommunicationService> communicationService, Lazy <IRuntimeService> runtimeService, RuntimeType runtimeType, NodePeer enginePeer) { if (communicationService == null) { throw new ArgumentNullException(); } if (runtimeService == null) { throw new ArgumentNullException(); } if (runtimeType == null) { throw new ArgumentNullException(); } if (enginePeer == null) { throw new ArgumentNullException(); } m_Type = runtimeType; m_Peer = enginePeer; m_communicationService = communicationService; m_runtimeService = runtimeService; }
/** 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); }
/** 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() + " ... "); } }
/** * Add a hub to the global hub cache * */ public void AddHub(NodePeer hub) { lock (HubCache_) { bool added = HubCache_.Add(hub); EnsureHubCache(); } }
/** * 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()); } }
public bool isConnected(NodePeer peer) { bool ret = false; lock (ConnectedHub_) { ret = ConnectedHub_.Contains(peer); } return(ret); }
void peer_OnReceive(NodePeer FromPeer, NodeBase Message) { IRuntime runtime = getRelationship(FromPeer); if (runtime != null) { runtime.MessageReceivedFromPeer(Message); } }
private G2Packet HandlePacketUPROC(NodePeer p, G2PacketUPROC pack) { G2UserProfile profile = Settings.SmartUserProfile(); G2Packet resp = new G2PacketUPROD(); resp.AddChild(new G2PacketXML(profile)); resp.FinalizePacket(); return(resp); }
private void setRelationship(NodePeer peer, IRuntime runtime) { lock (m_runtimeLookup_Lock) { if (!m_runtimeLookup.ContainsKey(peer)) { m_runtimeLookup.Add(peer, runtime); } } }
internal void SetLocalRuntimePeer(NodePeerList list) { foreach (var peer in list.Peers) { if (peer.Code.ToString() == Engine.PEER_CODE) { localRuntimePeer = peer; break; } } }
NodeBase peer_OnReceiveDelta(NodePeer FromPeer, FieldGuid BasedOnMessageID) { NodeBase originalMessage = null; IRuntime runtime = getRelationship(FromPeer); if (runtime != null) { originalMessage = runtime.DeltaReceivedFromPeer(BasedOnMessageID); } return(originalMessage); }
private G2Packet HandlePacketPI(NodePeer p, G2PacketPI pack) { p.ResetPingTimer(); G2Packet udp = pack.getFirstChildPacket(G2PacketType.UDP); G2Packet response = new G2PacketPO(); // PING relayed but we dont act as hub for now if (udp != null) { } response.FinalizePacket(); return(response); }
private IRuntime getRelationship(NodePeer peer) { IRuntime runtime = null; lock (m_runtimeLookup_Lock) { if (m_runtimeLookup.ContainsKey(peer)) { runtime = m_runtimeLookup[peer]; } } return(runtime); }
public HubSocket(NodePeer p,Socket c) { this.peer = p; this.sock = c; this.stream = new NetworkStream (c, true); SetupSocketOptions (); this.Reader = new G2PacketReader (p); this.shouldStop_ = false; Receiver = new Thread (new ThreadStart (ReceiveThread)); Sender = new Thread (new ThreadStart (SendThread)); Receiver.Name = "HubSocket Receiver " + p.Address.ToString(); Sender.Name = "HubSocket Sender " + p.Address.ToString(); }
private const int JOIN_WAIT_TIME = 50; // ms public HubSocket(NodePeer p, Socket c) { this.peer = p; this.sock = c; this.stream = new NetworkStream(c, true); SetupSocketOptions(); this.Reader = new G2PacketReader(p); this.shouldStop_ = false; Receiver = new Thread(new ThreadStart(ReceiveThread)); Sender = new Thread(new ThreadStart(SendThread)); Receiver.Name = "HubSocket Receiver " + p.Address.ToString(); Sender.Name = "HubSocket Sender " + p.Address.ToString(); }
public static void TestNetwork() { G2Network network = G2Network.Instance; network.StartNetwork (); NodePeer p = new NodePeer (IPAddress.Parse ("127.0.0.1"), 11000,0,false); Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); s.Connect (p.Address, p.Port); GHandshake hand = new GHandshake (p); hand.tcp.sock = s; p.AttachTo (hand); Thread.Sleep (10000); network.StopNetwork (); }
/** * Centralized connections with all peers * Get an existing connection * OR create one and register it with the peer * */ public static TCPConnection getPeerConnection(NodePeer p) { TCPConnection con; Sock.TryGetValue(p, out con); if (con != null) { return(con); } con = new TCPConnection(p.Address, p.Port); Sock.Add(p, con); return(con); }
/** * 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++; } }
public G2BrowseSearch(Peer peerToBrowse,SearchResult results) { referenceToPeer = peerToBrowse; referenceToSearchResults = results; IPAddress add = null; bool succ = IPAddress.TryParse(peerToBrowse.Ip, out add); Peer = new NodePeer(new NodeAddress(add, (ushort)peerToBrowse.Port),false); Peer.isHub = false; packetResults = new List<G2PacketQH2>(); reader = null; }
public static void TestNetwork() { G2Network network = G2Network.Instance; network.StartNetwork(); NodePeer p = new NodePeer(IPAddress.Parse("127.0.0.1"), 11000, 0, false); Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); s.Connect(p.Address, p.Port); GHandshake hand = new GHandshake(p); hand.tcp.sock = s; p.AttachTo(hand); Thread.Sleep(10000); network.StopNetwork(); }
private SearchResult referenceToSearchResults; // g2 search results public G2BrowseSearch(Peer peerToBrowse, SearchResult results) { referenceToPeer = peerToBrowse; referenceToSearchResults = results; IPAddress add = null; bool succ = IPAddress.TryParse(peerToBrowse.Ip, out add); Peer = new NodePeer(new NodeAddress(add, (ushort)peerToBrowse.Port), false); Peer.isHub = false; packetResults = new List <G2PacketQH2>(); reader = null; }
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); } }
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); } }
/** * Parse the neighbours hubs contained in this packet * and adds them to the cache * */ private G2Packet HandlePacketKHL(NodePeer p, G2PacketKHL pack) { foreach (G2Packet child in pack.children) { if (child.type != G2PacketType.NH) { continue; } G2PacketNH nh = child as G2PacketNH; if (nh != null && nh.node != null) { GHubCache.Instance.AddHub(new NodePeer(nh.node, true)); } } return(null); }
private G2Packet HandlePacketLNI(NodePeer peer, G2PacketLNI pack) { G2Packet p = pack.getFirstChildPacket(G2PacketType.NA); if (p != null) { peer.ListeningNode = ((G2PacketNA)p).node; } p = pack.getFirstChildPacket(G2PacketType.GU); if (p != null) { peer.Guid = ((G2PacketGU)p).nodeGuid; } // can handle vendor code etc etc return(null); }
// parse the many hubs data there are in a ack packet private G2Packet HandlePacketQA(NodePeer p, G2PacketQA pack) { foreach (G2Packet child in pack.children) { if (child.type == G2PacketType.S) // search hubs data { G2PacketS s = child as G2PacketS; if (s == null) { continue; } if (s.Timestamp != -1) { DateTime lastSeen = BinaryUtils.UnixTimeStampToDateTime(s.Timestamp); cache.AddHub(new NodePeer(s.Node.ipv4, s.Node.port, lastSeen, true)); } else { cache.AddHub(new NodePeer(s.Node.ipv4, s.Node.port, DateTime.Now, true)); } } else if (child.type == G2PacketType.RA) { G2PacketRA ra = child as G2PacketRA; if (ra == null || ra.Seconds == 0) { continue; } p.DontQueryBefore(ra.Seconds * 1000); } else if (child.type == G2PacketType.D) { G2PacketD d = child as G2PacketD; if (d.Node != null) { cache.AddHub(new NodePeer(d.Node, true)); } } } return(null); }
private void HandleHub(HttpHeader header) { IPAddress _listen_ip = IPAddress.Parse(header[HttpHeader.LISTEN_IP_KEY]); ushort _listen_port = Convert.ToUInt16(header[HttpHeader.LISTEN_PORT_KEY]); string encoding = header[HttpHeader.ACCEPT_ENCODING_KEY]; string _remote_ip = header[HttpHeader.REMOTE_IP_KEY]; GHubCache cache = GHubCache.Instance; IPAddress self = IPAddress.Parse(_remote_ip); G2Network.Instance.SelfAddress = self; if (_listen_ip != null && _listen_port > 0 && _listen_port < 65000) { remote_host = new NodePeer(_listen_ip, _listen_port, DateTime.Now.ToString(), true); } }
public G2Packet HandlePacket(NodePeer p, G2Packet pack) { switch (pack.type) { case G2PacketType.PI: return HandlePacketPI(p, pack as G2PacketPI); case G2PacketType.UPROC: return HandlePacketUPROC(p, pack as G2PacketUPROC); case G2PacketType.LNI: return HandlePacketLNI(p, pack as G2PacketLNI); case G2PacketType.KHL: return HandlePacketKHL(p, pack as G2PacketKHL); case G2PacketType.QA: return HandlePacketQA(p, pack as G2PacketQA); default: return HandleDefault(p, pack); } }
/** * CHeck incoming message for this peer, and push a response if needed * */ private void OnNewMessage(NodePeer p) { G2Packet pack = null; G2Packet response = null; while ((pack = p.Buffer.PollPacketToReceive()) != null) { response = HandlePacket(p, pack); // network related packets (ping/pong/etc) if (response != null) { p.SendPacket(response); response = null; } if (pack.type == G2PacketType.QA || pack.type == G2PacketType.QH2) {// search related packets SearchManager.EnqueueResultPacket(p, pack); continue; } pack = null; } }
public G2Packet HandlePacket(NodePeer p, G2Packet pack) { switch (pack.type) { case G2PacketType.PI: return(HandlePacketPI(p, pack as G2PacketPI)); case G2PacketType.UPROC: return(HandlePacketUPROC(p, pack as G2PacketUPROC)); case G2PacketType.LNI: return(HandlePacketLNI(p, pack as G2PacketLNI)); case G2PacketType.KHL: return(HandlePacketKHL(p, pack as G2PacketKHL)); case G2PacketType.QA: return(HandlePacketQA(p, pack as G2PacketQA)); default: return(HandleDefault(p, pack)); } }
/** * 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"); } } }
public HubSocket(NodePeer p, Socket c, G2PacketReader packetReader) : this(p,c) { this.Reader = packetReader; }
private NodePeer peer; // Peer to which packets arrives #endregion Fields #region Constructors public G2PacketReader(NodePeer p) { peer = p; Buffer = new ByteBuffer(); }
private G2Packet HandlePacketUPROC(NodePeer p, G2PacketUPROC pack) { G2UserProfile profile = Settings.SmartUserProfile(); G2Packet resp = new G2PacketUPROD(); resp.AddChild(new G2PacketXML(profile)); resp.FinalizePacket(); return resp; }
// to be called when reading packet from stream public G2Packet(Header h) { this.children = new List<G2Packet> (); this.packetHeader = h; RemotePeer = null; }
/** * Centralized connections with all peers * Get an existing connection * OR create one and register it with the peer * */ public static TCPConnection getPeerConnection(NodePeer p) { TCPConnection con; Sock.TryGetValue(p,out con); if(con != null) return con; con = new TCPConnection(p.Address,p.Port); Sock.Add(p,con); return con; }
/** * CHeck incoming message for this peer, and push a response if needed * */ private void OnNewMessage(NodePeer p) { G2Packet pack = null; G2Packet response = null; while ((pack = p.Buffer.PollPacketToReceive ()) != null) { response = HandlePacket (p,pack); // network related packets (ping/pong/etc) if(response != null) { p.SendPacket (response); response = null; } if (pack.type == G2PacketType.QA || pack.type == G2PacketType.QH2) {// search related packets SearchManager.EnqueueResultPacket(p, pack); continue; } pack = null; } }
// parse the many hubs data there are in a ack packet private G2Packet HandlePacketQA(NodePeer p, G2PacketQA pack) { foreach (G2Packet child in pack.children) { if(child.type == G2PacketType.S) // search hubs data { G2PacketS s = child as G2PacketS; if(s == null) continue; if(s.Timestamp != -1) { DateTime lastSeen = BinaryUtils.UnixTimeStampToDateTime(s.Timestamp); cache.AddHub(new NodePeer(s.Node.ipv4, s.Node.port,lastSeen,true)); } else cache.AddHub(new NodePeer(s.Node.ipv4, s.Node.port,DateTime.Now, true)); } else if(child.type == G2PacketType.RA) { G2PacketRA ra = child as G2PacketRA; if (ra == null || ra.Seconds == 0) continue; p.DontQueryBefore(ra.Seconds * 1000); } else if (child.type == G2PacketType.D) { G2PacketD d = child as G2PacketD; if (d.Node != null) cache.AddHub(new NodePeer(d.Node, true)); } } return null; }
public void RemoveHub(NodePeer hub) { lock (HubCache_) { bool succ = HubCache_.Remove (hub); } }
/** 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() + " ... "); } }
public bool isConnected(NodePeer peer) { bool ret = false; lock (ConnectedHub_) { ret = ConnectedHub_.Contains (peer); } return ret; }
public void AddConnectedHub(NodePeer p) { lock (connectedHubs) { connectedHubs.Add (p); } }
public void AddHub(NodePeer h) { HubList.Add(h); }
public void RemoveHub(NodePeer h) { HubList.Remove(h); }
// tells if we have found a hub ready to connect or not public GHandshake(NodePeer remoteHost) { this.remote_host = remoteHost; tcp = TCPConnection.getPeerConnection(remoteHost); Encoding = HttpHeader.ENCODING_IDENTITY; }
public void RemoveHub(NodePeer hub) { lock (HubCache_) { bool succ = HubCache_.Remove(hub); } }
private void HandleHub(HttpHeader header) { IPAddress _listen_ip = IPAddress.Parse (header[HttpHeader.LISTEN_IP_KEY]); ushort _listen_port = Convert.ToUInt16 (header[HttpHeader.LISTEN_PORT_KEY]); string encoding = header[HttpHeader.ACCEPT_ENCODING_KEY]; string _remote_ip = header[HttpHeader.REMOTE_IP_KEY]; GHubCache cache = GHubCache.Instance; IPAddress self = IPAddress.Parse(_remote_ip); G2Network.Instance.SelfAddress = self; if (_listen_ip != null && _listen_port > 0 && _listen_port < 65000) { remote_host = new NodePeer (_listen_ip, _listen_port, DateTime.Now.ToString (), true); } }
public static bool CloseConnection(NodePeer p) { getPeerConnection(p).Close(); return Sock.Remove(p); }
public void RemoveConnectedHub(NodePeer p) { lock (connectedHubs) { connectedHubs.Remove (p); } }
// to be called when creating a new packet public G2Packet() { children = new List<G2Packet>(); packetHeader = null; RemotePeer = null; }
private G2Packet HandlePacketLNI(NodePeer peer,G2PacketLNI pack) { G2Packet p = pack.getFirstChildPacket(G2PacketType.NA); if (p != null) peer.ListeningNode = ((G2PacketNA)p).node; p = pack.getFirstChildPacket(G2PacketType.GU); if (p != null) peer.Guid = ((G2PacketGU)p).nodeGuid; // can handle vendor code etc etc return null; }
public void SendDeltaToPeer(IRuntime fromRuntime, NodePeer toPeer, NodeBase message, NodeBase basedOnMessage) { setRelationship(toPeer, fromRuntime); peer.SendDeltaToPeer(toPeer, message, basedOnMessage); }
/** * Analyse packet and return a packet to send (if there is one) * or null * */ private G2Packet HandleDefault(NodePeer p,G2Packet pack) { return null; }
/** * 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 ()); } }
/** * Parse the neighbours hubs contained in this packet * and adds them to the cache * */ private G2Packet HandlePacketKHL(NodePeer p, G2PacketKHL pack) { foreach (G2Packet child in pack.children) { if (child.type != G2PacketType.NH) continue; G2PacketNH nh = child as G2PacketNH; if (nh != null && nh.node != null) { GHubCache.Instance.AddHub(new NodePeer(nh.node,true)); } } return null; }
/** * Add a hub to the global hub cache * */ public void AddHub(NodePeer hub) { lock(HubCache_) { bool added = HubCache_.Add (hub); EnsureHubCache (); } }
private G2Packet HandlePacketPI(NodePeer p,G2PacketPI pack) { p.ResetPingTimer(); G2Packet udp = pack.getFirstChildPacket(G2PacketType.UDP); G2Packet response = new G2PacketPO(); // PING relayed but we dont act as hub for now if (udp != null) { } response.FinalizePacket(); return response; }