Ejemplo n.º 1
0
        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);
        }
Ejemplo n.º 2
0
        /// <summary>This is used to process a dhcp packet on the node side, that
        /// includes placing data such as the local Brunet Address, Ipop Namespace,
        /// and other optional parameters in our request to the dhcp server.  When
        /// receiving the results, if it is successful, the results are written to
        /// the TAP device.</summary>
        /// <param name="ipp"> The IPPacket that contains the Dhcp Request</param>
        /// <param name="dhcp_params"> an object containing any extra parameters for
        /// the dhcp server</param>
        /// <returns> true on if dhcp is supported.</returns>
        protected virtual bool HandleDhcp(IPPacket ipp)
        {
            UdpPacket  udpp        = new UdpPacket(ipp.Payload);
            DhcpPacket dhcp_packet = new DhcpPacket(udpp.Payload);
            MemBlock   ether_addr  = dhcp_packet.chaddr;

            if (_dhcp_config == null)
            {
                return(true);
            }

            DhcpServer dhcp_server = CheckOutDhcpServer(ether_addr);

            if (dhcp_server == null)
            {
                return(true);
            }

            MemBlock last_ip = null;

            _ether_to_ip.TryGetValue(ether_addr, out last_ip);
            byte[] last_ipb = (last_ip == null) ? null : (byte[])last_ip;

            WaitCallback wcb = delegate(object o) {
                ProtocolLog.WriteIf(IpopLog.DhcpLog, String.Format(
                                        "Attempting Dhcp for: {0}", Utils.MemBlockToString(ether_addr, '.')));

                DhcpPacket rpacket = null;
                try {
                    rpacket = dhcp_server.ProcessPacket(dhcp_packet,
                                                        AppNode.Node.Address.ToString(), last_ipb);
                } catch (Exception e) {
                    ProtocolLog.WriteIf(IpopLog.DhcpLog, e.Message);
                    CheckInDhcpServer(dhcp_server);
                    return;
                }

                /* Check our allocation to see if we're getting a new address */
                MemBlock new_addr = rpacket.yiaddr;
                UpdateMapping(ether_addr, new_addr);

                MemBlock destination_ip = ipp.SourceIP;
                if (destination_ip.Equals(IPPacket.ZeroAddress))
                {
                    destination_ip = IPPacket.BroadcastAddress;
                }

                UdpPacket res_udpp = new UdpPacket(_dhcp_server_port, _dhcp_client_port, rpacket.Packet);
                IPPacket  res_ipp  = new IPPacket(IPPacket.Protocols.Udp, rpacket.siaddr,
                                                  destination_ip, res_udpp.ICPacket);
                EthernetPacket res_ep = new EthernetPacket(ether_addr, EthernetPacket.UnicastAddress,
                                                           EthernetPacket.Types.IP, res_ipp.ICPacket);
                Ethernet.Send(res_ep.ICPacket);
                CheckInDhcpServer(dhcp_server);
            };

            ThreadPool.QueueUserWorkItem(wcb);
            return(true);
        }
Ejemplo n.º 3
0
    /**
    <summary>The _listen_threads method, reads from sockets and let's the node
    handle the incoming data.</summary>
    */
    protected void Listen() {
      if (Thread.CurrentThread.Name == null) {
        Thread.CurrentThread.Name = "iphandler_thread";
      }
      ArrayList sockets = new ArrayList();
      sockets.Add(_uc);
      if(_mc != null) {
        sockets.Add(_mc);
      }

      byte[] buffer =  new byte[Int16.MaxValue];
      DateTime last_debug = DateTime.UtcNow;
      TimeSpan debug_period = TimeSpan.FromSeconds(5);
      while(1 == _running) {
        if (ProtocolLog.Monitor.Enabled) {
          DateTime now = DateTime.UtcNow;
          if (now - last_debug > debug_period) {
            last_debug = now;
            ProtocolLog.Write(ProtocolLog.Monitor, String.Format("I am alive: {0}", now));
          }
        }
        try {
          ArrayList readers = (ArrayList) sockets.Clone();
          Socket.Select(readers, null, null, 10000000); //10 seconds
          foreach(Socket socket in readers) {
            EndPoint ep = new IPEndPoint(IPAddress.Any, 0);
            int rec_bytes = socket.ReceiveFrom(buffer, ref ep);
            Subscriber s = _sub;
            //s can't change once we've read it.
            if( s != null && rec_bytes > 0) {
              MemBlock packet = MemBlock.Copy(buffer, 0, rec_bytes);
              MemBlock cookie = packet.Slice(0, 4);
              if(cookie.Equals(MagicCookie)) {
                packet = packet.Slice(4);
                ISender sender = CreateUnicastSender(ep);
                s.Handle(packet, sender);
              }
            }
          }
        }
        catch(ObjectDisposedException odx) {
          //If we are no longer running, this is to be expected.
          if(1 == _running) {
          //If we are running print it out
            ProtocolLog.WriteIf(ProtocolLog.Exceptions, odx.ToString());
          }
          break;
        }
        catch(Exception x) {
          if(0 == _running) {
            ProtocolLog.WriteIf(ProtocolLog.Exceptions, x.ToString());
          }
        }
      }
    }
Ejemplo n.º 4
0
        /*
         * Handle the data from our underlying edge
         */
        public void HandleData(MemBlock b, ISender ret, object state)
        {
            MemBlock tmp = b.Slice(0, PType.Protocol.Pathing.Length);

            if (tmp.Equals(PType.Protocol.Pathing.ToMemBlock()))
            {
                _pem.HandleData(b, ret, null);
                return;
            }
            ReceivedPacketEvent(b);
        }
Ejemplo n.º 5
0
    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++;
      }
    }
Ejemplo n.º 6
0
        public ArpPacket Respond(MemBlock response)
        {
            MemBlock target_proto = SenderProtoAddress;

            if (SenderProtoAddress.Equals(IPPacket.ZeroAddress))
            {
                target_proto = IPPacket.BroadcastAddress;
            }

            return(new ArpPacket(HardwareType, ProtocolType, Operations.Reply,
                                 response, TargetProtoAddress, SenderHWAddress, target_proto));
        }
Ejemplo n.º 7
0
 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++;
     }
 }
Ejemplo n.º 8
0
 ///<summary>Verifies the hash with the DHEWithCertificateHash.</summary>
 public bool VerifyRequest(MemBlock hash)
 {
     if (DHEWithCertificateHash.Value == null)
     {
         throw new Exception("Hash not set!");
     }
     else if (!DHEWithCertificateHash.Value.Equals(hash))
     {
         throw new Exception("Hash does not match!");
     }
     _hash_verified = true;
     return(hash.Equals(DHEWithCertificateHash.Value));
 }
Ejemplo n.º 9
0
        protected int VerifyCookie(Ssl ssl, byte[] cookie)
        {
            MemBlock from_cookie = MemBlock.Reference(cookie);

            byte[]   lcookie      = CalculateCookie(ssl.Handle.GetHashCode());
            MemBlock local_cookie = MemBlock.Reference(lcookie);

            if (local_cookie.Equals(from_cookie))
            {
                return(1);
            }
            else
            {
                return(-1);
            }
        }
Ejemplo n.º 10
0
        /**
         * <summary>Parse a MemBlock packet into a Dhcp Packet</summary>
         * <param name="Packet">The dhcp packet to parse</param>
         */
        public DhcpPacket(MemBlock Packet)
        {
            if (Packet.Length < 240)
            {
                throw new Exception("Invalid Dhcp Packet:  Length < 240.");
            }

            _packet = Packet;
            op      = Packet[0];
            int hlen = Packet[2];

            xid    = Packet.Slice(4, 4);
            ciaddr = Packet.Slice(12, 4);
            yiaddr = Packet.Slice(16, 4);
            siaddr = Packet.Slice(20, 4);
            chaddr = Packet.Slice(28, hlen);
            MemBlock key = Packet.Slice(236, 4);

            if (!key.Equals(magic_key))
            {
                throw new Exception("Invalid Dhcp Packet: Invalid magic key.");
            }
            int idx = 240;

            /* Parse the options */
            Options = new Dictionary <OptionTypes, MemBlock>();
            /*  255 is end of options */
            while (Packet[idx] != 255)
            {
                /* 0 is padding */
                if (Packet[idx] != 0)
                {
                    OptionTypes type   = (OptionTypes)Packet[idx++];
                    byte        length = Packet[idx++];
                    Options[type] = Packet.Slice(idx, length);
                    idx          += length;
                }
                else
                {
                    idx++;
                }
            }
        }
Ejemplo n.º 11
0
        override public void HandleData(MemBlock data, ISender return_path, object state)
        {
            if (return_path is SecurityAssociation)
            {
                Handle(data, return_path);
                return;
            }

            MemBlock tmp = data.Slice(0, _ptype_mb.Length);

            if (tmp.Equals(_ptype_mb))
            {
                data = data.Slice(_ptype_mb.Length);
            }

            MemBlock        payload;
            int             localid, remoteid;
            IIdentifierPair cp;
            DtlsAssociation sa;

            try {
                _it.Parse(data, out payload, out localid, out remoteid);
                _it.TryGet(localid, remoteid, out cp);
            } catch (Exception e) {
                ProtocolLog.WriteIf(ProtocolLog.SecurityExceptions, e.Message);
                return;
            }

            if (cp != null)
            {
                sa = cp as DtlsAssociation;
            }
            else
            {
                NoSuchSA(return_path, remoteid, false, out sa);
                _it.Add(sa);
                sa.RemoteID = remoteid;
                sa.Subscribe(this, null);
            }
            sa.HandleData(payload, return_path, null);
        }
Ejemplo n.º 12
0
        /** Begin a Compare-and-Swap operation
         * @param key the key to change
         * @param new_value the value to replace if the old value is given
         * @param old_value the value we are checking for (may be null)
         * @param cb the delegate to call on completion
         * Note the swap succeeds if and only if the return value
         * of EndCompareSwap == old_value
         */
        override public IAsyncResult BeginCompareSwap(MemBlock key, MemBlock new_value,
                                                      MemBlock old_value, AsyncCallback cb,
                                                      object state)
        {
            MemBlock old_v = null;

            lock ( _sync ) {
                old_v = _ht[key] as MemBlock;
                if ((old_v == null) && (old_value == null))
                {
                    //Looks good:
                    _ht[key] = new_value;
                }
                else if (old_v.Equals(old_value))
                {
                    //Use Equals method to check for equality
                    _ht[key] = new_value;
                }
            }
            IAsyncResult r = new LhtAsResult(state, old_v);

            cb(r);
            return(r);
        }
Ejemplo n.º 13
0
 ///<summary>Verifies the hash with the DHEWithCertificateHash.</summary>
 public bool VerifyRequest(MemBlock hash) {
   if(DHEWithCertificateHash.Value == null) {
     throw new Exception("Hash not set!");
   } else if(!DHEWithCertificateHash.Value.Equals(hash)) {
     throw new Exception("Hash does not match!");
   }
   _hash_verified = true;
   return hash.Equals(DHEWithCertificateHash.Value);
 }
Ejemplo n.º 14
0
        /**
         * <summary>This provides a mechanism for a node to get a lease by using the
         * Dht.  This uses Dht.Create which provides an atomic operation on the Dht,
         * where this node is the first to store a value at a specific key.  The idea
         * being that, this node being the first to store the IP, all nodes doing a
         * lookup for that IP Address would be directed to this node.</summary>
         * <remarks>Working with the Dht is a little tricky as transient errors could
         * be misrepresented as a failed Create.  It is that reason why there is a
         * Renew parameter. If that is set, the algorithm for obtaining an address
         * is slightly changed with more weight on reobtaining the RequestedAddr.
         * </remarks>
         * <param name="RequestedAddr">Optional parameter if the node would like to
         * request a specific address.</param>
         * <param name="Renew">Is the RequestedAddr a renewal?</param>
         * <param name="node_address">The Brunet.Address where the DhtIpopNode resides
         * </param>
         * <param name="para">Optional, position 0 should hold the hostname.</param>
         */
        public override byte[] RequestLease(byte[] RequestedAddr, bool Renew,
                                            string node_address, params object[] para)
        {
            int max_renew_attempts = 1;
            int renew_attempts     = max_renew_attempts;
            int attempts           = 2;

            if (Renew)
            {
                if (!ValidIP(RequestedAddr))
                {
                    throw new Exception("Invalid requested address: " +
                                        Utils.BytesToString(RequestedAddr, '.'));
                }
                MemBlock request_addr = MemBlock.Reference(RequestedAddr);
                renew_attempts = 2;
                attempts       = 1;
                if (request_addr.Equals(_current_ip) && DateTime.UtcNow < _current_quarter_lifetime)
                {
                    return(_current_ip);
                }
            }
            else if (RequestedAddr == null || !ValidIP(RequestedAddr))
            {
                RequestedAddr = MemBlock.Reference(RandomIPAddress());
            }

            byte[] hostname = null;
            if (para.Length > 0 && para[0] is string)
            {
                string shostname = para[0] as string;
                if (!shostname.Equals(string.Empty))
                {
                    hostname = Encoding.UTF8.GetBytes(Config.Namespace + "." + shostname + "." + Dns.DomainName);
                }
            }

            byte[] multicast_key = null;
            if (_multicast)
            {
                multicast_key = Encoding.UTF8.GetBytes(Config.Namespace + ".multicast.ipop");
            }

            byte[] node_addr = Encoding.UTF8.GetBytes(node_address);
            bool   res       = false;

            while (attempts-- > 0)
            {
                string str_addr = Utils.BytesToString(RequestedAddr, '.');
                ProtocolLog.WriteIf(IpopLog.DhcpLog, "Attempting to allocate IP Address:" + str_addr);

                byte[] dhcp_key = Encoding.UTF8.GetBytes("dhcp:" + Config.Namespace + ":" + str_addr);
                byte[] ip_addr  = Encoding.UTF8.GetBytes(str_addr);

                while (renew_attempts-- > 0)
                {
                    try {
                        res = _dht.Create(dhcp_key, node_addr, Config.LeaseTime);

                        if (hostname != null)
                        {
                            _dht.Put(hostname, ip_addr, Config.LeaseTime);
                        }

                        if (_multicast)
                        {
                            _dht.Put(multicast_key, node_addr, Config.LeaseTime);
                        }

//            _dht.Put(node_addr, dhcp_key, Config.LeaseTime);
                    }
                    catch (Exception e) {
                        ProtocolLog.WriteIf(IpopLog.DhcpLog, "Unable to allocate: " + e.Message);
                        res = false;
                    }
                }
                if (res)
                {
                    _current_ip = MemBlock.Reference(RequestedAddr);
                    _current_quarter_lifetime = DateTime.UtcNow.AddSeconds(Config.LeaseTime / 4.0);
                    break;
                }
                else
                {
                    // Failure!  Guess a new IP address
                    RequestedAddr  = RandomIPAddress();
                    renew_attempts = max_renew_attempts;
                }
            }

            if (!res)
            {
                throw new Exception("Unable to get an IP Address!");
            }

            return(RequestedAddr);
        }
Ejemplo n.º 15
0
        ///<summary>Verifies the packet given a Hash algorithm.</summary>
        public bool Verify(HashAlgorithm hash)
        {
            MemBlock hash_data = MemBlock.Reference(hash.ComputeHash(_unsigned_data));

            return(_signature.Equals(hash_data));
        }
Ejemplo n.º 16
0
 /// <summary>Is this our IP?  Are we routing for it?</summary>
 /// <param name="ip">The IP in question.</param>
 protected virtual bool IsLocalIP(MemBlock ip)
 {
     return _ip_to_ether.ContainsKey(ip) || ip.Equals(IPPacket.ZeroAddress);
 }
Ejemplo n.º 17
0
 /// <summary>Is this our IP?  Are we routing for it?</summary>
 /// <param name="ip">The IP in question.</param>
 protected virtual bool IsLocalIP(MemBlock ip)
 {
     return(_ip_to_ether.ContainsKey(ip) || ip.Equals(IPPacket.ZeroAddress));
 }