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 LinuxTap(string dev) { int TUNSETIFF = GetIOCtlWrite('T', 202, 4); /* size of int 4, from if_tun.h */ ifreq1 ifr1 = new ifreq1(); int fd; if ((fd = Syscall.open("/dev/net/tun", OpenFlags.O_RDWR)) < 0) { throw new Exception("Failed to open /dev/net/tun"); } ifr1.ifru_flags = IFF_TAP | IFF_NO_PI; ifr1.ifrn_name = dev; if (ioctl(fd, TUNSETIFF, ref ifr1) < 0) { Syscall.close(fd); throw new Exception("TUNSETIFF failed"); } _fd = fd; int ctrl_fd = socket(AF_INET, SOCK_DGRAM, 0); if(ctrl_fd == -1) { Syscall.close(fd); throw new Exception("Unable to open CTL_FD"); } ifreq2 ifr2 = new ifreq2(); ifr2.ifrn_name = dev; // ioctl changed the name? if(ioctl(ctrl_fd, SIOCGIFHWADDR, ref ifr2) <0) { Console.WriteLine("Failed to get hw addr."); Syscall.close(ctrl_fd); throw new Exception("Failed to get hw addr."); } _addr = MemBlock.Reference(ASCIIEncoding.UTF8.GetBytes(ifr2.ifr_hwaddr.sa_data)); }
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))); } } }
/// <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) { IPAddresses ipaddrs = IPAddresses.GetIPAddresses(); ArrayList used_networks = new ArrayList(); MemBlock netip = startip; foreach (Hashtable ht in ipaddrs.AllInterfaces) { if (ht["inet addr"] != null && ht["Mask"] != null && (string)ht["interface"] != networkdevice) { MemBlock addr = MemBlock.Reference(Utils.StringToBytes((string) ht["inet addr"], '.')); MemBlock mask = MemBlock.Reference(Utils.StringToBytes((string) ht["Mask"], '.')); byte[] tmp = new byte[addr.Length]; for(int i = 0; i < addr.Length; i++) { tmp[i] = (byte)(addr[i] & mask[i]); } used_networks.Add(MemBlock.Reference(tmp)); } } 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; }
static EthernetPacket() { Random _rand = new Random(); byte[] unicast = new byte[6]; _rand.NextBytes(unicast); unicast[0] = 0xFE; UnicastAddress = MemBlock.Reference(unicast); }
/// <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 SecurityControlMessage() { byte[] empty_cookie = new byte[CookieLength]; for(int i = 0; i < CookieLength; i++) { empty_cookie[i] = 0; } EmptyCookie = MemBlock.Reference(empty_cookie); }
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); } }
public AHAddress(MemBlock mb) : base(mb) { if (ClassOf(_buffer) != this.Class) { throw new System. ArgumentException("Class of address is not my class: ", this.ToString()); } }
//Too bad we can't use a template here, .Net generics *may* do the job public static int ReadInt(MemBlock mb, int offset) { int val = 0; for(int i = 0; i < 4; i++) { val = (val << 8) | mb[i + offset]; } return val; }
/** * Create an address from a MemBlock */ protected Address(MemBlock mb) { _buffer = mb; if (ClassOf(_buffer) != this.Class) { throw new System. ArgumentException("Class of address is not my class: ", this.ToString()); } }
public AHAddress(MemBlock mb) : base(mb) { if (ClassOf(_buffer) != this.Class) { throw new System. ArgumentException("Class of address is not my class: ", this.ToString()); } _prefix = (uint)NumberSerializer.ReadInt(_buffer, 0); }
public DataPacket(ICopyable packet) { _update_icpacket = false; _update_packet = false; _icpacket = packet; _packet = packet as MemBlock; if(_packet == null) { _update_packet = true; } }
/** * This handles the packet forwarding protocol */ public void HandleData(MemBlock b, ISender ret_path, object state) { /* * Check it */ AHSender ahs = ret_path as AHSender; if( ahs != null ) { //This was an AHSender: /* * This goes A -> B -> C */ if( b[0] == 0 ) { int offset = 1; //This is the first leg, going from A->B Address add_c = AddressParser.Parse(b.Slice(offset, Address.MemSize)); offset += Address.MemSize; //Since ahs a sender to return, we would be the source: Address add_a = ahs.Destination; short ttl = NumberSerializer.ReadShort(b, offset);//2 bytes offset += 2; ushort options = (ushort) NumberSerializer.ReadShort(b, offset);//2 bytes offset += 2; MemBlock payload = b.Slice(offset); MemBlock f_header = MemBlock.Reference( new byte[]{1} ); /* * switch the packet from [A B f0 C] to [B C f 1 A] */ ICopyable new_payload = new CopyList(PType.Protocol.Forwarding, f_header, add_a, payload); /* * ttl and options are present in the forwarding header. */ AHSender next = new AHSender(_n, ahs.ReceivedFrom, add_c, ttl, options); next.Send(new_payload); } else if ( b[0] == 1 ) { /* * This is the second leg: B->C * Make a Forwarding Sender, and unwrap the inside packet */ Address add_a = AddressParser.Parse(b.Slice(1, Address.MemSize)); Address add_b = ahs.Destination; MemBlock rest_of_payload = b.Slice(1 + Address.MemSize); //Here's the return path: ISender new_ret_path = new ForwardingSender(_n, add_b, add_a); _n.HandleData(rest_of_payload, new_ret_path, this); } } else { //This is not (currently) supported. Console.Error.WriteLine("Got a forwarding request from: {0}", ret_path); } }
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) { 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> /// 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; }
/// <summary>Default constructor</summary> /// <param name="ip_address">An IP Address in the range.</param> /// <param name="netmask">The netmask for the range.</param> public DNS(MemBlock ip_address, MemBlock netmask) { _sync = new object(); byte[] ba = new byte[ip_address.Length]; for(int i = 0; i < ip_address.Length; i++) { ba[i] = (byte) (ip_address[i] & netmask[i]); } lock(_sync) { _base_address = MemBlock.Reference(ba); _netmask = netmask; } _active = true; }
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); } }
/// <summary> /// Does bulk Brunet DHT gets by calling the bulk DHT operation API of its /// XML-RPC interface. /// </summary> /// <returns>Null if not all the pieces are successfully retrieved and parsed.</returns> /// <exception cref="Exception">Parsing errors.</exception> private MemBlock GetFragsInBulk(byte[] base_key, int piece_num, out int largest_age, out int smallest_ttl) { largest_age = 0; smallest_ttl = Int32.MaxValue; MemBlock fragments = new MemBlock(); byte[][] keys = new byte[piece_num][]; for (int i = 0; i < piece_num; i++) { byte[] piece_key = BuildFragmentKey(base_key, i); keys[i] = piece_key; } DhtGetResult[] dgrs = _dht.BulkGet(keys); for (int i = 0; i < dgrs.Length; i++) { DhtGetResult dgr = dgrs[i]; if (dgr == null) { Logger.WriteLineIf(LogLevel.Error, _log_props, string.Format("Piece #{0} is null. Retrying...", i)); dgr = GetWithRetries(keys[i], 2); if (dgr == null) { Logger.WriteLineIf(LogLevel.Error, _log_props, string.Format("Piece #{0} is null after retries. Skipping " + "further parsing and returning...", i)); return null; } } FingerprintedData fpd; try { fpd = (FingerprintedData)DictionaryData.CreateDictionaryData(dgr.value); } catch (Exception ex) { Logger.WriteLineIf(LogLevel.Error, _log_props, ex); throw ex; } Logger.WriteLineIf(LogLevel.Verbose, _log_props, string.Format("Piece #{0} retrieved and successfully parsed", i)); RegularData rd = fpd.InnerData as RegularData; fragments = MemBlock.Concat(fragments, MemBlock.Reference(rd.PayLoad)); if (smallest_ttl > dgr.ttl) smallest_ttl = dgr.ttl; if (largest_age < dgr.age) largest_age = dgr.age; //Now it's safe to say, this attempt succeeded. } return fragments; }
public void HandleData(MemBlock b, ISender from, object state) { MemBlock payload = null; PType t = null; try { t = PType.Parse(b, out payload); if(t.Equals(PType.Protocol.ReqRep)) { _rrm.HandleData(payload, from, state); } else if(t.Equals(PType.Protocol.Rpc)) { Rpc.HandleData(payload, from, state); } } catch(Exception x) { Console.Error.WriteLine("Packet Handling Exception: {3}\n\tType: {0}\n\t\n\tFrom: {1}\n\tData: {2}", t, from, payload.GetString(System.Text.Encoding.ASCII), 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 AHPacket(MemBlock buf) { //Now this is exactly the same code as below: if (buf[0] != (byte)Packet.ProtType.AH ) { throw new System. ArgumentException("Packet is not an AHPacket: " + buf[0].ToString()); } _buffer = buf; int offset = 0; offset += 1; _hops = NumberSerializer.ReadShort(_buffer, offset); offset += 2; _ttl = NumberSerializer.ReadShort(_buffer, offset); offset += 2; //Skip the addresses offset += 40; _options = (ushort)NumberSerializer.ReadShort(_buffer, offset); }
public static RpcDHCPServer GetRpcDHCPServer(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 RpcDHCPServer(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; } }
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"); }
/** * @param s Stream to read the AHPacket from * @param length the lenght of the packet */ public AHPacket(Stream s, int length) { if( s.Length < length ) { throw new ArgumentException("Cannot read AHPacket from Stream"); } byte[] buffer = new byte[length]; s.Read(buffer, 0, length); int offset = 0; //Now this is exactly the same code as below: if (buffer[offset] != (byte)Packet.ProtType.AH ) { throw new System. ArgumentException("Packet is not an AHPacket: " + buffer[offset].ToString()); } offset += 1; _hops = NumberSerializer.ReadShort(buffer, offset); offset += 2; _ttl = NumberSerializer.ReadShort(buffer, offset); offset += 2; //Skip the addresses offset += 40; _options = (ushort)NumberSerializer.ReadShort(buffer, offset); _buffer = MemBlock.Reference(buffer, 0, length); }
/// <summary>Default constructor</summary> /// <param name="ip_address">An IP Address in the range.</param> /// <param name="netmask">The netmask for the range.</param> public DNS(MemBlock ip_address, MemBlock netmask, string dns_server, bool RA) { if (dns_server == null) { dns_server = DefaultDNSServer; RA = true; } DNSServer = new IPEndPoint(IPAddress.Parse(dns_server), 53); _recursive_available = RA; _sync = new object(); byte[] ba = new byte[ip_address.Length]; for (int i = 0; i < ip_address.Length; i++) { ba[i] = (byte)(ip_address[i] & netmask[i]); } lock (_sync) { _base_address = MemBlock.Reference(ba); _netmask = netmask; } _active = true; }
/// <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(); }
/// <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 = Dns.GetHostEntry(Dns.GetHostName()); 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; }