protected void HandleRequestAck(ReqrepType rt, int idnum, MemBlock rest, ISender ret_path) { RequestState reqs; lock ( _sync ) { if (_req_state_table.TryGet(idnum, out reqs)) { if (reqs.AddAck(ret_path)) { /* * Let's look at how long it took to get this reply: */ TimeSpan rtt = DateTime.UtcNow - reqs.ReqDate; if (ret_path is Edge) { _edge_reqtimeout = ComputeNewTimeOut(rtt.TotalMilliseconds, _edge_rtt_stats, _MINIMUM_TIMEOUT, _STD_DEVS); } else { _nonedge_reqtimeout = ComputeNewTimeOut(rtt.TotalMilliseconds, _nonedge_rtt_stats, _MINIMUM_TIMEOUT, _STD_DEVS); } } } } }
/// <summary>Change in either local or remote IDs, time to update the /// header to match.</summary> protected void UpdateHeader() { byte[] header = new byte[8]; NumberSerializer.WriteInt(_local_id, header, SOURCE_OFFSET); NumberSerializer.WriteInt(_remote_id, header, DESTINATION_OFFSET); _header = MemBlock.Reference(header); }
/// <summary>This is the generic Put that is used by both the regular Put /// and Create methods. The use of the unique variable differentiates the /// two. This is asynchronous. Results are stored in the Channel returns. /// Creates and Puts return true if successful or exception if there are /// network errors in adding the entry, creates also fail if a previous /// entry exists. The work of determining success is handled in /// PutEnqueueHandler and PutCloseHandler.</summary> /// <param name="key">The index to store the value at.</param> /// <param name="value">The value to store.</param> /// <param name="ttl">The dht lease time for the key:value pair.</param> /// <param name="returns">The Channel where the result will be placed.</param> /// <param name="unique">True to do a create, false otherwise.</param> public void AsyncPut(MemBlock key, MemBlock value, int ttl, Channel returns, bool unique) { if (!_online) { throw new DhtException("The Node is (going) offline, DHT is offline."); } AsDhtPutState adps = new AsDhtPutState(returns); MemBlock[] brunet_address_for_key = MapToRing(key); Channel[] q = new Channel[DEGREE]; lock (_adps_table.SyncRoot) { for (int k = 0; k < DEGREE; k++) { Channel queue = new Channel(1); queue.CloseEvent += this.PutCloseHandler; _adps_table[queue] = adps; q[k] = queue; } } for (int k = 0; k < DEGREE; k++) { Address target = new AHAddress(brunet_address_for_key[k]); AHSender s = new AHGreedySender(Node, target); _rpc.Invoke(s, q[k], "dht.Put", brunet_address_for_key[k], value, ttl, unique); } }
/** * <summary>Deletes all expired entries for the specified key. For each entry * deleted, count is decremented. This should be called before accessing the * data stored in this table.</summary> * <param name="key">The index to check for expired entries.</param> * <returns>The amount of entries deleted.</returns> */ public int DeleteExpired(MemBlock key) { LinkedList <Entry> data = (LinkedList <Entry>)_data[key]; if (data == null) { return(0); } DateTime now = DateTime.UtcNow; LinkedListNode <Entry> current = data.First; while (current != null) { if (current.Value.EndTime > now) { break; } LinkedListNode <Entry> next = current.Next; data.Remove(current); current = next; count--; } int lcount = data.Count; if (data.Count == 0) { list_of_keys.Remove(key); _data.Remove(key); } return(lcount); }
/// <summary>This parses a MemBlock into the Ethernet fields</summary> /// <param name="Packet">The Ethernet packet</param> public EthernetPacket(MemBlock Packet) { _icpacket = _packet = Packet; DestinationAddress = Packet.Slice(0, 6); SourceAddress = Packet.Slice(6, 6); Type = (Types) ((Packet[12] << 8) | Packet[13]); _icpayload = _payload = Packet.Slice(14); }
static EthernetPacket() { Random _rand = new Random(); byte[] unicast = new byte[6]; _rand.NextBytes(unicast); unicast[0] = 0xFE; UnicastAddress = MemBlock.Reference(unicast); }
public IcmpPacket(Types type, short id, short seq_num) { Type = type; Identifier = id; SequenceNumber = seq_num; Code = (byte)0; byte[] msg = new byte[64]; Random rand = new Random(); rand.NextBytes(msg); msg[0] = (byte)type; msg[1] = Code; msg[2] = (byte)0; msg[3] = (byte)0; NumberSerializer.WriteShort(Identifier, msg, 4); NumberSerializer.WriteShort(SequenceNumber, msg, 6); short checksum = (short)IPPacket.GenerateChecksum(MemBlock.Reference(msg)); NumberSerializer.WriteShort(checksum, msg, 2); _icpacket = MemBlock.Reference(msg); _packet = MemBlock.Reference(msg); }
/** * When we get a reply ack, we can remove the item from our cache, * we know the other guy got our reply */ protected void HandleReplyAck(ReqrepType rt, int idnum, MemBlock err_data, ISender ret_path) { RequestKey rk = new RequestKey(idnum, ret_path); lock ( _sync ) { /** * This is not completely safe, but probably fine. Consider the * case where: * A -(req)-> B * A timeout but B does get the req * A <-(rep)- B * A -(req)-> B (these cross in flight) * A -(repack)-> B * * but then the repack passes the req retransmission (out of order * delivery) * * This is unlikely, but we could improve it. * @todo improve the reply caching algorithm */ ReplyState rs = (ReplyState)_reply_cache[rk]; if (rs != null) { ReleaseReplyState(rs); } } }
/// <summary>Continues a broadcast to the overlay.</summary> public BroadcastSender(StructuredNode node, AHAddress source, AHAddress from, AHAddress to, int forwarders, int hops) { Node = node; Source = source; From = from; To = to; _distance_sorter = new AbsoluteDistanceComparer(node.Address as AHAddress); _address_sorter = new LeftDistanceComparer(node.Address as AHAddress); Forwarders = forwarders; Hops = hops; byte[] hops_data = new byte[4]; NumberSerializer.WriteInt(hops, hops_data, 0); _hops = MemBlock.Reference(hops_data); if (forwarders == DEFAULT_FORWARDERS) { _forwarders = DEFAULT_FORWARDERS_MB; } else { byte[] def = new byte[4]; NumberSerializer.WriteInt(forwarders, def, 0); _forwarders = MemBlock.Reference(def); } }
/** * <summary>Attempts to store the key:value pair into this server.</summary> * <remarks>First the dht deletes any expired entries stored at the key, * second it retrieves the entries from the data store. If it is empty it * creates a new entry and returns. Otherwise, it looks for the value in * the list and updates the lease time. If there is no entry for that * key:value pair it either adds it in the case of a put or throws an * exception if it is a create.</remarks> * <param name="key">The index to store the data at.</param> * <param name="value">Data to store at the key.</param> * <param name="ttl">Dht lease time in seconds</param> * <param name="unique">True if this should perform a create, false otherwise. * </param> * <returns>True on success, thrown exception on failure</returns> * <exception cref="Exception">Data is too large, unresolved remote issues, * or the create is no successful</exception> */ public bool PutHandler(MemBlock key, MemBlock value, int ttl, bool unique) { DateTime create_time = DateTime.UtcNow; DateTime end_time = create_time.AddSeconds(ttl); lock (_sync) { _data.DeleteExpired(key); LinkedList <Entry> data = _data.GetEntries(key); if (data != null) { foreach (Entry ent in data) { if (ent.Value.Equals(value)) { if (end_time > ent.EndTime) { _data.UpdateEntry(ent.Key, ent.Value, end_time); } return(true); } } // If this is a create we didn't find an previous entry, so failure, else add it if (unique) { throw new Exception("ENTRY_ALREADY_EXISTS"); } } // This is either a new key or a new value (put only) Entry e = new Entry(key, value, create_time, end_time); _data.AddEntry(e); } // end of lock return(true); }
/** <summary>Takes in a MemBlock and parses it as a Udp Packet.</summary> <param name="packet">The MemBlock containing the Udp Packet</param> */ public UdpPacket(MemBlock packet) { _icpacket = _packet = packet; SourcePort = (packet[0] << 8) | packet[1]; DestinationPort = (packet[2] << 8) | packet[3]; _icpayload = _payload = packet.Slice(8); }
/// <summary>Initializes the Ethernet device by opening the TAP device and /// starting the ISource thread.</summary> /// <param name="tap">The name of the TAP device on the host.</param> public Ethernet(string device_name) { for (int i = 0; i < 15; i++) { try { _tap = Ipop.Tap.TapDevice.GetTapDevice(device_name); break; } catch {} Thread.Sleep(2); ProtocolLog.WriteIf(ProtocolLog.Exceptions, "Unable to set up the tap, trying again..."); } if (_tap == null) { ProtocolLog.WriteIf(ProtocolLog.Exceptions, "Unable to set up the tap."); Environment.Exit(1); } Address = _tap.Address; _running = true; _read_thread = new Thread(ReadLoop); _read_thread.IsBackground = true; _read_thread.Start(); }
public void Test() { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); byte[] blob = rsa.ExportCspBlob(false); RSACryptoServiceProvider rsa_pub = new RSACryptoServiceProvider(); rsa_pub.ImportCspBlob(blob); CertificateMaker cm = new CertificateMaker("United States", "UFL", "ACIS", "David Wolinsky", "*****@*****.**", rsa_pub, "brunet:node:abcdefghijklmnopqrs"); Assert.AreEqual("C=United States, O=UFL, OU=ACIS, CN=David Wolinsky, [email protected]", cm.Subject.DN, "DN test 1"); cm = new CertificateMaker(cm.UnsignedData); Assert.AreEqual("C=United States, O=UFL, OU=ACIS, CN=David Wolinsky, [email protected]", cm.Subject.DN, "DN test 2"); Certificate cert = cm.Sign(cm, rsa); Assert.IsTrue(cert.Signature != null, "Signature"); Assert.AreEqual(cm.Subject.DN, cert.Issuer.DN, "Issuer = Subject"); Assert.AreEqual("brunet:node:abcdefghijklmnopqrs", cert.NodeAddress, "Node address"); Mono.Math.BigInteger rsa_pub_bi = new Mono.Math.BigInteger(rsa_pub.ExportCspBlob(false)); Mono.Math.BigInteger cert_pub_bi = new Mono.Math.BigInteger(cert.PublicKey.ExportCspBlob(false)); Assert.AreEqual(rsa_pub_bi, cert_pub_bi, "Key"); SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); Assert.AreEqual(MemBlock.Reference(cert.SerialNumber), MemBlock.Reference(sha1.ComputeHash(cert.UnsignedData)), "SerialNumber == hash of unsigned data"); }
MemBlock m_WriteList; // 需要写的的队列 MemBlock AllockBlock(string url, int nFileOffset, int nDownSize, int nFileSize) { MemBlock pBlock = null; lock (this) { pBlock = m_InvalidBlock; if (m_InvalidBlock != null) { m_nUseBlockMemSize += 4096; m_InvalidBlock = m_InvalidBlock.m_pNext; } } if (pBlock == null) { pBlock = new MemBlock(); pBlock.data = new byte[4096]; // 固定4K lock (this) { m_nCurBlockMemSize += 4096; } } pBlock.url = url; pBlock.nFileOfset = nFileOffset; pBlock.nDownSize = nDownSize; pBlock.nFileSize = nFileSize; pBlock.resFile = null; return(pBlock); }
/** * <summary>Generates a path given a key.</summary> * <param name="key">The key to generate a path for.</param> * <param name="path">Returns the directory portion of the path.</param> * <param name="filename">Returns the filename portion of the path.</param> * <returns>The path for the key.</returns> */ public string GeneratePath(MemBlock key, out string path, out string filename) { if (Address.MemSize < 5) { throw new Exception("Address.MemSize must be greater than or equal to 5."); } string[] l = new string[5]; for (int j = 0; j < 4; j++) { l[j] = string.Empty; } l[0] = _base_dir; l[1] = key[0].ToString(); l[2] = key[1].ToString(); l[3] = key[2].ToString(); for (int i = 3; i < Address.MemSize - 2; i++) { l[4] += key[i].ToString(); } path = String.Join(Path.DirectorySeparatorChar.ToString(), l); filename = key[Address.MemSize - 1].ToString(); return(Path.Combine(path, filename)); }
public void TestPrimitiveTypes() { ArrayList expected_values = new ArrayList(); MemBlock e_mb = MemBlock.Reference(Encoding.UTF8.GetBytes("test memblock")); expected_values.Add(e_mb); float e_f = (float)Math.PI; expected_values.Add((double)e_f); ushort e_sh = 11; expected_values.Add(e_sh); ulong e_long = 11111111111; expected_values.Add(e_long); uint e_ui = 34; expected_values.Add(e_ui); _mrm.CurrentInvokeState.RetValues = expected_values.ToArray(); string target = this.GetRandomNodeAddr(); object[] ret = this._rpc.proxy(target, 3, -1, "Foo"); byte[] actual = (byte[])ret[0]; Assert.IsTrue(e_mb.Equals(actual)); float a_f = Convert.ToSingle((double)ret[1]); Assert.AreEqual(e_f, a_f); }
public void HandleData(MemBlock packet, ISender from, object node) { _message_count++; long stop_time, rt_ticks = -10000; if ( !from.Equals(node)) { if (packet[0] == 0) { //log.Debug("Echo Response:"); stop_time = System.DateTime.Now.Ticks; int received_uid = NumberSerializer.ReadInt(packet, 1); if(uid_starttime.ContainsKey(received_uid)){ rt_ticks = stop_time - (long)EchoTester.uid_starttime[received_uid]; } double rt_ms = (double) rt_ticks/10000.0; uid_brunetpingtime.Add(received_uid, rt_ms); Console.WriteLine("Packet ID = {0}, Round-trip = {1}", received_uid, rt_ms); } else { //log.Debug("Echo Request:"); } //log.Debug(packet.ToString()); //System.Console.WriteLine("{0}", packet.ToString()); if (packet[0] > 0) { //Send a reply back, this is a request byte[] new_payload = new byte[ packet.Length ]; packet.CopyTo(new_payload, 0); new_payload[0] = (byte) 0; from.Send(new CopyList(PType.Protocol.Echo, MemBlock.Reference(new_payload))); } } }
/** * This is either a request or response. Look up the handler * for it, and pass the packet to the handler */ public void HandleData(MemBlock p, ISender from, object state) { //Is it a request or reply? ReqrepType rt = (ReqrepType)((byte)p[0]); int idnum = NumberSerializer.ReadInt(p, 1); MemBlock rest = p.Slice(5); //Skip the type and the id if (rt == ReqrepType.Request || rt == ReqrepType.LossyRequest) { HandleRequest(rt, idnum, rest, from); } else if (rt == ReqrepType.Reply) { HandleReply(rt, idnum, rest, from); } else if (rt == ReqrepType.ReplyAck) { HandleReplyAck(rt, idnum, rest, from); } else if (rt == ReqrepType.RequestAck) { HandleRequestAck(rt, idnum, rest, from); } else if (rt == ReqrepType.Error) { HandleError(rt, idnum, rest, from); } }
public void HandleData(MemBlock payload, ISender return_path, object state) { if(_sub != null) { MemBlock rest = null; PType.Parse(payload, out rest); _sub.Handle(rest, return_path); } }
public void MDnsATest() { String Name = "david-laptop.local"; DnsPacket.Types Type = DnsPacket.Types.A; bool CacheFlush = true; DnsPacket.Classes Class = DnsPacket.Classes.IN; int Ttl = 120; String RData = "10.227.56.136"; Response rp = new Response(Name, Type, Class, CacheFlush, Ttl, RData); MemBlock am = MemBlock.Reference(new byte[] { 0x0c, 0x64, 0x61, 0x76, 0x69, 0x64, 0x2d, 0x6c, 0x61, 0x70, 0x74, 0x6f, 0x70, 0x05, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x00, 0x00, 0x01, 0x80, 0x01, 0x00, 0x00, 0x00, 0x78, 0x00, 0x04, 0x0a, 0xe3, 0x38, 0x88 }); Response rm = new Response(am, 0); Assert.AreEqual(rp.Packet, am, "Packet"); Assert.AreEqual(rm.Name, Name, "Name"); Assert.AreEqual(rm.Type, Type, "Type"); Assert.AreEqual(rm.Class, Class, "Class"); Assert.AreEqual(rm.CacheFlush, CacheFlush, "CacheFlush"); Assert.AreEqual(rm.Ttl, Ttl, "Ttl"); Assert.AreEqual(rm.RData, RData, "RData"); }
/** * Abandon any attempts to get requests for the given ID. * @throw Exception if handler is not the original handler for this Request */ public void StopRequest(int request_id, IReplyHandler handler) { RequestState rs = null; lock ( _sync ) { if (!_req_state_table.TryTake(request_id, out rs)) { rs = null; } } if (rs != null) { /* * Send an ack for this reply: */ byte[] ack_payload = new byte[5]; ack_payload[0] = (byte)ReqrepType.ReplyAck; NumberSerializer.WriteInt(request_id, ack_payload, 1); ICopyable data = new CopyList(_prefix, MemBlock.Reference(ack_payload)); foreach (ISender ret_path in rs.Repliers) { try { //Try to send an ack, but if we can't, oh well... ret_path.Send(data); } catch { } } } }
/** * <summary>This should be called if an entry already exists as it will find * the entry and update its lease time. If an entry does not exist nothing * happens.</summary> * <param name="key">The index to store the value.</param> * <param name="value">The data to store.</param> * <param name="end_time">The lease time for the data.</param> */ public void UpdateEntry(MemBlock key, MemBlock value, DateTime end_time) { CheckEntries(); LinkedList <Entry> data = (LinkedList <Entry>)_data[key]; if (data != null) { Entry entry = null; LinkedListNode <Entry> current = data.First; while (current != null) { if (current.Value.Value.Equals(value)) { entry = current.Value; data.Remove(current); break; } current = current.Next; } if (entry != null) { count--; entry.EndTime = end_time; AddEntry(entry); } } }
/// <summary>Always returns the oldest non-tunnel address.</summary> public virtual Address EvaluatePotentialOverlap(IDictionary msg) { Address oldest_addr = null; int oldest_age = -1; foreach (DictionaryEntry de in msg) { MemBlock key = de.Key as MemBlock; if (key == null) { key = MemBlock.Reference((byte[])de.Key); } Address addr = new AHAddress(key); Hashtable values = de.Value as Hashtable; TransportAddress.TAType tatype = TransportAddressFactory.StringToType(values["ta"] as string); if (tatype.Equals(TransportAddress.TAType.Tunnel)) { continue; } int age = (int)values["ct"]; if (age > oldest_age) { oldest_addr = addr; } } return(oldest_addr); }
public IgmpPacket(MemBlock packet) { _icpacket = _packet = packet; Type = packet[0]; GroupAddress = packet.Slice(4, 4); _icpayload = _payload = packet.Slice(8); }
/// <summary>Writes an IPPacket as is to the TAP device.</summary> /// <param name="packet">The IPPacket!</param> protected virtual void WriteIP(ICopyable packet) { MemBlock mp = packet as MemBlock; if (mp == null) { mp = MemBlock.Copy(packet); } IPPacket ipp = new IPPacket(mp); MemBlock dest = null; if (!_ip_to_ether.TryGetValue(ipp.DestinationIP, out dest)) { if (ipp.DestinationIP[0] >= 224 && ipp.DestinationIP[0] <= 239) { dest = EthernetPacket.GetMulticastEthernetAddress(ipp.DestinationIP); } else if (ipp.DestinationIP[3] == 255) { dest = EthernetPacket.BroadcastAddress; } else { return; } } EthernetPacket res_ep = new EthernetPacket(dest, EthernetPacket.UnicastAddress, EthernetPacket.Types.IP, mp); Ethernet.Send(res_ep.ICPacket); }
/// <summary>Tasks that should be performed during startup until completion /// and repetitive tasks are added here. protected void CheckNode(object o, EventArgs ea) { lock (_sync) { if (_dhcp_config == null) { GetDhcpConfig(); if (_dhcp_config == null) { return; } } // The rest doesn't quite work right yet... DateTime now = DateTime.UtcNow; if ((now - _last_check_node).TotalSeconds < 30) { return; } _last_check_node = now; } // Discover machines in on the LAN if they respond to ICMP requests WaitCallback wcb = delegate(object obj) { SendIcmpRequest(MemBlock.Reference(_dhcp_server.Broadcast)); }; ThreadPool.QueueUserWorkItem(wcb); }
/** * <summary>Generates an 16-bit IP (UDP, TCP) checksum based upon header and * optional extra memory blocks placed into args.</summary> * <param name="header">The Header to base the checksum on.</param> * <param name="args">Any extra memory blocks to include in checksum * calculations.</param> * <returns>a 16-bit IP header checksum.</returns> */ public static ushort GenerateChecksum(MemBlock header, params Object[] args) { int value = 0; int length = header.Length; for (int i = 0; i < length; i += 2) { byte first = header[i]; byte second = (length == i + 1) ? (byte)0 : header[i + 1]; value += second + (first << 8); } for (int j = 0; j < args.Length; j++) { MemBlock tmp = (MemBlock)args[j]; length = tmp.Length; for (int i = 0; i < length; i += 2) { byte first = tmp[i]; byte second = (length == i + 1) ? (byte)0 : tmp[i + 1]; value += second + (first << 8); } } while (value >> 16 > 0) { value = (value & 0xFFFF) + (value >> 16); } return((ushort)(~value & 0xFFFF)); }
/// <summary> /// Finds an available IP range on the system /// </summary> /// <param name="networkdevice">Device to be ignored</param> /// <param name="startip">Device to be ignored</param> /// <returns>Return IP to use</returns> public static MemBlock GetNetwork(string networkdevice, MemBlock startip) { MemBlock netip = startip; ArrayList used_networks = new ArrayList(); IPHostEntry entry = System.Net.Dns.GetHostEntry(String.Empty); foreach (IPAddress ip in entry.AddressList) { byte[] address = ip.GetAddressBytes(); address[2] = 0; address[3] = 0; used_networks.Add(MemBlock.Reference(address)); } while (used_networks.Contains(netip)) { byte[] tmp = new byte[netip.Length]; netip.CopyTo(tmp, 0); if (tmp[1] == 0) { throw new Exception("Out of Addresses!"); } tmp[1] -= 1; netip = MemBlock.Reference(tmp); } return(netip); }
public void Test() { MemBlock mdnsm = MemBlock.Reference(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x0E, 0x64, 0x61, 0x76, 0x69, 0x64, 0x69, 0x77, 0x2D, 0x6C, 0x61, 0x70, 0x74, 0x6F, 0x70, 0x05, 0x6C, 0x6F, 0x63, 0x61, 0x6C, 0x00, 0x00, 0xFF, 0x00, 0x01, 0xC0, 0x0C, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x78, 0x00, 0x04, 0x0A, 0xFE, 0x00, 0x01 }); DnsPacket mdns = new DnsPacket(mdnsm); String ss_ip = "10.254.112.232"; bool change = MDnsTranslator.mDnsTranslate(mdns.Answers, ss_ip); change |= MDnsTranslator.mDnsTranslate(mdns.Authority, ss_ip); change |= MDnsTranslator.mDnsTranslate(mdns.Additional, ss_ip); // If we make a change let's make a new packet! if (change) { mdns = new DnsPacket(mdns.ID, mdns.Query, mdns.Opcode, mdns.AA, mdns.RA, mdns.RD, mdns.Questions, mdns.Answers, mdns.Authority, mdns.Additional); } Assert.AreEqual(mdns.Authority[0].Name, "davidiw-laptop.local", "Name"); Assert.AreEqual(mdns.Authority[0].Type, DnsPacket.Types.A, "Type"); Assert.AreEqual(mdns.Authority[0].Class, DnsPacket.Classes.IN, "Class"); Assert.AreEqual(mdns.Authority[0].CacheFlush, false, "CacheFlush"); Assert.AreEqual(mdns.Authority[0].Ttl, 120, "Ttl"); Assert.AreEqual(mdns.Authority[0].RData, "10.254.112.232", "RData"); }
public void DnsPtrTest() { String Name = "64.233.169.104"; DnsPacket.Types Type = DnsPacket.Types.Ptr; DnsPacket.Classes Class = DnsPacket.Classes.IN; int Ttl = 30; String RData = "yo-in-f104.google.com"; Response rp = new Response(Name, Type, Class, Ttl, RData); MemBlock ptrm = MemBlock.Reference(new byte[] { 0x03, 0x31, 0x30, 0x34, 0x03, 0x31, 0x36, 0x39, 0x03, 0x32, 0x33, 0x33, 0x02, 0x36, 0x34, 0x07, 0x69, 0x6e, 0x2d, 0x61, 0x64, 0x64, 0x72, 0x04, 0x61, 0x72, 0x70, 0x61, 0x00, 0x00, 0x0c, 0x00, 0x01, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x17, 0x0a, 0x79, 0x6f, 0x2d, 0x69, 0x6e, 0x2d, 0x66, 0x31, 0x30, 0x34, 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03, 0x63, 0x6f, 0x6d, 0x00 }); Response rm = new Response(ptrm, 0); Assert.AreEqual(rp.Packet, ptrm, "Packet"); Assert.AreEqual(rm.Name, Name, "Name"); Assert.AreEqual(rm.Type, Type, "Type"); Assert.AreEqual(rm.Class, Class, "Class"); Assert.AreEqual(rm.Ttl, Ttl, "Ttl"); Assert.AreEqual(rm.RData, RData, "RData"); }
protected void SendControlPacket(EndPoint end, int remoteid, int localid, ControlCode c, object state) { using (MemoryStream ms = new MemoryStream()) { NumberSerializer.WriteInt((int)c, ms); if (c == ControlCode.EdgeDataAnnounce) { UdpEdge e = (UdpEdge)_id_ht[localid]; if ((e != null) && (e.RemoteID == remoteid)) { Hashtable t = new Hashtable(); t["RemoteTA"] = e.RemoteTA.ToString(); t["LocalTA"] = e.LocalTA.ToString(); AdrConverter.Serialize(t, ms); } else { if (ProtocolLog.UdpEdge.Enabled) { ProtocolLog.Write(ProtocolLog.UdpEdge, String.Format( "Problem sending EdgeData: EndPoint: {0}, remoteid: {1}, " + "localid: {2}, Edge: {3}", end, remoteid, localid, e)); } } } _send_queue.Enqueue(new UdpMessage(localid, ~remoteid, MemBlock.Reference(ms.ToArray()), end)); if (ProtocolLog.UdpEdge.Enabled) { ProtocolLog.Write(ProtocolLog.UdpEdge, String.Format( "Sending control {1} to: {0}", end, c)); } } }
protected void HandleError(ReqrepType rt, int idnum, MemBlock err_data, ISender ret_path) { //Get the request: RequestState reqs; bool act; lock ( _sync ) { ///@todo, we might not want to stop listening after one error act = _req_state_table.TryTake(idnum, out reqs); } if (act) { #if REQREP_DEBUG Console.Error.WriteLine("[ReqrepManager: {0}] Receiving error on request id: {1}, from: {2}", _info, idnum, ret_path); #endif ///@todo make sure we are checking that this ret_path makes sense for ///our request ReqrepError rrerr = (ReqrepError)err_data[0]; reqs.ReplyHandler.HandleError(this, idnum, rrerr, ret_path, reqs.UserState); } else { //We have already dealt with this Request } }
/* * Start sending packets */ public void Run() { byte[] buf = new byte[UInt16.MaxValue]; Random ran_obj = new Random(); for (int counter = 0; counter < count; counter++) { try { int size = ran_obj.Next(4, Int16.MaxValue); ran_obj.NextBytes(buf); NumberSerializer.WriteInt(counter, buf, 0); MemBlock cp = MemBlock.Copy(buf, 0, Math.Max(4, counter)); lock (_sync) { _sent_blocks[cp] = counter; } _e.Send(cp); Thread.Sleep(10); Console.WriteLine("Sending Packet #: " + counter); } catch (Exception x) { Console.WriteLine("send: {0} caused exception: {1}", counter, x); break; } } //Let all the responses get back Thread.Sleep(5000); Check(); _e.Close(); }
/** Parse without looking at the cache */ protected static Address NoCacheParse(string ascii) { string[] parts = ascii.Split(':'); //It should be: urn:brunet:node:[encoded address] // or brunet:node:[encoded address] int offset = 0; if (parts[0].ToLower() == "urn") { offset = 1; } string brunet = parts[offset].ToLower(); if (brunet != "brunet") { throw new ParseException ("String is not a properly formated Brunet Address:" + ascii); } string node = parts[offset + 1].ToLower(); if (node != "node") { throw new ParseException ("String is not a properly formated Brunet Address:" + ascii); } try { byte[] binadd = Base32.Decode(parts[offset + 2]); MemBlock mb = MemBlock.Reference(binadd); return(Parse(mb)); } catch (System.ArgumentOutOfRangeException ex) { throw new ParseException("Failed to parse Address string", ex); } }
public bool HandleReply(ReqrepManager man, ReqrepManager.ReqrepType rt, int mid, PType prot, MemBlock payload, ISender returnpath, ReqrepManager.Statistics statistics, object state) { DateTime reply_time = DateTime.UtcNow; ListDictionary res_dict = new ListDictionary(); AHSender ah_rp = returnpath as AHSender; if (ah_rp != null) { res_dict["target"] = ah_rp.Destination.ToString(); } //Here are the number of microseconds res_dict["musec"] = (int)(1000.0 * ((reply_time - _start_time).TotalMilliseconds)); //Send the RPC result now; RpcManager my_rpc = System.Threading.Interlocked.Exchange(ref _rpc, null); if (my_rpc != null) { //We have not sent any reply yet: my_rpc.SendResult(_req_state, res_dict); } return(false); }
/** * <summary>Disk caching is unsupported at this time.</summary> */ /* When we have a cache eviction, we must write it to disk, we take * each entry, convert it explicitly into a hashtable, and then use adr * to create a stream and write it to disk */ public void CacheEviction(Object o, EventArgs args) { Brunet.Collections.Cache.EvictionArgs eargs = (Brunet.Collections.Cache.EvictionArgs)args; MemBlock key = (MemBlock)eargs.Key; if (Dht.DhtLog.Enabled) { ProtocolLog.Write(Dht.DhtLog, String.Format( "Evicted out of cache {0}, entries in dht {1}, entries in cache {2}", (new BigInteger(key)).ToString(16), Count, _data.Count)); } if (eargs.Value != null && ((LinkedList <Entry>)eargs.Value).Count > 0) { LinkedList <Entry> data = (LinkedList <Entry>)eargs.Value; // AdrConverter doesn't support LinkedLists Entry[] entries = new Entry[data.Count]; data.CopyTo(entries, 0); Hashtable[] ht_entries = new Hashtable[entries.Length]; int index = 0; foreach (Entry entry in entries) { ht_entries[index++] = (Hashtable)entry; } string dir_path, filename; string file_path = GeneratePath(key, out dir_path, out filename); if (!Directory.Exists(dir_path)) { Directory.CreateDirectory(dir_path); } using (FileStream fs = File.Open(file_path, FileMode.Create)) { AdrConverter.Serialize(ht_entries, fs); } } }
public void HandleData(MemBlock payload, ISender return_path, object state) { _last_received = payload; _ht[payload] = return_path; _order.Add(payload); if(HandleDataCallback != null) { HandleDataCallback(payload, null); } }
static SecurityControlMessage() { byte[] empty_cookie = new byte[CookieLength]; for(int i = 0; i < CookieLength; i++) { empty_cookie[i] = 0; } EmptyCookie = MemBlock.Reference(empty_cookie); }
/** <summary>Create a DhtDns using the specified Dht object</summary> <param name="dht">A Dht object used to acquire name translations</param> */ public DhtDns(MemBlock ip, MemBlock netmask, string name_server, bool forward_queries, IDht dht, String ipop_namespace) : base(ip, netmask, name_server, forward_queries) { _ipop_namespace = ipop_namespace; _dht = dht; _sync = new object(); }
public void HandleData(MemBlock b, ISender return_path, object state) { byte b0 = b[0]; if( b0 == 0 ) { //This is a request: MemBlock data = b.Slice(1); //Make sure node to reply with a zero return_path.Send( new CopyList( PType.Protocol.Echo, REPLY_HEADER, data) ); } }
/** <summary>Takes in a MemBlock and parses it as a Udp Packet.</summary> <param name="packet">The MemBlock containing the Udp Packet</param> */ public UdpPacket(MemBlock packet) { if(packet.Length < 8) { throw new Exception("Invalid UDP Packet"); } _icpacket = _packet = packet; SourcePort = (packet[0] << 8) | packet[1]; DestinationPort = (packet[2] << 8) | packet[3]; _icpayload = _payload = packet.Slice(8); }
/// <summary>Translates an IP Address to a Brunet Address. If it is in the /// cache it returns a result, otherwise it returns null and begins a Miss /// lookup.</summary> /// <param name="ip">The IP Address to translate.</param> /// <returns>Null if none exists or there is a miss or the Brunet Address if /// one exists in the cache</returns> public Address Resolve(MemBlock ip) { Address addr; bool update; bool success = _cache.TryGetValue(ip, out addr, out update); if(update || !success) { Miss(ip); } return addr; }
/** Parse the first LENGTH bytes to get the AHHeader */ public AHHeader(MemBlock mb) { Hops = NumberSerializer.ReadShort(mb, 0); Ttl = NumberSerializer.ReadShort(mb, 2); //We parse the Address objects lazily Opts = (ushort)NumberSerializer.ReadShort(mb, 2 * Address.MemSize + 4); if( mb.Length != LENGTH ) { mb = mb.Slice(0,LENGTH); } _data = mb; }
public void HandleData(MemBlock data, ISender return_path, object state) { /* * Write the messages: */ Console.WriteLine("Msg from: {0}", return_path); data.ToMemoryStream().WriteTo( System.Console.OpenStandardOutput() ); Console.WriteLine(); return_path.Send( new CopyList(PType.Protocol.Chat, MemBlock.Null) ); }
public DataPacket(ICopyable packet) { _update_icpacket = false; _update_packet = false; _icpacket = packet; _packet = packet as MemBlock; if(_packet == null) { _update_packet = true; } }
protected AHHeader(short hops, AHHeader head) { //Set a new number of hops: Hops = hops; //Copy the rest: Ttl = head.Ttl; Opts = head.Opts; _src = head._src; _dest = head._dest; _data = head._data; }
/// <summary> /// This method replaces IP addresses based on some identifier /// </summary> /// <param name="payload">Payload to be translated</param> /// <param name="old_ss_ip">Old source IP address</param> /// <param name="old_sd_ip">Old destination IP</param> /// <param name="new_ss_ip">New source IP address</param> /// <param name="new_sd_ip">New destination IP address</param> /// <param name="packet_id">A packet identifier</param> /// <returns>A MemBlock of the translated payload</returns> public static MemBlock TextTranslate(MemBlock payload, string old_ss_ip, string old_sd_ip, string new_ss_ip, string new_sd_ip, string packet_id) { string sdata = payload.GetString(System.Text.Encoding.UTF8); if(sdata.Contains(packet_id)) { sdata = sdata.Replace(old_ss_ip, new_ss_ip); sdata = sdata.Replace(old_sd_ip, new_sd_ip); payload = MemBlock.Reference(System.Text.Encoding.UTF8.GetBytes(sdata)); } return payload; }
public bool HandleReply(ReqrepManager man, ReqrepManager.ReqrepType rt, int mid, PType prot, MemBlock payload, ISender from, ReqrepManager.Statistics s, object state) { Console.WriteLine("{0} got our message", from); return false; }
public DirectionalAddress(MemBlock mb) { if (ClassOf(mb) != this.Class) { throw new System. ArgumentException ("This is not an AHAddress (Class 124) : ", this.ToString()); } _buffer = mb; _dir = (Direction) NumberSerializer.ReadInt(mb, 0); }
public void HandleData(MemBlock p, ISender edge, object state) { try { int num = NumberSerializer.ReadInt(p, 0); Console.WriteLine("Got packet number: {0}", num); edge.Send( p ); } catch(Exception x) { Console.WriteLine("Server got exception on send: {0}", x); } }
/// <summary> /// 释放 /// </summary> /// <param name="block"></param> public void Free(MemBlock block) { if (block.GetBytes() == null) return; int nIndex = GetIndex(block.GetMaxLength()); if (nIndex >= mMaxList) return; mAllMemList[nIndex].Enqueue(block); }
public static void Verify(MemBlock p, ISender from, object state) { lock(_class_lock) { // // Make sure that the packet equals my state. // if (!p.Equals(state)) { _wrongly_routed++; } _received++; } }
public void HandleData(MemBlock p, ISender edge, object state) { //object count_o = null; try { lock(_sync) { //clear this item out //count_o = _sent_blocks[p]; _sent_blocks.Remove(p); } } catch(Exception x) { Console.WriteLine("Error on handling response from {0}: {1}", edge, x); } }
public ArpPacket(MemBlock Packet) { _icpacket = _packet = Packet; HardwareType = NumberSerializer.ReadShort(Packet, 0); ProtocolType = NumberSerializer.ReadShort(Packet, 2); int hw_len = Packet[4]; int proto_len = Packet[5]; Operation = (Operations) NumberSerializer.ReadShort(Packet, 6); int pos = 8; SenderHWAddress = MemBlock.Reference(Packet, pos, hw_len); pos += hw_len; SenderProtoAddress = MemBlock.Reference(Packet, pos, proto_len); pos += proto_len; TargetHWAddress = MemBlock.Reference(Packet, pos, hw_len); pos += hw_len; TargetProtoAddress = MemBlock.Reference(Packet, pos, proto_len); }
public static ManagedDhcpServer GetManagedDhcpServer(MemBlock ip, MemBlock netmask) { DHCPConfig config = new DHCPConfig(); config.LeaseTime = 3200; config.Netmask = Utils.MemBlockToString(netmask, '.'); config.IPBase = Utils.MemBlockToString(ip, '.'); config.ReservedIPs = new DHCPConfig.ReservedIP[1]; config.ReservedIPs[0] = new DHCPConfig.ReservedIP(); byte[] local_ip = new byte[4]; ip.CopyTo(local_ip, 0); local_ip[3] = 2; config.ReservedIPs[0].IPBase = Utils.BytesToString(local_ip, '.'); config.ReservedIPs[0].Mask = "255.255.255.255"; return new ManagedDhcpServer(config); }
public IcmpPacket(MemBlock Packet) { if(Packet.Length < 4) { throw new Exception("Icmp: Not long enough!"); } _icpacket = Packet; _packet = Packet; Type = (Types) Packet[0]; Code = Packet[1]; if(Packet.Length >= 8) { Identifier = NumberSerializer.ReadShort(Packet, 4); SequenceNumber = NumberSerializer.ReadShort(Packet, 6); } else { Identifier = 0; SequenceNumber = 0; } }
/// <summary>Translates an IP Address to a Brunet Address. If it is in the /// cache it returns a result, otherwise it returns null and begins a Miss /// lookup.</summary> /// <param name="ip">The IP Address to translate.</param> /// <returns>Null if none exists or there is a miss or the Brunet Address if /// one exists in the cache</returns> public Address Resolve(MemBlock ip) { Address stored_addr; bool update; bool contains = _verified_cache.TryGetValue(ip, out stored_addr, out update); if(!contains) { contains = _incoming_cache.TryGetValue(ip, out stored_addr, out update); update = true; } if(contains) { _incoming_cache.Update(ip, stored_addr); } if(update) { Miss(ip); } return stored_addr; }
public void test() { MockDataHandler mdh = new MockDataHandler(); mdh.HandleDataCallback += Callback; ISender sender = new MockSender(null, null, mdh, 0); byte[][] b = new byte[10][]; MemBlock[] mb = new MemBlock[10]; Random rand = new Random(); for(int i = 0; i < 10; i++) { b[i] = new byte[128]; rand.NextBytes(b[i]); mb[i] = MemBlock.Reference(b[i]); sender.Send(mb[i]); } for(int i = 0; i < 10; i++) { Assert.AreEqual(i, mdh.Position(mb[i]), "Position " + i); Assert.IsTrue(mdh.Contains(mb[i]), "Contains " + i); } Assert.AreEqual(_count, 10, "Count"); }
/// <summary>Default constructor</summary> /// <param name="ip_address">An IP Address in the range.</param> /// <param name="netmask">The netmask for the range.</param> /// <param name="name_server">The external name server to be queried.</param> /// <param name="forward_queries">Set if queries are to be forwarded to external name server.</param> public Dns(MemBlock ip_address, MemBlock netmask, string name_server, bool forward_queries) { if(forward_queries) { if(name_server == null || name_server == string.Empty) { // GoogleDns name_server = "8.8.8.8"; } _name_server = new IPEndPoint(IPAddress.Parse(name_server), 53); } _forward_queries = forward_queries; _netmask = netmask; byte[] ba = new byte[ip_address.Length]; for(int i = 0; i < ip_address.Length; i++) { ba[i] = (byte) (ip_address[i] & netmask[i]); } _base_address = MemBlock.Reference(ba); }
/// <summary> /// Constructor for the class, it initializes various objects /// </summary> /// <param name="node">Takes in a structured node</param> public ManagedAddressResolverAndDns(StructuredNode node, DhcpServer dhcp, MemBlock local_ip, string name_server, bool forward_queries) : base(MemBlock.Reference(dhcp.BaseIP), MemBlock.Reference(dhcp.Netmask), name_server, forward_queries) { _node = node; _dns_a = new Hashtable(); _dns_ptr = new Hashtable(); _ip_addr = new Hashtable(); _addr_ip = new Hashtable(); _blocked_addrs = new Hashtable(); mcast_addr = new ArrayList(); _dhcp = dhcp; _local_ip = local_ip; _sync = new object(); _udp_translators = new IProtocolTranslator<UdpPacket>[] { new MDnsTranslator(local_ip), new SipTranslator(local_ip), new SsdpTranslator(local_ip) }; }