Exemplo n.º 1
0
        public void ReceiveAck(G2ReceivedPacket packet)
        {
            SearchAck ack = SearchAck.Decode(packet);

            // loopback
            if (Network.Local.Equals(ack.Source))
                return;

            if (Core.ServiceBandwidth.ContainsKey(ack.Service))
                Core.ServiceBandwidth[ack.Service].InPerSec += packet.Root.Data.Length;

            if (ack.Source.Firewall == FirewallType.Open)
                Routing.Add(new DhtContact(ack.Source, packet.Source.IP));

            foreach (DhtContact contact in ack.ContactList)
                Routing.Add(contact); // function calls back into seach system, adding closer nodes

            // if response to initial pong or crawl
            if (ack.SearchID == 0)
            {
                Core.RunInGuiThread(Network.CrawlerSearchAck, ack, packet);
                return;
            }

            // mark searches as done
            lock (Active)
                foreach (DhtSearch search in Active)
                    if (search.SearchID == ack.SearchID)
                    {
                        foreach (DhtLookup lookup in search.LookupList)
                            if (lookup.Contact.UserID == ack.Source.UserID && lookup.Contact.ClientID == ack.Source.ClientID)
                                lookup.Status = LookupStatus.Done;

                        if (search.ProxyTcp != null && search.ProxyTcp.Proxy == ProxyType.ClientBlocked)
                        {
                            ack.FromAddress = packet.Source;
                            search.ProxyTcp.SendPacket(ack);
                            return;
                        }

                        foreach (byte[] value in ack.ValueList)
                            search.Found(value, packet.Source);

                        if (ack.Proxied)
                            search.Found(new DhtContact(ack.Source, packet.Source.IP), true);

                        if (!search.Finished && search.FoundValues.Count > search.TargetResults)
                            search.FinishSearch("Max Values Found");
                    }
        }
Exemplo n.º 2
0
        public static CommClose Decode(G2ReceivedPacket packet)
        {
            CommClose close = new CommClose();

            G2Header child = new G2Header(packet.Root.Data);

            while( G2Protocol.ReadNextChild(packet.Root, child) == G2ReadResult.PACKET_GOOD )
            {
                if (child.Name == Packet_Message)
                    if( G2Protocol.ReadPayload(child) )
                        close.Reason = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize);
            }

            return close;
        }
Exemplo n.º 3
0
        void ReceivePackets()
        {
            int Start  = 0;
            G2ReadResult streamStatus = G2ReadResult.PACKET_GOOD;

            while(streamStatus == G2ReadResult.PACKET_GOOD)
            {
                G2ReceivedPacket packet = new G2ReceivedPacket();
                packet.Root = new G2Header(FinalRecvBuffer);

                streamStatus = G2Protocol.ReadNextPacket(packet.Root, ref Start, ref FinalRecvBuffSize);

                if( streamStatus != G2ReadResult.PACKET_GOOD )
                    break;

                packet.Tcp       = this;
                packet.Source = new DhtContact(this, RemoteIP);

                // extract data from final recv buffer so it can be referenced without being overwritten by this thread
                byte[] extracted = Utilities.ExtractBytes(packet.Root.Data, packet.Root.PacketPos, packet.Root.PacketSize);
                packet.Root = new G2Header(extracted);
                G2Protocol.ReadPacket(packet.Root);

                LastPacket = packet;

                PacketLogEntry logEntry = new PacketLogEntry(Core.TimeNow, TransportProtocol.Tcp, DirectionType.In, packet.Source, packet.Root.Data);
                Network.LogPacket(logEntry);

                Network.IncomingPacket(packet);
            }

            // re-align buffer
            if (Start > 0 && FinalRecvBuffSize > 0)
            {
                Buffer.BlockCopy(FinalRecvBuffer, Start, FinalRecvBuffer, 0, FinalRecvBuffSize);
                //Network.UpdateConsole(PacketBytesReady.ToString() + " bytes moved to front of receive buffer");
            }
        }
Exemplo n.º 4
0
        public static SessionRequest Decode(G2ReceivedPacket packet)
        {
            SessionRequest sr = new SessionRequest();

            G2Header child = new G2Header(packet.Root.Data);

            while( G2Protocol.ReadNextChild(packet.Root, child) == G2ReadResult.PACKET_GOOD )
            {
                if (child.Name == Packet_Key)
                    if (G2Protocol.ReadPayload(child))
                        sr.EncryptedKey = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize);
            }

            return sr;
        }
Exemplo n.º 5
0
 public static RudpPacket Decode(G2ReceivedPacket packet)
 {
     return Decode(packet.Root);
 }
Exemplo n.º 6
0
        private void DrawGroup(Graphics buffer, Dictionary<ulong, Dictionary<ulong, PacketGroup>> TrafficGroup, bool tcp)
        {
            foreach (Dictionary<ulong, PacketGroup> destination in TrafficGroup.Values)
                foreach (PacketGroup group in destination.Values)
                {
                    if (!NodePoints.ContainsKey(group.SourceID) || !NodePoints.ContainsKey(group.DestID))
                        continue;

                    group.SetPoints(NodePoints[group.SourceID], NodePoints[group.DestID]);

                    TrafficPen.Width = 1;
                    group.LineSize = 200 + 20;

                    if (group.TotalSize > 200)
                    {
                        TrafficPen.Width = 2;
                        group.LineSize = 1000 + 100;
                    }

                    if (group.TotalSize > 1000)
                    {
                        TrafficPen.Width = 3;
                        group.LineSize = group.TotalSize + 500;
                    }

                    // calc break size
                    double breakSize = (group.LineSize - group.TotalSize) / (group.Packets.Count + 1);
                    double pos = breakSize;

                    Color bgColor = Color.WhiteSmoke;

                    //if (SelectedID != 0)
                    //    bgColor = group.SourceID == SelectedID ? Color.LightCoral : Color.LightBlue;
                    //else
                    //    bgColor = tcp ? Color.LightBlue : Color.WhiteSmoke;

                    TrafficPen.Color = bgColor;
                    buffer.DrawLine(TrafficPen, group.GetPoint(0), group.GetPoint(pos));

                    foreach (byte[] packet in group.Packets)
                    {

                        if (Sim.TestEncryption || Sim.TestTcpFullBuffer)
                        {
                            TrafficPen.Color = Legend.PicUnk.BackColor;
                            buffer.DrawLine(TrafficPen, group.GetPoint(pos), group.GetPoint(pos + packet.Length));
                        }

                        else
                        {
                            G2Header root = new G2Header(packet);
                            G2Protocol.ReadPacket(root);

                            double controlLen = (root.InternalPos > 0) ? root.InternalPos - root.PacketPos : packet.Length;

                            // net packet
                            if (root.Name == RootPacket.Network)
                            {
                                TrafficPen.Color = Legend.PicNet.BackColor;
                                buffer.DrawLine(TrafficPen, group.GetPoint(pos), group.GetPoint(pos + controlLen));

                                NetworkPacket netPacket = NetworkPacket.Decode(root);
                                G2Header internalRoot = new G2Header(netPacket.InternalData);
                                G2Protocol.ReadPacket(internalRoot);

                                G2ReceivedPacket recvedPacket = new G2ReceivedPacket();
                                recvedPacket.Root = internalRoot;

                                // draw internal
                                TrafficPen.Color = Legend.PicUnk.BackColor;

                                if (internalRoot.Name == NetworkPacket.SearchRequest)
                                {
                                    SearchReq req = SearchReq.Decode(recvedPacket);

                                    int paramLen = req.Parameters == null ? 10 : req.Parameters.Length;

                                    TrafficPen.Color = Legend.PicSrchReq.BackColor;
                                    buffer.DrawLine(TrafficPen, group.GetPoint(pos + controlLen), group.GetPoint(pos + controlLen + internalRoot.PacketSize - paramLen));

                                    TrafficPen.Color = GetComponentColor(req.Service);
                                    buffer.DrawLine(TrafficPen, group.GetPoint(pos + controlLen + internalRoot.PacketSize - paramLen), group.GetPoint(pos + controlLen + internalRoot.PacketSize));
                                }

                                else if (internalRoot.Name == NetworkPacket.SearchAck)
                                {
                                    SearchAck ack = SearchAck.Decode(recvedPacket);

                                    int valLen = 10;

                                    if (ack.ValueList.Count > 0)
                                    {
                                        valLen = 0;
                                        foreach (byte[] val in ack.ValueList)
                                            valLen += val.Length;
                                    }

                                    TrafficPen.Color = Legend.PicSrchAck.BackColor;
                                    buffer.DrawLine(TrafficPen, group.GetPoint(pos + controlLen), group.GetPoint(pos + controlLen + internalRoot.PacketSize - valLen));

                                    TrafficPen.Color = GetComponentColor(ack.Service);
                                    buffer.DrawLine(TrafficPen, group.GetPoint(pos + controlLen + internalRoot.PacketSize - valLen), group.GetPoint(pos + controlLen + internalRoot.PacketSize));
                                }

                                else if (internalRoot.Name == NetworkPacket.StoreRequest)
                                {
                                    StoreReq req = StoreReq.Decode(recvedPacket);

                                    int dataLen = req.Data == null ? 10 : req.Data.Length;

                                    TrafficPen.Color = Legend.PicStore.BackColor;
                                    buffer.DrawLine(TrafficPen, group.GetPoint(pos + controlLen), group.GetPoint(pos + controlLen + internalRoot.PacketSize - dataLen));

                                    TrafficPen.Color = GetComponentColor(req.Service);
                                    buffer.DrawLine(TrafficPen, group.GetPoint(pos + controlLen + internalRoot.PacketSize - dataLen), group.GetPoint(pos + controlLen + internalRoot.PacketSize));
                                }

                                else
                                {
                                    if (internalRoot.Name == NetworkPacket.Ping)
                                        TrafficPen.Color = Legend.PicPing.BackColor;

                                    else if (internalRoot.Name == NetworkPacket.Pong)
                                        TrafficPen.Color = Legend.PicPong.BackColor;

                                    else if (internalRoot.Name == NetworkPacket.ProxyRequest)
                                        TrafficPen.Color = Legend.PicPxyReq.BackColor;

                                    else if (internalRoot.Name == NetworkPacket.ProxyAck)
                                        TrafficPen.Color = Legend.PicPxyAck.BackColor;

                                    buffer.DrawLine(TrafficPen, group.GetPoint(pos + controlLen), group.GetPoint(pos + packet.Length));
                                }
                            }

                            // comm packet
                            if (root.Name == RootPacket.Comm)
                            {
                                TrafficPen.Color = Legend.PicComm.BackColor;
                                buffer.DrawLine(TrafficPen, group.GetPoint(pos), group.GetPoint(pos + controlLen));

                                TrafficPen.Color = Legend.PicUnk.BackColor;
                                buffer.DrawLine(TrafficPen, group.GetPoint(pos + controlLen), group.GetPoint(pos + packet.Length));
                            }
                        }

                        if (SelectedID != 0)
                            buffer.DrawString(group.TotalSize.ToString(), TahomaFont, BlackBrush, group.GetPoint(group.LineSize / 4));

                        pos += packet.Length;

                        TrafficPen.Color = bgColor;
                        buffer.DrawLine(TrafficPen, group.GetPoint(pos), group.GetPoint(pos + breakSize));
                        pos += breakSize;
                    }
                }
        }
Exemplo n.º 7
0
        public static KeyAck Decode(G2ReceivedPacket packet)
        {
            KeyAck ka = new KeyAck();

            G2Header child = new G2Header(packet.Root.Data);

            while (G2Protocol.ReadNextChild(packet.Root, child) == G2ReadResult.PACKET_GOOD)
            {
                if (!G2Protocol.ReadPayload(child))
                    continue ;

                if (child.Name == Packet_Key)
                    ka.PublicKey = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize);
            }

            return ka;
        }
Exemplo n.º 8
0
        void Receive_Pong(G2ReceivedPacket packet)
        {
            Core.ServiceBandwidth[Core.DhtServiceID].InPerSec += packet.Root.Data.Length;

            Pong pong = Pong.Decode(packet);

            SetLocalIP(pong.RemoteIP, packet);

            bool lanIP = Utilities.IsLocalIP(packet.Source.IP);
            bool validSource = (!lanIP || LanMode && lanIP);

            // check if remote has a newer version cached
            if (!IsLookup && pong.Version != 0 && Core.Update != null)
                if (Core.Context.SignedUpdate == null ||
                    !Core.Context.SignedUpdate.Loaded ||
                    Core.Context.SignedUpdate.SequentialVersion < pong.Version)
                {
                    // ota update disabled for now
                    //Core.Update.NewVersion(pong.Version, pong.Source.UserID);
                }

            // if received tcp
            if (packet.ReceivedTcp)
            {
                // if regular interval pong
                if (pong.Source == null)
                {
                    // keep routing entry fresh so connect state remains
                    if (validSource && packet.Tcp.Proxy == ProxyType.Server)
                        Routing.Add(new DhtContact(packet.Tcp, packet.Tcp.RemoteIP), true);
                }

                // else connect pong with source info
                else
                {
                    // usually a proxied pong from somewhere else to keep our routing fresh
                    if (validSource && pong.Source.Firewall == FirewallType.Open)
                        Routing.Add(new DhtContact(pong.Source, packet.Source.IP), true);

                    // pong's direct flag ensures that tcp connection info (especially client ID) is not set with
                    //   information from a pong routed through the remote host, but from the host we're directly connected to
                    if (pong.Direct)
                    {
                        packet.Tcp.UserID = pong.Source.UserID;
                        packet.Tcp.ClientID = pong.Source.ClientID;
                        packet.Tcp.TcpPort = pong.Source.TcpPort;
                        packet.Tcp.UdpPort = pong.Source.UdpPort;

                        // if firewalled
                        if (packet.Tcp.Outbound && packet.Tcp.Proxy == ProxyType.Unset)
                        {
                            if (Core.Firewall != FirewallType.Open && TcpControl.AcceptProxy(ProxyType.Server, pong.Source.UserID))
                            {
                                // send proxy request
                                ProxyReq request = new ProxyReq();
                                request.SenderID = Local.UserID;
                                request.Type = (Core.Firewall == FirewallType.Blocked) ? ProxyType.ClientBlocked : ProxyType.ClientNAT;
                                packet.Tcp.SendPacket(request);
                            }

                            // else ping/pong done, end connect
                            else
                                packet.Tcp.CleanClose("Not in need of a proxy");
                        }
                    }
                }
            }

            // pong received udp or tunneled
            else
            {
                if (validSource)
                {
                    if (Core.Firewall == FirewallType.Blocked && !packet.Tunneled)
                        Core.SetFirewallType(FirewallType.NAT);

                    // add to routing
                    // on startup, especially in sim everyone starts blocked so pong source firewall is not set right, but still needs to go into routing
                    Routing.TryAdd(packet, pong.Source, true);
                }

                // send bootstrap request for nodes if network not responsive
                // do tcp connect because if 2 nodes on network then one needs to find out they're open
                if (!Responsive)
                {
                    Searches.SendRequest(packet.Source, Local.UserID, 0, Core.DhtServiceID, 0, null);

                    if (!packet.Tunneled) // ip isnt set correctly on tunneled, and if tunneled then lookup active and host tested anyways
                        TcpControl.MakeOutbound(packet.Source, pong.Source.TcpPort, "pong bootstrap");
                }

                // forward to proxied nodes, so that their routing tables are up to date, so they can publish easily
                if (Core.Firewall == FirewallType.Open)
                {
                    pong.FromAddress = packet.Source;
                    pong.RemoteIP = null;
                    pong.Direct = false;

                    foreach (TcpConnect connection in TcpControl.ProxyClients)
                        connection.SendPacket(pong);
                }
            }
        }
Exemplo n.º 9
0
        public void IncomingPacket(G2ReceivedPacket packet)
        {
            if (Core.Sim == null || Core.Sim.Internet.TestCoreThread)
            {
                lock (IncomingPackets)
                    // if each packet 1kb, have a megabyte buffer for backed up packets (hashing, etc..)
                    if (IncomingPackets.Count < 1000)
                        IncomingPackets.Enqueue(packet);

                Core.ProcessEvent.Set();
            }
            else
            {
                try
                {
                    ReceivePacket(packet);
                }
                catch (Exception ex)
                {
                    UpdateLog("Exception", "DhtNetwork::IncomingPacket: " + ex.Message);
                }
            }
        }
Exemplo n.º 10
0
        public void SetLocalIP(IPAddress localIP, G2ReceivedPacket packet)
        {
            if (localIP != null && !packet.Tunneled)
            {
                bool lanIP = Utilities.IsLocalIP(localIP); // re init to what they think our ip is

                if (!lanIP || LanMode && lanIP)
                    Core.LocalIP = localIP;

                if (!lanIP && LanMode)
                    SetLanMode(false);
            }
        }
Exemplo n.º 11
0
        void Receive_Ping(G2ReceivedPacket packet)
        {
            Core.ServiceBandwidth[Core.DhtServiceID].InPerSec += packet.Root.Data.Length;

            Ping ping = Ping.Decode(packet);

            bool lanIP = Utilities.IsLocalIP(packet.Source.IP);
            bool validSource = (!lanIP || LanMode && lanIP);

            // set local IP
            SetLocalIP(ping.RemoteIP, packet);

            // check loop back
            if (ping.Source != null && Local.Equals(ping.Source))
            {
                if (packet.ReceivedTcp)
                    packet.Tcp.CleanClose("Loopback connection");

                return;
            }

            // dont send back pong if received tunneled and no longer need to use lookup proxies
            // remote would only send tunneled ping if UseGlobalProxies published info on network
            // let our lookup address expire from remote's routing table
            if (packet.Tunneled && !UseLookupProxies)
                return;

            // setup pong reply
            Pong pong = new Pong();

            if (ping.Source != null)
                pong.Source = GetLocalSource();

            if (ping.RemoteIP != null)
                pong.RemoteIP = packet.Source.IP;

            if (!IsLookup && Core.Context.SignedUpdate != null && Core.Context.SignedUpdate.Loaded)
                pong.Version = Core.Context.SignedUpdate.SequentialVersion;

            int sentBytes = 0;

            // received tcp
            if (packet.ReceivedTcp)
            {
                if (ping.Source == null)
                {
                    packet.Tcp.SendPacket(pong);
                    return;
                }

                if (validSource)
                {
                    if (ping.Source.Firewall == FirewallType.Open)
                        Routing.Add(new DhtContact(ping.Source, packet.Source.IP));

                    // received incoming tcp means we are not firewalled
                    if (!packet.Tcp.Outbound)
                    {
                        // done here to prevent setting open for loopback tcp connection
                        Core.SetFirewallType(FirewallType.Open);
                        pong.Source.Firewall = FirewallType.Open;
                    }
                }

                // check if already connected
                if (packet.Tcp.Proxy == ProxyType.Unset && TcpControl.GetProxy(ping.Source) != null)
                {
                    packet.Tcp.CleanClose("Dupelicate Connection");
                    return;
                }

                packet.Tcp.UserID = ping.Source.UserID;
                packet.Tcp.ClientID = ping.Source.ClientID;
                packet.Tcp.TcpPort = ping.Source.TcpPort;
                packet.Tcp.UdpPort = ping.Source.UdpPort;

                // if inbound connection, to our open host, and haven't checked fw yet
                if (!packet.Tcp.Outbound &&
                    ping.Source.Firewall != FirewallType.Open &&
                    !packet.Tcp.CheckedFirewall)
                {
                    TcpControl.MakeOutbound(packet.Source, ping.Source.TcpPort, "check firewall");
                    packet.Tcp.CheckedFirewall = true;
                }

                pong.Direct = true;
                sentBytes = packet.Tcp.SendPacket(pong);

                // dont send close if proxies maxxed yet, because their id might be closer than current proxies
            }

            // ping received udp or tunneled
            else
            {
                if (validSource)
                {
                    // received udp traffic, we must be behind a NAT at least
                    if (Core.Firewall == FirewallType.Blocked && !packet.Tunneled)
                        Core.SetFirewallType(FirewallType.NAT);

                    Routing.TryAdd(packet, ping.Source);
                }

                // if received over lan, the port isn't set
                if (packet.Source.UdpPort == 0)
                    packet.Source.UdpPort = ping.Source.UdpPort;

                // send pong
                sentBytes = SendPacket(packet.Source, pong);
            }

            Core.ServiceBandwidth[Core.DhtServiceID].OutPerSec += sentBytes;
        }
Exemplo n.º 12
0
        public void Receive_Bye(G2ReceivedPacket packet)
        {
            Bye bye = Bye.Decode(packet);

            foreach(DhtContact contact in bye.ContactList)
                Network.Routing.Add(contact);

            string message = (bye.Message != null) ? bye.Message : "";

            packet.Tcp.ByeMessage = "Remote: " + message;

            Network.UpdateLog("Tcp", "Bye Received from " + packet.Tcp.ToString() + " " + message);

            // close connection
            packet.Tcp.Disconnect();

            // reconnect
            if (bye.Reconnect && NeedProxies(ProxyType.Server))
                MakeOutbound(packet.Source, packet.Tcp.TcpPort, "Reconnecting");
        }
Exemplo n.º 13
0
        void ParsePacket(byte[] buff, int length, IPEndPoint sender, bool copied)
        {
            G2ReceivedPacket packet = new G2ReceivedPacket();
            packet.Root = new G2Header(buff);

            if(G2Protocol.ReadPacket(packet.Root))
            {
                packet.Source = new DhtContact(0, 0, sender.Address, 0, 0);

                byte[] packetData = copied ? buff : Utilities.ExtractBytes(packet.Root.Data, packet.Root.PacketPos, packet.Root.PacketSize);

                PacketLogEntry logEntry = new PacketLogEntry(Core.TimeNow, TransportProtocol.LAN, DirectionType.In, packet.Source, packetData);
                Network.LogPacket(logEntry);

                Network.IncomingPacket(packet);
            }
        }
Exemplo n.º 14
0
        public void Receive_StoreReq(G2ReceivedPacket packet)
        {
            StoreReq store = StoreReq.Decode(packet);

            if (Core.ServiceBandwidth.ContainsKey(store.Service))
                Core.ServiceBandwidth[store.Service].InPerSec += packet.Root.Data.Length;

            if (store.Source.Firewall == FirewallType.Open )
                    // dont need to add to routing if nat/blocked because eventual routing ping by server will auto add
                    Network.Routing.Add(new DhtContact(store.Source, packet.Source.IP));

            // forward to proxied nodes - only replicate data to blocked nodes on operation network
            if (!Network.IsLookup)
                // when we go offline it will be these nodes that update their next proxy with stored info
                foreach (TcpConnect socket in Network.TcpControl.ProxyClients)
                    if (packet.Tcp != socket)
                    {
                        if (packet.ReceivedUdp)
                            store.FromAddress = packet.Source;

                        socket.SendPacket(store);
                    }

            // pass to components
            DataReq data = new DataReq(packet.Source, store.Key, store.Service, store.DataType, store.Data);

            if (packet.ReceivedTcp && packet.Tcp.Proxy == ProxyType.Server)
                data.LocalProxy = new DhtClient(packet.Tcp);

            if(data.Service == 0)
                Receive_Patch(packet.Source, store.Data);

            else if (StoreEvent.Contains(store.Service, store.DataType))
                StoreEvent[store.Service, store.DataType].Invoke(data);
        }
Exemplo n.º 15
0
        public void Receive_ProxyRequest(G2ReceivedPacket packet)
        {
            ProxyReq request = ProxyReq.Decode(packet);

            ProxyAck ack = new ProxyAck();
            ack.Source = GetLocalSource();

            // check if there is space for type required
            if (Core.Firewall == FirewallType.Open && TcpControl.AcceptProxy(request.Type, ack.Source.UserID))
            {
                ack.Accept = true;
            }
            else if (packet.ReceivedTcp)
            {
                packet.Tcp.CleanClose("Couldn't accept proxy request");
                return;
            }

            // always send some contacts along so node can find closer proxy
            ack.ContactList = Routing.Find(request.SenderID, 8);

            // received request tcp
            if (packet.ReceivedUdp)
                UdpControl.SendTo(packet.Source, ack);

            // received request tcp
            else
            {
                packet.Tcp.Proxy = request.Type;
                packet.Tcp.SendPacket(ack);

                TcpControl.AddProxy(packet.Tcp);

                // check if a proxy needs to be disconnected now because overflow
                TcpControl.CheckProxies();
            }
        }
Exemplo n.º 16
0
        public void ReceiveCommPacket(G2ReceivedPacket raw, RudpPacket packet)
        {
            try
            {
                if (packet.PacketType == RudpPacketType.Light ||
                    packet.PacketType == RudpPacketType.LightAck)
                {
                    LightComm.ReceivePacket(raw, packet);
                    return;
                }

                // if a socket already set up
                lock (RudpControl.SocketMap)
                    if (RudpControl.SocketMap.ContainsKey(packet.PeerID))
                    {
                        RudpControl.SocketMap[packet.PeerID].RudpReceive(raw, packet, IsLookup);
                        return;
                    }

                // if starting new session
                if (packet.PacketType != RudpPacketType.Syn)
                    return;

                RudpSyn syn = new RudpSyn(packet.Payload);

                // prevent connection from self
                if (syn.SenderID == Local.UserID && syn.ClientID == Local.ClientID)
                    return;

                // find connecting session with same or unknown client id
                ulong id = syn.SenderID ^ syn.ClientID;

                if (RudpControl.SessionMap.ContainsKey(id))
                {
                    RudpSession session = RudpControl.SessionMap[id];

                    // if session id zero or matches forward
                    if ((session.Comm.State == RudpState.Connecting && session.Comm.RemotePeerID == 0) ||
                        (session.Comm.State != RudpState.Closed && session.Comm.RemotePeerID == syn.ConnID)) // duplicate syn
                    {
                        session.Comm.RudpReceive(raw, packet, IsLookup);
                        return;
                    }

                    else if (session.Comm.State == RudpState.Finishing)
                    {
                        RudpControl.RemoveSession(session);
                        // remove session, allow new one to be created
                    }
                    else
                        return;
                }

                // if clientid not in session, create new session
                RudpSession newSession = new RudpSession(RudpControl, syn.SenderID, syn.ClientID, true);

                RudpControl.SessionMap[id] = newSession;

                // send ack before sending our own syn (connect)
                // ack tells remote which address is good so that our syn's ack comes back quickly
                newSession.Comm.RudpReceive(raw, packet, IsLookup);

                newSession.Connect();

                UpdateLog("RUDP", "Inbound session accepted to ClientID " + syn.ClientID.ToString());
            }
            catch (Exception ex)
            {
                UpdateLog("Exception", "DhtNetwork::ReceiveCommPacket: " + ex.Message);
            }
        }
Exemplo n.º 17
0
        public void Send_CrawlAck(CrawlRequest req, G2ReceivedPacket packet)
        {
            CrawlAck ack = new CrawlAck();

            ack.Source = GetLocalSource();
            ack.Version = Core.Context.LocalSeqVersion.ToString();
            ack.Uptime = (Core.TimeNow - Core.StartTime).Seconds;

            foreach (TcpConnect connection in TcpControl.ProxyServers)
                ack.ProxyServers.Add(new DhtContact(connection, connection.RemoteIP));

            foreach (TcpConnect connection in TcpControl.ProxyClients)
                ack.ProxyClients.Add(new DhtContact(connection, connection.RemoteIP));

            if (packet.ReceivedTcp)
            {
                ack.ToAddress = packet.Source;
                packet.Tcp.SendPacket(ack);
            }
            else
                SendPacket(packet.Source, ack);
        }
Exemplo n.º 18
0
        public void ReceiveNetworkPacket(G2ReceivedPacket packet)
        {
            // Search request
            if (packet.Root.Name == NetworkPacket.SearchRequest)
                Searches.ReceiveRequest(packet);

            // Search ack
            else if (packet.Root.Name == NetworkPacket.SearchAck)
                Searches.ReceiveAck(packet);

            // Ping
            else if (packet.Root.Name == NetworkPacket.Ping)
                Receive_Ping(packet);

            // Pong
            else if (packet.Root.Name == NetworkPacket.Pong)
                Receive_Pong(packet);

            // Store
            else if (packet.Root.Name == NetworkPacket.StoreRequest)
                Store.Receive_StoreReq(packet);

            // Proxy request
            else if (packet.Root.Name == NetworkPacket.ProxyRequest)
                Receive_ProxyRequest(packet);

            // Proxy ack
            else if (packet.Root.Name == NetworkPacket.ProxyAck)
                Receive_ProxyAck(packet);

            // Bye
            else if (packet.Root.Name == NetworkPacket.Bye && packet.ReceivedTcp)
                TcpControl.Receive_Bye(packet);

            // Crawl Request
            else if (packet.Root.Name == NetworkPacket.CrawlRequest)
                Receive_CrawlRequest(packet);

            // Crawl Ack
            else if (packet.Root.Name == NetworkPacket.CrawlAck)
                Receive_CrawlAck(packet);

            // unknown packet
            else
            {
                UpdateLog("Exception", "Uknown packet type " + packet.Root.Name.ToString());
            }
        }
Exemplo n.º 19
0
 public static EncryptionUpdate Decode(G2ReceivedPacket packet)
 {
     // not decrypted
     EncryptionUpdate eu = new EncryptionUpdate(false);
     return eu;
 }
Exemplo n.º 20
0
        public void ReceivePacket(G2ReceivedPacket packet)
        {
            // Network packet
            if (packet.Root.Name == RootPacket.Network)
            {
                NetworkPacket netPacket = NetworkPacket.Decode(packet.Root);

                G2ReceivedPacket embedded = new G2ReceivedPacket();
                embedded.Tcp = packet.Tcp;
                embedded.Source = packet.Source;
                embedded.Source.UserID = netPacket.SourceID;
                embedded.Source.ClientID = netPacket.ClientID;
                embedded.Root = new G2Header(netPacket.InternalData);

                // from - received from proxy server
                if (netPacket.FromAddress != null)
                {
                    if (packet.ReceivedUdp)
                        throw new Exception("From tag set on packet received udp");
                    if (packet.Tcp.Proxy != ProxyType.Server)
                        throw new Exception("From tag (" + netPacket.FromAddress.ToString() + ") set on packet not received from server (" + packet.Tcp.ToString() + ")");

                    embedded.Source = new DhtContact(netPacket.FromAddress);
                }

                // to - received from proxied node, and not for us
                if (netPacket.ToAddress != null &&
                    !(netPacket.ToAddress.UserID == Local.UserID && netPacket.ToAddress.ClientID == Local.ClientID))
                {
                    if (packet.ReceivedUdp)
                        throw new Exception("To tag set on packet received udp");
                    if (packet.Tcp.Proxy == ProxyType.Server || packet.Tcp.Proxy == ProxyType.Unset)
                        throw new Exception("To tag set on packet received from server");

                    DhtAddress address = netPacket.ToAddress;
                    netPacket.ToAddress = null;

                    TcpConnect direct = TcpControl.GetProxy(address);

                    if (direct != null)
                        direct.SendPacket(netPacket);
                    else
                        UdpControl.SendTo(address, netPacket);

                    return;
                }

                // process
                if (G2Protocol.ReadPacket(embedded.Root))
                    ReceiveNetworkPacket(embedded);
            }

            // Tunnel Packet
            else if (packet.Root.Name == RootPacket.Tunnel)
            {
                // can only tunnel over lookup network
                if (!IsLookup)
                    return;

                PacketLogEntry logEntry = new PacketLogEntry(Core.TimeNow, TransportProtocol.Tunnel, DirectionType.In, packet.Source, packet.Root.Data);
                LogPacket(logEntry);

                TunnelPacket tunnel = TunnelPacket.Decode(packet.Root);

                // handle locally
                if (tunnel.Target.Equals(Local))
                {
                    Core.Context.Cores.LockReading(delegate()
                    {
                        foreach (OpCore core in Core.Context.Cores)
                            if (core.TunnelID == tunnel.Target.TunnelID)
                                core.Network.ReceiveTunnelPacket(packet, tunnel);
                    });

                }
                else if (tunnel.TargetServer != null)
                {
                    TcpConnect direct = TcpControl.GetProxy(tunnel.Target);

                    // if directly connected add from and forwared
                    if (direct != null)
                        direct.SendPacket(tunnel);

                    // only forward udp if received over tcp from a proxied host
                    else if (tunnel.TargetServer != null && packet.ReceivedTcp && packet.Tcp.Proxy != ProxyType.Server)
                        UdpControl.SendTo(tunnel.TargetServer, tunnel);
                }
            }

            // Communication Packet
            else if (packet.Root.Name == RootPacket.Comm)
            {
                RudpPacket commPacket = RudpPacket.Decode(packet);

                // received direct
                packet.Source.UserID = commPacket.SenderID;
                packet.Source.ClientID = commPacket.SenderClient;

                // remote node is proxied
                if (commPacket.RemoteProxy != null)
                    packet.Source = new DhtContact(commPacket.RemoteProxy);

                // For local host
                if (commPacket.TargetID == Local.UserID && commPacket.TargetClient == Local.ClientID)
                {
                    ReceiveCommPacket(packet, commPacket);
                    return;
                }

                // Also Forward to appropriate node
                TcpConnect socket = TcpControl.GetProxy(commPacket.TargetID, commPacket.TargetClient);

                if (socket != null)
                {
                    // forward to proxied node - strip TO flag, add from address
                    commPacket.ToAddress = null;
                    commPacket.RemoteProxy = packet.Source; // if remote proxy is null, then we are setting this to the packet's original source

                    socket.SendPacket(commPacket);
                    return;
                }

                // received from a proxied node, forward udp
                if (packet.ReceivedTcp && commPacket.ToAddress != null)
                {
                    DhtAddress target = commPacket.ToAddress;

                    commPacket.ToAddress = null; // strip TO flag
                    commPacket.RemoteProxy = new DhtAddress(Core.LocalIP, GetLocalSource());

                    UdpControl.SendTo(target, commPacket);
                }
            }
        }
Exemplo n.º 21
0
        public static KeyRequest Decode(G2ReceivedPacket packet)
        {
            KeyRequest kr = new KeyRequest();

            G2Header child = new G2Header(packet.Root.Data);

            while( G2Protocol.ReadNextChild(packet.Root, child) == G2ReadResult.PACKET_GOOD )
            {
                if (!G2Protocol.ReadPayload(child))
                    continue;

                if (child.Name == Packet_Encryption)
                    kr.Encryption = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize);

                else if (child.Name == Packet_Key)
                    kr.Key = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize);

                else if (child.Name == Packet_IV)
                    kr.IV = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize);
            }

            return kr;
        }
Exemplo n.º 22
0
        public void ReceiveTunnelPacket(G2ReceivedPacket raw, TunnelPacket tunnel)
        {
            if (Core.InvokeRequired) // called from  lookup core's thread
            {
                Core.RunInCoreAsync(delegate() { ReceiveTunnelPacket(raw, tunnel); });
                return;
            }

            Debug.Assert(!IsLookup);

            if (IsLookup)
                return;

            // decrypt public packet
            if (Core.Sim == null || Core.Sim.Internet.TestEncryption) // turn off encryption during simulation
            {
                if (tunnel.Payload.Length < 16)
                    throw new Exception("Not enough data received for IV");

                tunnel.Payload = Utilities.DecryptBytes(tunnel.Payload, tunnel.Payload.Length, LocalAugmentedKey);
            }

            G2ReceivedPacket opPacket = new G2ReceivedPacket();
            opPacket.Root = new G2Header(tunnel.Payload);

            // set source information
            if (G2Protocol.ReadPacket(opPacket.Root))
            {
                opPacket.Source = new DhtAddress();

                // used to add direct op contact if source firewall is open
                // or re-routing through same lookup proxy
                opPacket.Source.IP = raw.Source.IP;
                opPacket.Source.UdpPort = raw.Source.UdpPort;

                // op user/client set by net/comm processing

                opPacket.Source.TunnelClient = tunnel.Source;
                opPacket.Source.TunnelServer = tunnel.SourceServer;

                PacketLogEntry logEntry = new PacketLogEntry(Core.TimeNow, TransportProtocol.Tunnel, DirectionType.In, opPacket.Source, opPacket.Root.Data);
                LogPacket(logEntry);

                IncomingPacket(opPacket);
            }
        }
Exemplo n.º 23
0
        public static ProxyUpdate Decode(G2ReceivedPacket packet)
        {
            ProxyUpdate update = new ProxyUpdate();

            G2Header child = new G2Header(packet.Root.Data);

            while (G2Protocol.ReadNextChild(packet.Root, child) == G2ReadResult.PACKET_GOOD)
            {
                if (!G2Protocol.ReadPayload(child))
                    continue;

                switch (child.Name)
                {
                    case Packet_Proxy:
                        update.Proxy = DhtAddress.ReadPacket(child);
                        break;
                }
            }

            return update;
        }
Exemplo n.º 24
0
        public void Receive_CrawlAck(G2ReceivedPacket packet)
        {
            CrawlAck ack = CrawlAck.Decode(packet);

            Core.RunInGuiThread(CrawlerAck, ack, packet);
        }
Exemplo n.º 25
0
        public static SessionAck Decode(G2ReceivedPacket packet)
        {
            SessionAck sa = new SessionAck();

            G2Header child = new G2Header(packet.Root.Data);

            while( G2Protocol.ReadNextChild(packet.Root, child) == G2ReadResult.PACKET_GOOD )
            {
                if (child.Name == Packet_Name)
                    if (G2Protocol.ReadPayload(child))
                        sa.Name = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize);
            }

            return sa;
        }
Exemplo n.º 26
0
        public void Receive_CrawlRequest(G2ReceivedPacket packet)
        {
            CrawlRequest request = CrawlRequest.Decode(packet);

            if (Local.Equals(request.Target))
            {
                Send_CrawlAck(request, packet);
            }

            // Forward to appropriate node
            else
            {
                TcpConnect client = TcpControl.GetProxy(request.Target);

                if (client != null)
                {
                    request.FromAddress = packet.Source; // add so receiving host knows where to send response too

                    client.SendPacket(request);
                }
            }
        }
Exemplo n.º 27
0
 public static CommData Decode(G2ReceivedPacket packet)
 {
     return Decode(packet.Root);
 }
Exemplo n.º 28
0
        public void Receive_ProxyAck(G2ReceivedPacket packet)
        {
            ProxyAck ack = ProxyAck.Decode(packet);

            // update routing
            if (packet.ReceivedUdp && ack.Source.Firewall == FirewallType.Open)
                Routing.Add(new DhtContact(ack.Source, packet.Source.IP));

            foreach (DhtContact contact in ack.ContactList)
                Routing.Add(contact);

            // dont do proxy if we're not firewalled or remote host didnt accept
            if (Core.Firewall == FirewallType.Open || !ack.Accept)
            {
                if (packet.ReceivedTcp)
                    packet.Tcp.CleanClose("Proxy request rejected");

                return;
            }

            // received ack udp
            if (packet.ReceivedUdp)
            {
                if (!TcpControl.ProxyMap.ContainsKey(ack.Source.RoutingID))
                    TcpControl.MakeOutbound(packet.Source, ack.Source.TcpPort, "proxy ack recv");
            }

            // received ack tcp
            else
            {
                packet.Tcp.Proxy = ProxyType.Server;

                TcpControl.AddProxy(packet.Tcp);

                TcpControl.CheckProxies();

                // location and rudp connections updated after 20 seconds
            }
        }
Exemplo n.º 29
0
        public ListViewItem PackettoItem(PacketLogEntry logEntry)
        {
            // hash, protocol, direction, address, type, size
            string hash      = Utilities.BytestoHex(sha.ComputeHash( logEntry.Data), 0, 2, false);
            string protocol = logEntry.Protocol.ToString();

            // Network - Search / Search Req / Store ... - Component

            // Comm - Data / Ack / Syn

            // Rudp - Type - Component

            string name      = "?";

            G2Header root = new G2Header(logEntry.Data);

            if (G2Protocol.ReadPacket(root))
            {
                if(logEntry.Protocol == TransportProtocol.Rudp)
                {
                    name = TransportProtocol.Rudp.ToString() + " - ";

                    name += GetVariableName(typeof(CommPacket), root.Name);

                    if (root.Name == CommPacket.Data)
                    {
                        CommData data = CommData.Decode(root);

                        name += " - " + Network.Core.GetServiceName(data.Service);
                    }

                }
                else
                {
                    name = GetVariableName(typeof(RootPacket), root.Name) + " - ";

                    if (root.Name == RootPacket.Comm)
                    {
                        RudpPacket commPacket = RudpPacket.Decode(root);

                        name += GetVariableName(typeof(RudpPacketType), commPacket.PacketType);
                    }

                    if (root.Name == RootPacket.Network)
                    {
                        NetworkPacket netPacket = NetworkPacket.Decode(root);

                        G2Header internalRoot = new G2Header(netPacket.InternalData);
                        if (G2Protocol.ReadPacket(internalRoot))
                        {
                            name += GetVariableName(typeof(NetworkPacket), internalRoot.Name);

                            uint id = 0;
                            G2ReceivedPacket wrap = new G2ReceivedPacket();
                            wrap.Root = internalRoot;

                            // search request / search acks / stores have component types
                            if (internalRoot.Name == NetworkPacket.SearchRequest)
                            {
                                SearchReq req = SearchReq.Decode(wrap);
                                id = req.Service;
                            }

                            if (internalRoot.Name == NetworkPacket.SearchAck)
                            {
                                SearchAck ack = SearchAck.Decode(wrap);
                                id = ack.Service;
                            }

                            if (internalRoot.Name == NetworkPacket.StoreRequest)
                            {
                                StoreReq store = StoreReq.Decode(wrap);
                                id = store.Service;
                            }

                            if(id != 0)
                                name += " - " + Network.Core.GetServiceName(id); // GetVariableName(typeof(ServiceID), id);
                        }
                    }
                }
            }

            string time = logEntry.Time.ToString("HH:mm:ss:ff");

            string address = (logEntry.Address == null) ? "Broadcast" : logEntry.Address.ToString();
            return new PacketListViewItem(logEntry, new string[] { time, protocol, address, name, logEntry.Data.Length.ToString(), hash }, logEntry.Direction == DirectionType.In );
        }
Exemplo n.º 30
0
        private void SendAck(G2ReceivedPacket packet, SearchReq request, SearchAck ack)
        {
            // if request came in tcp, send back tcp - scenario happens in these situations
                // req u-> open t-> fw ack t-> open u-> remote
                // fw req t-> open ack t-> fw
                // fw1 req t-> open t-> fw2 ack t-> open t-> fw1

            int bytesSent = 0;

            if (packet.ReceivedTcp)
            {
                ack.ToAddress = packet.Source;
                bytesSent = packet.Tcp.SendPacket(ack);
            }
            else
                bytesSent = Network.SendPacket(packet.Source, ack);

            Core.ServiceBandwidth[ack.Service].OutPerSec += bytesSent;
        }