Exemple #1
0
        public bool SendPacket(G2Packet packet)
        {
            if (Core.InvokeRequired)
            {
                Debug.Assert(false);
            }

            byte[] final = packet.Encode(Network.Protocol);

            if (Comm.State != RudpState.Connected)
            {
                return(false);
            }

            PacketLogEntry logEntry = new PacketLogEntry(Core.TimeNow, TransportProtocol.Rudp, DirectionType.Out, Comm.PrimaryAddress.Address, final);

            Core.Network.LogPacket(logEntry);

            // dont worry about buffers, cause initial comm buffer is large enough to fit all negotiating packets
            if (SendEncryptor == null)
            {
                int length = final.Length;
                Comm.Send(final, ref length);
                return(true);
            }

            // goal - dont fill encrypt buffer because it will block stuff like pings during transfers
            // use as temp, return failed if no room

            if (SendBuffer == null)
            {
                SendBuffer = new byte[BUFF_SIZE];
            }

            if (EncryptBuffer == null)
            {
                EncryptBuffer = new byte[BUFF_SIZE];
            }

            LastSends.Enqueue(new Tuple <int, int>(EncryptBuffSize, final.Length));
            if (LastSends.Count > 100)
            {
                LastSends.Dequeue();
            }

            // ensure enough space in encrypt buff for packet and expedite packets
            if (BUFF_SIZE - EncryptBuffSize < final.Length + 128)
            {
                throw new Exception("Packet Dropped");
            }

            // encode put into send buff
            lock (SendBuffer)
            {
                final.CopyTo(SendBuffer, SendBuffSize);
                SendBuffSize += final.Length;
            }

            return(FlushSend()); // return true if room in comm buffer
        }
Exemple #2
0
        public void SendReliable(DhtClient client, uint service, int type, G2Packet packet, bool expedite)
        {
            if (!Clients.ContainsKey(client.RoutingID))
            {
                return;
            }

            RudpPacket comm = CreateRudpPacket(client, service, type, packet, true);

            LightClient target = Clients[client.RoutingID];

            if (expedite)
            {
                target.NextTry = Core.TimeNow;
                target.Packets.AddFirst(new Tuple <uint, RudpPacket>(service, comm));
                target.TrySend(Network);
                return;
            }

            Active[client.RoutingID] = target;

            target.Packets.AddLast(new Tuple <uint, RudpPacket>(service, comm));
            while (target.Packets.Count > 30)
            {
                //crit - log to console? Debug.Assert(false);
                target.Packets.RemoveFirst();
            }

            target.TrySend(Network);
        }
Exemple #3
0
        public void SendTo(G2Packet packet)
        {
            if (Core.InvokeRequired)
            {
                Debug.Assert(false);
            }


            if (packet is NetworkPacket)
            {
                ((NetworkPacket)packet).SourceID = Network.Local.UserID;
                ((NetworkPacket)packet).ClientID = Network.Local.ClientID;
            }

            byte[] encoded = packet.Encode(Network.Protocol);

            PacketLogEntry logEntry = new PacketLogEntry(Core.TimeNow, TransportProtocol.LAN, DirectionType.Out, null, encoded);

            Network.LogPacket(logEntry);

            byte[] final = null;

            // encrypt, turn off encryption during simulation
            if (Core.Sim == null || Core.Sim.Internet.TestEncryption)
            {
                final = Utilities.EncryptBytes(encoded, Network.OpCrypt.Key);
            }
            else
            {
                final = encoded;
            }

            // send
            try
            {
                if (Core.Sim != null)
                {
                    //Core.Sim.Internet.SendPacket(SimPacketType.Udp, Network, final, address.ToEndPoint(), null);
                    return;
                }

                if (LanSocket == null)
                {
                    return;
                }

                if (encoded.Length > MAX_UDP_SIZE)
                {
                    throw new Exception("Packet larger than " + MAX_UDP_SIZE.ToString() + " bytes");
                }

                EndPoint tempSender = (EndPoint) new IPEndPoint(IPAddress.Broadcast, ListenPort);
                LanSocket.BeginSendTo(final, 0, final.Length, SocketFlags.None, tempSender, new AsyncCallback(UdpSocket_SendTo), LanSocket);
            }
            catch (Exception ex)
            {
                Network.UpdateLog("Exception", "LanHandler::SendTo: " + ex.Message);
            }
        }
Exemple #4
0
 public void GotPacket(G2Packet pack)
 {
     Buffer.PushPacketToReceive(pack);
     if (isHub)
     {
         G2Network.Instance.NewActionAvailable();       // signal processing thread only for connected hubs ( != browsable peer )
     }
 }
Exemple #5
0
        public bool SendData(uint service, uint datatype, G2Packet packet)
        {
            CommData data = new CommData(service, datatype, packet.Encode(Network.Protocol));

            Core.ServiceBandwidth[service].OutPerSec += data.Data.Length;

            return(SendPacket(data));
        }
Exemple #6
0
        /**
         * Send LNI And PI packets
         * */
        public void SendStartPackets()
        {
            G2Packet lni = Settings.SmartLNIPacket();

            SendPacket(lni);
            G2Packet PI = new G2PacketPI();

            SendPacket(PI);
        }
Exemple #7
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());
     }
 }
Exemple #8
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);
     }
 }
Exemple #9
0
        private static bool isPartialFile(G2PacketH hit)
        {
            G2Packet part = hit.getFirstChildPacket(G2PacketType.PART);

            if (part != null)
            {
                return(true);
            }
            return(false);
        }
Exemple #10
0
        private string getVendorCodeFromQueryHit(G2PacketQH2 qh2)
        {
            G2Packet vendorPacket = qh2.getFirstChildPacket(G2PacketType.V);

            if (vendorPacket == null)
            {
                return("");
            }
            return(((G2PacketV)vendorPacket).Str);
        }
Exemple #11
0
        private string getDNSNameFromQueryHit(G2PacketQH2 qh2)
        {
            G2Packet dns = qh2.getFirstChildPacket(G2PacketType.DNS);

            if (dns == null)
            {
                return("");
            }
            return(((G2PacketDNS)dns).Str);
        }
Exemple #12
0
 public int SendPacket(DhtAddress contact, G2Packet packet)
 {
     if (contact.TunnelServer != null)
     {
         return(SendTunnelPacket(contact, packet));
     }
     else
     {
         return(UdpControl.SendTo(contact, packet));
     }
 }
Exemple #13
0
        /**
         * Wait for packet to send to peer from its buffer and send it
         * */
        public void SendThread()
        {
            while (!shouldStop_)
            {
                G2Packet pack = peer.Buffer.PollPacketToSend();

                MemoryStream str = new MemoryStream((int)pack.getTotalPacketLength());
                pack.Write(str);
                bool succ = Send(str);
            }
        }
Exemple #14
0
        /** Search address of the servent
         *  may be null
         **/
        private static NodeAddress getAddressFromQueryHit(G2PacketQH2 qh2)
        {
            G2Packet p = qh2.getFirstChildPacket(G2PacketType.NA);

            if (p == null)
            {
                return(null);
            }
            G2PacketNA na = p as G2PacketNA;

            return(na.node);
        }
Exemple #15
0
        /**
         * Return creation time in DateTime format if present
         * otherwise return current time
         * */
        private static DateTime getCreationTimeFromHit(G2PacketH hit)
        {
            G2Packet pack = hit.getFirstChildPacket(G2PacketType.CT);

            if (pack == null)
            {
                return(DateTime.Now);
            }
            G2PacketCT ct = pack as G2PacketCT;

            return(BinaryUtils.UnixTimeStampToDateTime(ct.Timestamp));
        }
Exemple #16
0
        /**
         * Pick a packet to analyse by the processing thread
         * */
        public G2Packet PollPacketToReceive()
        {
            G2Packet pack = null;

            lock (ReceiveBuffer) {
                if (ReceiveBuffer.Count > 0)
                {
                    pack = (G2Packet)ReceiveBuffer.Dequeue();
                }
            }
            return(pack);
        }
Exemple #17
0
        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);
        }
Exemple #18
0
        /**
         * Retrieve a packet
         * */
        public G2Packet PollPacketToSend()
        {
            G2Packet pack = null;

            lock (SendBuffer) {
                while (SendBuffer.Count == 0)
                {
                    Monitor.Wait(SendBuffer);
                }

                pack = (G2Packet)SendBuffer.Dequeue();
            }
            return(pack);
        }
Exemple #19
0
        /**
         * Get a URL link if present
         * IF not present , it has to beretrieved by HTTP request
         * */
        private static string getDownloadLink(G2PacketH hit)
        {
            G2Packet pack = hit.getFirstChildPacket(G2PacketType.URL);

            if (pack == null)
            {
                return("");
            }
            G2PacketURL url = pack as G2PacketURL;

            if (url == null)
            {
                return("");
            }

            return(url.Str);
        }
Exemple #20
0
        /*		*
         * Return the nickname if there is one
         * otherwise return empty string
         * */
        private static String getNickFromQueryHit(G2PacketQH2 qh2)
        {
            G2Packet upro = qh2.getFirstChildPacket(G2PacketType.UPRO);

            if (upro == null)
            {
                return("");
            }
            G2Packet nick = upro.getFirstChildPacket(G2PacketType.NICK);

            if (nick == null)
            {
                return("");
            }

            return(((G2PacketNICK)nick).Str);
        }
Exemple #21
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);
            }
        }
Exemple #22
0
        private static ActionInnocence.P2PScan.PeerCollection getAlternateLocationsFromQueryHit(G2PacketQH2 qh2)
        {
            G2Packet pack = qh2.getFirstChildPacket(G2PacketType.ALT);

            if (pack == null)
            {
                return(null);
            }
            G2PacketALT altPack = pack as G2PacketALT;

            ActionInnocence.P2PScan.PeerCollection coll = new ActionInnocence.P2PScan.PeerCollection();
            foreach (NodeAddress add in altPack.Addresses)
            {
                coll.Add(new ActionInnocence.P2PScan.Peer(add.ipv4.ToString(), add.ToString(), add.port, ""));
            }
            return(coll);
        }
Exemple #23
0
        private G2PacketQH2 PollResultPacket()
        {
            G2PacketQH2 resultPack;

            lock (LockBuffer)
            {
                // not while because we can terminate the thread with the timer
                if (Buffer.ReceiveBufferCount == 0)
                {
                    Monitor.Wait(LockBuffer);
                }

                G2Packet pack = Buffer.PollPacketToReceive();
                resultPack = pack as G2PacketQH2;
            }
            return(resultPack);
        }
Exemple #24
0
        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);
        }
Exemple #25
0
        RudpPacket CreateRudpPacket(DhtClient client, uint service, int type, G2Packet packet, bool reliable)
        {
            RudpPacket comm = new RudpPacket();

            comm.SenderID     = Network.Local.UserID;
            comm.SenderClient = Network.Local.ClientID;
            comm.TargetID     = client.UserID;
            comm.TargetClient = client.ClientID;
            comm.PacketType   = RudpPacketType.Light;
            comm.Payload      = RudpLight.Encode(service, type, packet.Encode(Network.Protocol));

            if (reliable)
            {
                comm.PeerID   = (ushort)Core.RndGen.Next(ushort.MaxValue); // used to ack
                comm.Sequence = 1;
            }

            return(comm);
        }
Exemple #26
0
        /**
         * Stop the connection to the peer,
         * and sends the results back
         * */
        private void SearchTimeOut(Object sender, EventArgs args)
        {
            G2Packet pack = null;

            while ((pack = Peer.Buffer.PollPacketToReceive()) != null)
            {
                G2PacketQH2 qh2 = pack as G2PacketQH2;
                if (qh2 == null)
                {
                    continue;
                }
                packetResults.Add(qh2);
            }

            Peer.Close();

            if (EndSearch != null)
            {
                EndSearch(referenceToPeer, referenceToSearchResults, packetResults);
            }
        }
Exemple #27
0
        /**
         * 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;
            }
        }
Exemple #28
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 !!");
        }
Exemple #29
0
        public void SendUnreliable(uint service, uint type, G2Packet packet)
        {
            // fast, secure, out-of-band method of sending data
            // useful for things like VOIP during a file transfer with host
            // data has got to go out asap, no matter what

            // check rudp socket is connected
            if (Status != SessionStatus.Active)
            {
                return;
            }

            // add to special rudp packet
            RudpPacket rudp = new RudpPacket();

            rudp.SenderID     = Network.Local.UserID;
            rudp.SenderClient = Network.Local.ClientID;
            rudp.TargetID     = UserID;
            rudp.TargetClient = ClientID;
            rudp.PeerID       = Comm.RemotePeerID;
            rudp.PacketType   = RudpPacketType.Unreliable;

            CommData data = new CommData(service, type, packet.Encode(Network.Protocol));

            rudp.Payload = Utilities.EncryptBytes(data.Encode(Network.Protocol), OutboundEnc.Key);

            // send
            Comm.SendPacket(rudp, Comm.PrimaryAddress);

            // stats
            Core.ServiceBandwidth[service].OutPerSec += data.Data.Length;

            PacketLogEntry logEntry = new PacketLogEntry(Core.TimeNow, TransportProtocol.Rudp, DirectionType.Out, Comm.PrimaryAddress.Address, rudp.Payload);

            Core.Network.LogPacket(logEntry);
        }
 /**
  * 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");
         }
     }
 }