private void Receive_Patch(DhtAddress source, byte[] data) { // invoke patch G2Header root = new G2Header(data); if (G2Protocol.ReadPacket(root)) { if (root.Name == StorePacket.Patch) { PatchPacket packet = PatchPacket.Decode(root); if (packet == null) { return; } foreach (PatchTag patch in packet.PatchData) { if (PatchEvent.Contains(patch.Service, patch.DataType)) { PatchEvent[patch.Service, patch.DataType].Invoke(source, patch.Tag); } } } } }
public void SendRequest(DhtAddress address, UInt64 targetID, uint searchID, uint service, uint datatype, byte[] parameters) { SearchReq request = new SearchReq(); request.Source = Network.GetLocalSource(); request.SearchID = searchID; request.TargetID = targetID; request.Service = service; request.DataType = datatype; request.Parameters = parameters; int sentBytes = 0; TcpConnect direct = Network.TcpControl.GetProxy(address); if (direct != null) { sentBytes = direct.SendPacket(request); } else { sentBytes = Network.SendPacket(address, request); } Core.ServiceBandwidth[request.Service].OutPerSec += sentBytes; }
public DhtContact(DhtAddress address) { UserID = address.UserID; ClientID = address.ClientID; IP = address.IP; UdpPort = address.UdpPort; }
public DataReq(DhtAddress source, ulong target, uint service, uint datatype, byte[] data) { Source = source; Target = target; Service = service; DataType = datatype; Data = data; }
public PacketLogEntry(DateTime time, TransportProtocol protocol, DirectionType direction, DhtAddress address, byte[] data) { Time = time; Protocol = protocol; Direction = direction; Address = address; Data = data; }
public void Send_CrawlRequest(DhtAddress address, DhtClient target) { CrawlRequest request = new CrawlRequest(); request.Target = target; SendPacket(address, request); }
// used to add global proxies public DhtContact(DhtSource opHost, IPAddress opIP, TunnelAddress client, DhtAddress server) { UserID = opHost.UserID; ClientID = opHost.ClientID; IP = opIP; TcpPort = opHost.TcpPort; UdpPort = opHost.UdpPort; TunnelServer = new DhtAddress(server.UserID, server.ClientID, server.IP, server.UdpPort); TunnelClient = client; }
public int SendPacket(DhtAddress contact, G2Packet packet) { if (contact.TunnelServer != null) { return(SendTunnelPacket(contact, packet)); } else { return(UdpControl.SendTo(contact, packet)); } }
public void Update(DhtClient client, DhtAddress address) { // clients can have different userids than their address (proxied) if (!Clients.ContainsKey(client.RoutingID)) { Clients[client.RoutingID] = new LightClient(client); } Clients[client.RoutingID].AddAddress(Core, address, false); }
public void Send_StoreReq(DhtAddress address, DhtClient localProxy, DataReq publish) { if (address == null) { return; } StoreReq store = new StoreReq(); store.Source = Network.GetLocalSource(); store.Key = publish.Target; store.Service = publish.Service; store.DataType = publish.DataType; store.Data = publish.Data; int sentBytes = 0; TcpConnect direct = Network.TcpControl.GetProxy(address); if (direct != null) { sentBytes = direct.SendPacket(store); } else if (address.TunnelClient != null) { sentBytes = Network.SendTunnelPacket(address, store); } // if blocked send tcp with to tag else if (Core.Firewall == FirewallType.Blocked) { store.ToAddress = address; TcpConnect proxy = Network.TcpControl.GetProxy(localProxy); if (proxy != null) { sentBytes = proxy.SendPacket(store); } else { sentBytes = Network.TcpControl.SendRandomProxy(store); } } else { sentBytes = Network.UdpControl.SendTo(address, store); } Core.ServiceBandwidth[store.Service].OutPerSec += sentBytes; }
void Store_Patch(DhtAddress source, byte[] data) { if (data.Length < 9) { return; } ulong user = BitConverter.ToUInt64(data, 0); if (!Network.Routing.InCacheArea(user)) { return; } uint version = CompactNum.ToUInt32(data, 8, data.Length - 8); OpVersionedFile vfile = GetFile(user); if (vfile != null && vfile.Header != null) { if (vfile.Header.Version > version) { Store.Send_StoreReq(source, null, new DataReq(null, vfile.UserID, Service, DataType, vfile.SignedHeader)); return; } vfile.Unique = false; // network has current or newer version if (vfile.Header.Version == version) { return; } // else our version is old, download below } if (Network.Established) { Network.Searches.SendDirectRequest(source, user, Service, DataType, BitConverter.GetBytes(version)); } else { DownloadLater[user] = version; } }
public void Found(byte[] value, DhtAddress source) { if (FoundEvent != null) { FoundEvent.Invoke(this, source, value); } foreach (byte[] found in FoundValues) { if (Utilities.MemCompare(found, value)) { return; } } FoundValues.Add(value); }
public static TunnelPacket Decode(G2Header root) { TunnelPacket tunnel = new TunnelPacket(); if (G2Protocol.ReadPayload(root)) { tunnel.Payload = Utilities.ExtractBytes(root.Data, root.PayloadPos, root.PayloadSize); } G2Protocol.ResetPacket(root); G2Header child = new G2Header(root.Data); while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD) { if (!G2Protocol.ReadPayload(child)) { continue; } switch (child.Name) { case Packet_Source: tunnel.Source = TunnelAddress.FromBytes(child.Data, child.PayloadPos); break; case Packet_Target: tunnel.Target = TunnelAddress.FromBytes(child.Data, child.PayloadPos); break; case Packet_SourceServer: tunnel.SourceServer = DhtAddress.ReadPacket(child); break; case Packet_TargetServer: tunnel.TargetServer = DhtAddress.ReadPacket(child); break; } } return(tunnel); }
public void MakeOutbound(DhtAddress address, ushort tcpPort, string reason) { try { int connecting = 0; // check if already connected lock (SocketList) foreach (TcpConnect socket in SocketList) { if (socket.State == TcpState.Connecting) { connecting++; } if (socket.State != TcpState.Closed && address.IP.Equals(socket.RemoteIP) && tcpPort == socket.TcpPort && socket.Outbound) // allows check firewall to work { return; } } if (connecting > 6) { Debug.Assert(true); return; } TcpConnect outbound = new TcpConnect(this, address, tcpPort); Network.UpdateLog("Tcp", "Attempting Connection to " + address.ToString() + ":" + tcpPort.ToString() + " (" + reason + ")"); lock (SocketList) SocketList.Add(outbound); } catch (Exception ex) { Network.UpdateLog("Exception", "TcpHandler::MakeOutbound: " + ex.Message); } }
public void PublishDirect(List <LocationData> locations, ulong target, uint service, uint datatype, byte[] data) { if (Core.InvokeRequired) { Core.RunInCoreAsync(delegate() { PublishDirect(locations, target, service, datatype, data); }); return; } DataReq req = new DataReq(null, target, service, datatype, data); foreach (LocationData location in locations) { DhtAddress address = new DhtAddress(location.IP, location.Source); Send_StoreReq(address, null, req); foreach (DhtAddress proxy in location.Proxies) { Send_StoreReq(proxy, null, req); } } }
public static new DhtContact ReadPacket(G2Header root) { // read payload DhtContact contact = new DhtContact(); contact.UserID = BitConverter.ToUInt64(root.Data, root.PayloadPos); contact.ClientID = BitConverter.ToUInt16(root.Data, root.PayloadPos + 8); contact.UdpPort = BitConverter.ToUInt16(root.Data, root.PayloadPos + 10); contact.TcpPort = BitConverter.ToUInt16(root.Data, root.PayloadPos + 12); // read packets G2Protocol.ResetPacket(root); G2Header child = new G2Header(root.Data); while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD) { if (!G2Protocol.ReadPayload(child)) { continue; } switch (child.Name) { case Packet_IP: contact.IP = new IPAddress(Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize)); break; case Packet_Server: contact.TunnelServer = DhtAddress.ReadPacket(child); break; case Packet_Client: contact.TunnelClient = TunnelAddress.FromBytes(child.Data, child.PayloadPos); break; } } return(contact); }
// sends a direct request, no acks are returned, if host has what is requested it sends a store request as a reply // make sure whatevers calling this handles the resulting store request public void SendDirectRequest(DhtAddress dest, ulong target, uint service, uint datatype, byte[] parameters) { SearchReq request = new SearchReq(); request.Source = Network.GetLocalSource(); request.TargetID = target; request.Service = service; request.DataType = datatype; request.Parameters = parameters; request.Nodes = false; int sentBytes = 0; TcpConnect socket = Network.TcpControl.GetProxy(dest); if (socket != null) { sentBytes = socket.SendPacket(request); } else if (dest.TunnelClient != null) { sentBytes = Network.SendTunnelPacket(dest, request); } else if (Core.Firewall == FirewallType.Blocked) { request.ToAddress = dest; sentBytes = Network.TcpControl.SendRandomProxy(request); } else { sentBytes = Network.UdpControl.SendTo(dest, request); } Core.ServiceBandwidth[request.Service].OutPerSec += sentBytes; // if remote end has what we need they will send us a store request }
void Locations_TagReceived(DhtAddress address, ulong user, byte[] tag) { // if user not cached, we only active search their info if in local cache area if (tag.Length == 0) { return; } uint version = 0; OpVersionedFile file = Cache.GetFile(user); if (file != null) { version = CompactNum.ToUInt32(tag, 0, tag.Length); if (version < file.Header.Version) { Store.Send_StoreReq(address, null, new DataReq(null, file.UserID, ServiceID, DataTypeSync, file.SignedHeader)); } } // get new version of local sync file if ((file != null && version > file.Header.Version) || (file == null && ((!GlobalIM && Network.Routing.InCacheArea(user)) || (GlobalIM && Core.Buddies.BuddyList.SafeContainsKey(user))))) { Cache.Research(user); } // ensure we have the lastest versions of the user's services if (file != null) { CheckTags(file.UserID); } }
public void AddAddress(OpCore core, DhtAddress address, bool moveFront) { AddAddress(core, new RudpAddress(address), moveFront); // limit 5, remove oldest addresses, but not untried ones if (Addresses.Count > 5) { foreach (RudpAddress old in (from a in Addresses orderby a.LastAck select a).ToArray()) { if (Addresses.Count <= 5) { break; } if (old.LastAck == default(DateTime)) { continue; } Addresses.Remove(old); } } }
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); }
void Search_Found(DhtSearch search, DhtAddress source, byte[] data) { G2Header root = new G2Header(data); if (!G2Protocol.ReadPacket(root)) { return; } UpdateInfo info = UpdateInfo.Decode(root); // verifies signature if (info == null) { return; } if (Core.Context.SignedUpdate == null || Core.Context.SignedUpdate.SequentialVersion < info.SequentialVersion) { Core.Context.SignedUpdate = info; LookupConfig.WriteUpdateInfo(Core); } // version less than what we have else if (Core.Context.SignedUpdate.SequentialVersion > info.SequentialVersion) { return; } // version remote has already loaded if (Core.Context.SignedUpdate.Loaded) { return; } // same sources will be hit as file download search progresses StartDownload(search.TargetID); }
// outbound public TcpConnect(TcpHandler control, DhtAddress address, ushort tcpPort) { Debug.Assert(address.UserID != 0); TcpControl = control; Network = TcpControl.Network; Core = TcpControl.Core; Bandwidth = new BandwidthLog(Core.RecordBandwidthSeconds); Outbound = true; RemoteIP = address.IP; TcpPort = tcpPort; UdpPort = address.UdpPort; UserID = address.UserID; try { IPEndPoint endpoint = new IPEndPoint(RemoteIP, TcpPort); if (Core.Sim != null) { Core.Sim.Internet.SendPacket(SimPacketType.TcpConnect, Network, null, endpoint, this); return; } TcpSocket = new Socket(address.IP.AddressFamily, SocketType.Stream, ProtocolType.Tcp); TcpSocket.BeginConnect((EndPoint)endpoint, new AsyncCallback(Socket_Connect), TcpSocket); } catch (Exception ex) { LogException("TcpSocket", ex.Message); Disconnect(); } }
void Store_Patch(DhtAddress source, byte[] data) { if (data.Length < 9) return; ulong user = BitConverter.ToUInt64(data, 0); if (!Network.Routing.InCacheArea(user)) return; uint version = CompactNum.ToUInt32(data, 8, data.Length - 8); OpVersionedFile vfile = GetFile(user); if (vfile != null && vfile.Header != null) { if (vfile.Header.Version > version) { Store.Send_StoreReq(source, null, new DataReq(null, vfile.UserID, Service, DataType, vfile.SignedHeader)); return; } vfile.Unique = false; // network has current or newer version if (vfile.Header.Version == version) return; // else our version is old, download below } if (Network.Established) Network.Searches.SendDirectRequest(source, user, Service, DataType, BitConverter.GetBytes(version)); else DownloadLater[user] = version; }
void Search_Found(DhtSearch search, DhtAddress source, byte[] data) { DataReq store = new DataReq(source, search.TargetID, ServiceID, 0, data); Store_Local(store); }
public void Send_StoreReq(DhtAddress address, DhtClient localProxy, DataReq publish) { if (address == null) return; StoreReq store = new StoreReq(); store.Source = Network.GetLocalSource(); store.Key = publish.Target; store.Service = publish.Service; store.DataType = publish.DataType; store.Data = publish.Data; int sentBytes = 0; TcpConnect direct = Network.TcpControl.GetProxy(address); if (direct != null) sentBytes = direct.SendPacket(store); else if (address.TunnelClient != null) sentBytes = Network.SendTunnelPacket(address, store); // if blocked send tcp with to tag else if (Core.Firewall == FirewallType.Blocked) { store.ToAddress = address; TcpConnect proxy = Network.TcpControl.GetProxy(localProxy); if (proxy != null) sentBytes = proxy.SendPacket(store); else sentBytes = Network.TcpControl.SendRandomProxy(store); } else sentBytes = Network.UdpControl.SendTo(address, store); Core.ServiceBandwidth[store.Service].OutPerSec += sentBytes; }
void Search_Found(DhtSearch search, DhtAddress source, byte[] data) { Store_Local(new DataReq(source, search.TargetID, Service, DataType, data)); }
public RudpAddress(DhtAddress address, TcpConnect proxy) { Address = address; LocalProxy = new DhtClient(proxy); }
public void PublishDirect(List<LocationData> locations, ulong target, uint service, uint datatype, byte[] data) { if (Core.InvokeRequired) { Core.RunInCoreAsync(delegate() { PublishDirect(locations, target, service, datatype, data); }); return; } DataReq req = new DataReq(null, target, service, datatype, data); foreach (LocationData location in locations) { DhtAddress address = new DhtAddress(location.IP, location.Source); Send_StoreReq(address, null, req); foreach (DhtAddress proxy in location.Proxies) Send_StoreReq(proxy, null, req); } }
void Store_Patch(DhtAddress source, byte[] data) { if (!Network.Established || data.Length < 8) return; ulong user = BitConverter.ToUInt64(data, 0); if (!Network.Routing.InCacheArea(user)) return; if (!CachedData.Any(d => d.TargetID == user)) Network.Searches.SendDirectRequest(source, user, ServiceID, DataType, null); }
private void Receive_Patch(DhtAddress source, byte[] data) { // invoke patch G2Header root = new G2Header(data); if (G2Protocol.ReadPacket(root)) if (root.Name == StorePacket.Patch) { PatchPacket packet = PatchPacket.Decode(root); if (packet == null) return; foreach (PatchTag patch in packet.PatchData) if (PatchEvent.Contains(patch.Service, patch.DataType)) PatchEvent[patch.Service, patch.DataType].Invoke(source, patch.Tag); } }
void Search_Found(DhtSearch search, DhtAddress source, byte[] data) { G2Header root = new G2Header(data); if (!G2Protocol.ReadPacket(root)) return; UpdateInfo info = UpdateInfo.Decode(root); // verifies signature if (info == null) return; if (Core.Context.SignedUpdate == null || Core.Context.SignedUpdate.SequentialVersion < info.SequentialVersion) { Core.Context.SignedUpdate = info; LookupConfig.WriteUpdateInfo(Core); } // version less than what we have else if (Core.Context.SignedUpdate.SequentialVersion > info.SequentialVersion) return; // version remote has already loaded if (Core.Context.SignedUpdate.Loaded) return; // same sources will be hit as file download search progresses StartDownload(search.TargetID); }
public static RudpPacket Decode(G2Header root) { RudpPacket gc = new RudpPacket(); if (G2Protocol.ReadPayload(root)) { gc.Payload = Utilities.ExtractBytes(root.Data, root.PayloadPos, root.PayloadSize); } G2Protocol.ResetPacket(root); G2Header child = new G2Header(root.Data); while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD) { if (!G2Protocol.ReadPayload(child)) { continue; } switch (child.Name) { case Packet_SenderDht: gc.SenderID = BitConverter.ToUInt64(child.Data, child.PayloadPos); break; case Packet_SenderClient: gc.SenderClient = BitConverter.ToUInt16(child.Data, child.PayloadPos); break; case Packet_TargetDht: gc.TargetID = BitConverter.ToUInt64(child.Data, child.PayloadPos); break; case Packet_TargetClient: gc.TargetClient = BitConverter.ToUInt16(child.Data, child.PayloadPos); break; case Packet_Type: gc.PacketType = child.Data[child.PayloadPos]; break; case Packet_ID: gc.PeerID = BitConverter.ToUInt16(child.Data, child.PayloadPos); break; case Packet_Seq: gc.Sequence = (byte)child.Data[child.PayloadPos]; break; case Packet_Ident: gc.Ident = BitConverter.ToUInt32(child.Data, child.PayloadPos); break; case Packet_To: gc.ToAddress = DhtAddress.ReadPacket(child); break; case Packet_Proxy: gc.RemoteProxy = DhtAddress.ReadPacket(child); break; } } return(gc); }
void Search_FoundTemp(DhtSearch search, DhtAddress source, byte[] data) { object[] carry = search.Carry as object[]; object hostArg = carry[0]; Action<byte[], object> hostFoundEvent = carry[1] as Action<byte[], object>; OpCore sourceCore = carry[2] as OpCore; // strip temp data TempData temp = TempData.Decode(search.TargetID, data); if (temp == null) return; Action FireEvent = () => hostFoundEvent.Invoke(temp.Data, hostArg); // fire host event with carry vars if (sourceCore != null) sourceCore.RunInCoreAsync(FireEvent); else FireEvent.Invoke(); }
// nodes in lookup proxy mode are psuedo-open, instead of udp they send tunneled packets // tunnel packets include routing information to the lookup target as well as // the encrytped operation packet embedded in the payload public int SendTunnelPacket(DhtAddress contact, G2Packet embed) { Debug.Assert(contact.TunnelClient != null && contact.TunnelServer != null); Debug.Assert(Core.Context.Lookup != null); Debug.Assert(!IsLookup); Debug.Assert(Core.User.Settings.OpAccess != AccessType.Secret); if (IsLookup || Core.Context.Lookup == null || Core.User.Settings.OpAccess == AccessType.Secret) return 0; OpCore lookup = Core.Context.Lookup; // tunnel packet through lookup network byte[] encoded = embed.Encode(Protocol); PacketLogEntry logEntry = new PacketLogEntry(Core.TimeNow, TransportProtocol.Tunnel, DirectionType.Out, contact, encoded); LogPacket(logEntry); TunnelPacket packet = new TunnelPacket(); // encrypt, turn off encryption during simulation if (Core.Sim == null || Core.Sim.Internet.TestEncryption) packet.Payload = Utilities.EncryptBytes(encoded, GetAugmentedKey(contact.UserID)); else packet.Payload = encoded; packet.Source = new TunnelAddress(lookup.Network.Local, Core.TunnelID); packet.Target = contact.TunnelClient; int bytesSent = 0; // if we are the tunnel server (our lookup net is open, but op is blocked) if (lookup.Network.Local.Equals(contact.TunnelServer)) // use dhtclient compare { lookup.RunInCoreAsync(delegate() { TcpConnect direct = lookup.Network.TcpControl.GetProxy(packet.Target); if (direct != null) { packet.SourceServer = new DhtAddress(Core.LocalIP, lookup.Network.GetLocalSource()); bytesSent = direct.SendPacket(packet); } }); return bytesSent; } // if not open send proxied through local lookup proxy // NAT as well because receiver would need to send all responses through same local lookup proxy // for NATd host to get replies if (Core.Firewall != FirewallType.Open) { packet.TargetServer = contact.TunnelServer; lookup.RunInCoreAsync(delegate() { TcpConnect server = lookup.Network.TcpControl.GetProxy(packet.TargetServer) ?? // direct path lookup.Network.TcpControl.GetProxyServer(contact.IP) ?? // reRoute through same server lookup.Network.TcpControl.GetRandomProxy(); // random proxy if (server != null) { packet.SourceServer = new DhtAddress(server.RemoteIP, server); bytesSent = server.SendPacket(packet); } }); } // else we are open, send op ip address in the souce server else { packet.SourceServer = new DhtAddress(Core.LocalIP, lookup.Network.GetLocalSource()); lookup.RunInCoreAsync(delegate() { bytesSent = lookup.Network.UdpControl.SendTo(contact.TunnelServer, packet); }); } return bytesSent; }
public int SendTo(DhtAddress address, G2Packet packet) { if (Core.InvokeRequired) { Debug.Assert(false); } Debug.Assert(address.UdpPort != 0); 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.Udp, DirectionType.Out, address, 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.GetAugmentedKey(address.UserID)); } else { final = encoded; } // send try { if (Core.Sim != null) { Core.Sim.Internet.SendPacket(SimPacketType.Udp, Network, final, address.ToEndPoint(), null); } else { if (UdpSocket == null) { return(0); } if (encoded.Length > MAX_UDP_SIZE) { throw new Exception("Packet larger than " + MAX_UDP_SIZE.ToString() + " bytes"); } UdpSocket.BeginSendTo(final, 0, final.Length, SocketFlags.None, address.ToEndPoint(), new AsyncCallback(UdpSocket_SendTo), UdpSocket); } // record bandwidth Bandwidth.OutPerSec += final.Length; return(final.Length); } catch (Exception ex) { Network.UpdateLog("Exception", "UdpHandler::SendTo: " + ex.Message); } return(0); }
// sends a direct request, no acks are returned, if host has what is requested it sends a store request as a reply // make sure whatevers calling this handles the resulting store request public void SendDirectRequest(DhtAddress dest, ulong target, uint service, uint datatype, byte[] parameters) { SearchReq request = new SearchReq(); request.Source = Network.GetLocalSource(); request.TargetID = target; request.Service = service; request.DataType = datatype; request.Parameters = parameters; request.Nodes = false; int sentBytes = 0; TcpConnect socket = Network.TcpControl.GetProxy(dest); if (socket != null) sentBytes = socket.SendPacket(request); else if (dest.TunnelClient != null) sentBytes = Network.SendTunnelPacket(dest, request); else if (Core.Firewall == FirewallType.Blocked) { request.ToAddress = dest; sentBytes = Network.TcpControl.SendRandomProxy(request); } else sentBytes = Network.UdpControl.SendTo(dest, request); Core.ServiceBandwidth[request.Service].OutPerSec += sentBytes; // if remote end has what we need they will send us a store request }
public void MakeOutbound( DhtAddress address, ushort tcpPort, string reason) { try { int connecting = 0; // check if already connected lock(SocketList) foreach (TcpConnect socket in SocketList) { if (socket.State == TcpState.Connecting) connecting++; if (socket.State != TcpState.Closed && address.IP.Equals(socket.RemoteIP) && tcpPort == socket.TcpPort && socket.Outbound) // allows check firewall to work return; } if (connecting > 6) { Debug.Assert(true); return; } TcpConnect outbound = new TcpConnect(this, address, tcpPort); Network.UpdateLog("Tcp", "Attempting Connection to " + address.ToString() + ":" + tcpPort.ToString() + " (" + reason + ")"); lock(SocketList) SocketList.Add(outbound); } catch(Exception ex) { Network.UpdateLog("Exception", "TcpHandler::MakeOutbound: " + ex.Message); } }
private void Process_LocationData(DataReq data, SignedData signed, LocationData location) { Core.IndexKey(location.UserID, ref location.Key); Debug.Assert(location.UserID == location.Source.UserID); if (location.UserID != location.Source.UserID) { return; } ClientInfo client = GetLocationInfo(location.UserID, location.Source.ClientID); // check location version if (client != null) { if (location.Version == client.Data.Version) { return; } else if (location.Version < client.Data.Version) { if (data != null && data.Source != null) { Network.Store.Send_StoreReq(data.Source, data.LocalProxy, new DataReq(null, client.Data.UserID, ServiceID, 0, client.SignedData)); } return; } } Core.IndexName(location.UserID, location.Name); // notify components of new versions (usually just localsync service signed up for this) DhtAddress address = new DhtAddress(location.IP, location.Source); foreach (PatchTag tag in location.Tags) { if (TagReceived.Contains(tag.Service, tag.DataType)) { TagReceived[tag.Service, tag.DataType].Invoke(address, location.UserID, tag.Tag); } } // add location if (client == null) { // if too many clients, and not us, return if (location.UserID != Core.UserID && ActiveClientCount(location.UserID) > MaxClientsperUser) { return; } client = new ClientInfo(location); Clients.SafeAdd(client.RoutingID, client); // dont need to worry about remote caching old locs indefinitely because if a loc is cached remotely // that means the remote is being continuall pinged, or else the loc would expire // if we're still interested in loc after a min, it will be pinged locally } client.Data = location; client.SignedData = signed.Encode(Network.Protocol); if (client.Data.UserID == Core.UserID && client.Data.Source.ClientID == Network.Local.ClientID) { LocalClient = client; } AddRoutingData(location); // only get down here if loc was new version in first place (recently published) // with live comm trickle down this prevents highers from being direct ping flooded to find their // online status client.LastSeen = Core.TimeNow; SignalUpdate(client, true); }
public int SendTo(DhtAddress address, G2Packet packet) { if (Core.InvokeRequired) Debug.Assert(false); Debug.Assert(address.UdpPort != 0); 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.Udp, DirectionType.Out, address, 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.GetAugmentedKey(address.UserID)); else final = encoded; // send try { if (Core.Sim != null) { Core.Sim.Internet.SendPacket(SimPacketType.Udp, Network, final, address.ToEndPoint(), null); } else { if (UdpSocket == null) return 0; if (encoded.Length > MAX_UDP_SIZE) throw new Exception("Packet larger than " + MAX_UDP_SIZE.ToString() + " bytes"); UdpSocket.BeginSendTo(final, 0, final.Length, SocketFlags.None, address.ToEndPoint(), new AsyncCallback(UdpSocket_SendTo), UdpSocket); } // record bandwidth Bandwidth.OutPerSec += final.Length; return final.Length; } catch(Exception ex) { Network.UpdateLog("Exception", "UdpHandler::SendTo: " + ex.Message); } return 0; }
public void Found(byte[] value, DhtAddress source) { if(FoundEvent != null) FoundEvent.Invoke(this, source, value); foreach (byte[] found in FoundValues) if(Utilities.MemCompare(found, value)) return; FoundValues.Add(value); }
void Store_Patch(DhtAddress source, byte[] data) { if (data.Length % PatchEntrySize != 0) return; int offset = 0; for (int i = 0; i < data.Length; i += PatchEntrySize) { ulong user = BitConverter.ToUInt64(data, i); PostUID uid = PostUID.FromBytes(data, i + 8); ushort version = BitConverter.ToUInt16(data, i + 24); offset += PatchEntrySize; if (!Network.Routing.InCacheArea(user)) continue; OpPost post = GetPost(user, uid); if (post != null) { // remote version is lower, send update if (post.Header.Version > version) { Store.Send_StoreReq(source, null, new DataReq(null, user, ServiceID, 0, post.SignedHeader)); continue; } // version equal, pass post.Unique = false; // network has current or newer version if (post.Header.Version == version) continue; // else our version is old, download below } // download cause we dont have it or its a higher version if (Network.Established) Network.Searches.SendDirectRequest(source, user, ServiceID, 0, uid.ToBytes()); else { List<PostUID> list = null; if (!DownloadLater.SafeTryGetValue(user, out list)) { list = new List<PostUID>(); DownloadLater.SafeAdd(user, list); } list.Add(uid); } } }
public static LocationData Decode(byte[] data) { G2Header root = new G2Header(data); G2Protocol.ReadPacket(root); if (root.Name != LocationPacket.Data) { return(null); } LocationData loc = new LocationData(); G2Header child = new G2Header(root.Data); while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD) { if (!G2Protocol.ReadPayload(child)) { continue; } switch (child.Name) { case Packet_Key: loc.Key = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize); loc.UserID = Utilities.KeytoID(loc.Key); break; case Packet_Source: loc.Source = DhtSource.ReadPacket(child); loc.UserID = loc.Source.UserID; // encode light doesnt send full key break; case Packet_IP: loc.IP = new IPAddress(Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize)); break; case Packet_Proxies: loc.Proxies.Add(DhtAddress.ReadPacket(child)); break; case Packet_Name: loc.Name = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize); break; case Packet_Place: loc.Place = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize); break; case Packet_Version: loc.Version = CompactNum.ToUInt32(child.Data, child.PayloadPos, child.PayloadSize); break; case Packet_GMTOffset: loc.GmtOffset = BitConverter.ToInt32(child.Data, child.PayloadPos); break; case Packet_Away: loc.Away = BitConverter.ToBoolean(child.Data, child.PayloadPos); break; case Packet_AwayMsg: loc.AwayMessage = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize); break; case Packet_Tag: loc.Tags.Add(PatchTag.FromBytes(child.Data, child.PayloadPos, child.PayloadSize)); break; case Packet_TunnelClient: loc.TunnelClient = TunnelAddress.FromBytes(child.Data, child.PayloadPos); break; case Packet_TunnelServers: loc.TunnelServers.Add(DhtAddress.ReadPacket(child)); break; } } return(loc); }
void Search_FoundTime(DhtSearch search, DhtAddress source, byte[] data) { OpBoard board = GetBoard(search.TargetID); if (data.Length < TheadSearch_ResultsSize) return; PostUID uid = PostUID.FromBytes(data, 0); ushort version = BitConverter.ToUInt16(data, 16); OpPost post = GetPost(search.TargetID, uid); if (post != null) if (post.Header.Version >= version) return; PostSearch(search.TargetID, uid, version); }
void Search_FoundThread(DhtSearch search, DhtAddress source, byte[] data) { if (data.Length < TheadSearch_ResultsSize) return; PostUID uid = PostUID.FromBytes(data, 0); ushort version = BitConverter.ToUInt16(data, 16); ushort replies = BitConverter.ToUInt16(data, 18); OpPost post = GetPost(search.TargetID, uid); if (post != null) { if (post.Replies < replies) { post.Replies = replies; UpdateGui(post); } // if we have current version, pass, else download if (post.Header.Version >= version) return; } PostSearch(search.TargetID, uid, version); // if parent save replies value if (replies != 0) { int hash = search.TargetID.GetHashCode() ^ uid.GetHashCode(); ushort savedReplies = 0; if (SavedReplyCount.SafeTryGetValue(hash, out savedReplies)) if (savedReplies < replies) SavedReplyCount.SafeAdd(hash, replies); } }
public void SendRequest(DhtAddress address, UInt64 targetID, uint searchID, uint service, uint datatype, byte[] parameters) { SearchReq request = new SearchReq(); request.Source = Network.GetLocalSource(); request.SearchID = searchID; request.TargetID = targetID; request.Service = service; request.DataType = datatype; request.Parameters = parameters; int sentBytes = 0; TcpConnect direct = Network.TcpControl.GetProxy(address); if (direct != null) sentBytes = direct.SendPacket(request); else sentBytes = Network.SendPacket(address, request); Core.ServiceBandwidth[request.Service].OutPerSec += sentBytes; }
public RudpAddress(DhtAddress address) { Address = address; }
public int SendPacket(DhtAddress contact, G2Packet packet) { if (contact.TunnelServer != null) return SendTunnelPacket(contact, packet); else return UdpControl.SendTo(contact, packet); }
void Locations_TagReceived(DhtAddress address, ulong user, byte[] tag) { // if user not cached, we only active search their info if in local cache area if (tag.Length == 0) return; uint version = 0; OpVersionedFile file = Cache.GetFile(user); if (file != null) { version = CompactNum.ToUInt32(tag, 0, tag.Length); if (version < file.Header.Version) Store.Send_StoreReq(address, null, new DataReq(null, file.UserID, ServiceID, DataTypeSync, file.SignedHeader)); } // get new version of local sync file if ( (file != null && version > file.Header.Version) || (file == null && ( ( !GlobalIM && Network.Routing.InCacheArea(user)) || ( GlobalIM && Core.Buddies.BuddyList.SafeContainsKey(user)) ))) { Cache.Research(user); } // ensure we have the lastest versions of the user's services if (file != null) CheckTags(file.UserID); }