Beispiel #1
0
        public static TransportAddress CreateInstance(TransportAddress.TAType t,
                                                      IPAddress host, int port)
        {
            Cache ta_cache = Interlocked.Exchange <Cache>(ref _ta_cache, null);

            if (ta_cache != null)
            {
                TransportAddress ta = null;
                try {
                    CacheKey key = new CacheKey(host, port, t);
                    ta = (TransportAddress)ta_cache[key];
                    if (ta == null)
                    {
                        ta            = new IPTransportAddress(t, host, port);
                        ta_cache[key] = ta;
                    }
                }
                finally {
                    Interlocked.Exchange <Cache>(ref _ta_cache, ta_cache);
                }
                return(ta);
            }
            else
            {
                return(new IPTransportAddress(t, host, port));
            }
        }
Beispiel #2
0
        public static TransportAddress CreateInstance(TransportAddress.TAType t,
                                                      IPAddress host, int port)
        {
            var ta = new IPTransportAddress(t, host, port);

            return(CacheInstance(ta));
        }
Beispiel #3
0
 public IPTransportAddress(TransportAddress.TAType t, IPAddress addr, int port) :
     this(String.Format("brunet.{0}://{1}:{2}", TATypeToString(t), addr, port))
 {
     _type = t;
     _ips  = new ArrayList(1);
     _ips.Add(addr);
 }
Beispiel #4
0
        /// <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);
        }
Beispiel #5
0
 override protected void Finished()
 {
   _node0.ConnectionTable.ConnectionEvent -= HandleConnection;
   _node1.ConnectionTable.ConnectionEvent -= HandleConnection;
   Connection con = _node0.ConnectionTable.GetConnection(ConnectionType.Structured, _node1.Address);
   if(con != null) {
     _type = con.Edge.TAType;
   }
   base.Finished();
 }
Beispiel #6
0
        static public void Clear(TransportAddress.TAType type)
        {
            if (!_el_map.ContainsKey(type))
            {
                return;
            }
            var el_map = _el_map[type];

            el_map.Clear();
            _el_map.Remove(type);
        }
Beispiel #7
0
 public SimulationEdge(IEdgeSendHandler s, int local_id, int remote_id,
                       bool is_in, int delay, TransportAddress.TAType type) : base(s, is_in)
 {
     Delay      = delay;
     LocalID    = local_id;
     RemoteID   = remote_id;
     _ta_type   = type;
     _local_ta  = GetTransportAddress(local_id);
     _remote_ta = GetTransportAddress(remote_id);
     SimEL      = s as SimulationEdgeListener;
 }
Beispiel #8
0
        override protected void Finished()
        {
            _node0.ConnectionTable.ConnectionEvent -= HandleConnection;
            _node1.ConnectionTable.ConnectionEvent -= HandleConnection;
            Connection con = _node0.ConnectionTable.GetConnection(ConnectionType.Structured, _node1.Address);

            if (con != null)
            {
                _type = con.State.Edge.TAType;
            }
            base.Finished();
        }
Beispiel #9
0
 /**
  * This creates Edges of a given type
  */
 public void CreateEdgeTo(TransportAddress destination,
                          EdgeListener.EdgeCreationCallback ecb)
 {
     TransportAddress.TAType t = destination.TransportAddressType;
     if (_el_map.Contains(t))
     {
         EdgeListener el = (EdgeListener)_el_map[t];
         el.CreateEdgeTo(destination, ecb);
     }
     else
     {
         ecb(false, null, new EdgeException("No EdgeListener for TA type: " +
                                            t.ToString()));
     }
 }
Beispiel #10
0
        /// <summary>Always returns the fastest non-tunnel, overlapping address.</summary>
        public override Address EvaluatePotentialOverlap(IDictionary msg)
        {
            Address best_addr          = null;
            double  best_latency       = double.MaxValue;
            Address their_best_addr    = null;
            double  their_best_latency = double.MaxValue;

            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);

                IDictionary             info   = de.Value as IDictionary;
                TransportAddress.TAType tatype =
                    TransportAddressFactory.StringToType(info["ta"] as string);

                if (tatype.Equals(TransportAddress.TAType.Relay))
                {
                    continue;
                }

                double latency = _ncservice.GetMeasuredLatency(addr);
                if (latency > 0 && latency < best_latency)
                {
                    best_addr    = addr;
                    best_latency = latency;
                }

                if (!info.Contains("lat"))
                {
                    continue;
                }

                latency = (double)info["lat"];
                if (latency > 0 && latency < their_best_latency)
                {
                    their_best_addr    = addr;
                    their_best_latency = latency;
                }
            }

            best_addr = their_best_latency < best_latency ? their_best_addr : best_addr;
            return(best_addr == null?base.EvaluatePotentialOverlap(msg) : best_addr);
        }
Beispiel #11
0
 /**
  * This gets the name of the local machine, then does a DNS lookup on that
  * name, and finally does the same as TransportAddress.Create for that
  * list of IPAddress objects.
  *
  * If the DNS hostname is not correctly configured, it will return the
  * loopback address.
  */
 public static IEnumerable CreateForLocalHost(TransportAddress.TAType tat, int port)
 {
     try {
         string      StrLocalHost = Dns.GetHostName();
         IPHostEntry IPEntry      = Dns.GetHostEntry(StrLocalHost);
         return(Create(tat, port, IPEntry.AddressList));
     }
     catch (Exception) {
         //Oh, well, that didn't work.
         ArrayList tas = new ArrayList(1);
         //Just put the loopback address, it might help us talk to some other
         //local node.
         tas.Add(CreateInstance(tat, new IPEndPoint(IPAddress.Loopback, port)));
         return(tas);
     }
 }
Beispiel #12
0
        protected static TransportAddress NoCacheCreateInstance(string s)
        {
            string scheme = s.Substring(0, s.IndexOf(":"));
            string t      = scheme.Substring(scheme.IndexOf('.') + 1);
            //Console.Error.WriteLine(t);

            TransportAddress result = null;

            TransportAddress.TAType ta_type = StringToType(t);

            switch (ta_type)
            {
            case TransportAddress.TAType.Tcp:
                result = new IPTransportAddress(s);
                break;

            case TransportAddress.TAType.Udp:
                result = new IPTransportAddress(s);
                break;

            case TransportAddress.TAType.Function:
                result = new IPTransportAddress(s);
                break;

            case TransportAddress.TAType.S:
                result = new SimulationTransportAddress(s);
                break;

            case TransportAddress.TAType.Tls:
                result = new IPTransportAddress(s);
                break;

            case TransportAddress.TAType.TlsTest:
                result = new IPTransportAddress(s);
                break;

            case TransportAddress.TAType.Tunnel:
                result = new TunnelTransportAddress(s);
                break;
            }

            return(result);
        }
Beispiel #13
0
        public SimulationEdgeListener(int id, double loss_prob, TAAuthorizer ta_auth,
                                      bool use_delay, TransportAddress.TAType type, INat nat)
        {
            _edges      = new Dictionary <Edge, Edge>();
            _use_delay  = use_delay;
            LocalID     = id;
            _ploss_prob = loss_prob;
            if (ta_auth == null)
            {
                _ta_auth = new ConstantAuthorizer(TAAuthorizer.Decision.Allow);
            }
            else
            {
                _ta_auth = ta_auth;
            }
            _ta_type = type;

            Nat         = nat;
            _is_started = false;
        }
Beispiel #14
0
        /// <summary>Returns the oldest 4 addresses in the overlap.</summary>
        public virtual List <Connection> EvaluateOverlap(ConnectionList cons, IDictionary msg)
        {
            List <Connection> overlap = new List <Connection>();

            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);

                int index = cons.IndexOf(addr);
                if (index < 0)
                {
                    continue;
                }

                Connection con = cons[index];

                // Since there are no guarantees about routing over two tunnels, we do
                // not consider cases where we are connected to the overlapping tunnels
                // peers via tunnels
                if (con.Edge.TAType.Equals(TransportAddress.TAType.Tunnel))
                {
                    Hashtable values = de.Value as Hashtable;
                    TransportAddress.TAType tatype =
                        TransportAddressFactory.StringToType(values["ta"] as string);
                    if (tatype.Equals(TransportAddress.TAType.Tunnel))
                    {
                        continue;
                    }
                }
                overlap.Add(con);
            }

            return(GetOldest(overlap));
        }
Beispiel #15
0
 public FakeEdge(TransportAddress local, TransportAddress remote, TransportAddress.TAType tatype)
 {
     _tatype    = tatype;
     local_add  = local;
     remote_add = remote;
 }
Beispiel #16
0
        /*
         * Given an IEnumerable of NatDataPoints, return a list of
         * ports from most likely to least likely to be the
         * next port used by the NAT
         *
         * @return an empty list if this is not our type
         */
        protected ArrayList PredictPorts(IEnumerable ndps)
        {
            ArrayList all_diffs = new ArrayList();
            //Get an increasing subset of the ports:
            int  prev             = Int32.MinValue;
            int  most_recent_port = -1;
            uint sum            = 0;
            uint sum2           = 0;
            bool got_extra_data = false;

            TransportAddress.TAType t = TransportAddress.TAType.Unknown;
            string host = String.Empty;

            foreach (NatDataPoint ndp in ndps)
            {
                if (false == (ndp is EdgeClosePoint))
                {
                    //Ignore closing events for prediction, they'll screw up the port prediction
                    TransportAddress ta = ndp.PeerViewOfLocalTA;
                    if (ta != null)
                    {
                        int port = ((IPTransportAddress)ta).Port;
//          Console.Error.WriteLine("port: {0}", port);
                        if (!got_extra_data)
                        {
                            t                = ta.TransportAddressType;
                            host             = ((IPTransportAddress)ta).Host;
                            most_recent_port = port;
                            got_extra_data   = true;
                        }
                        if (prev > port)
                        {
                            uint diff = (uint)(prev - port); //Clearly diff is always non-neg
                            all_diffs.Add(diff);
                            sum  += diff;
                            sum2 += diff * diff;
                        }
                        prev = port;
                    }
                }
            }

            /**
             * Now look at the mean and variance of the diffs
             */
            ArrayList prediction = new ArrayList();

            if (all_diffs.Count > 1)
            {
                double n    = (double)all_diffs.Count;
                double sd   = (double)sum;
                double mean = sd / n;
                double s2   = ((double)sum2) - sd * sd / n;
                s2 = s2 / (double)(all_diffs.Count - 1);
                double stddev = Math.Sqrt(s2);
                //Console.Error.WriteLine("stddev: {0}", stddev);
                if (stddev < MAX_STD_DEV)
                {
                    try {
                        double max_delta = mean + SAFETY * stddev;
                        if (max_delta < mean + 0.001)
                        {
                            //This means the stddev is very small, just go up one above the
                            //mean:
                            max_delta = mean + 1.001;
                        }
                        int delta = (int)(mean - SAFETY * stddev);
                        while (delta < max_delta)
                        {
                            if (delta > 0)
                            {
                                int pred_port = most_recent_port + delta;
                                prediction.Add(TransportAddressFactory.CreateInstance(t, host, pred_port));
                            }
                            else
                            {
                                //Increment the max by one just to keep a constant width:
                                max_delta += 1.001; //Giving a little extra to make sure we get 1
                            }
                            delta++;
                        }
                    }
                    catch {
                        //Just ignore any bad transport addresses.
                    }
                }
                else
                {
                    //The standard deviation is too wide to make a meaningful prediction
                }
            }
            return(prediction);
        }
Beispiel #17
0
 public IPTransportEnum(TransportAddress.TAType tat, int port, IEnumerable ips) {
   _tat = tat;
   _port = port;
   _ips = ips;
 }
Beispiel #18
0
 public IPTransportAddress(TransportAddress.TAType t, string host, int port) :
     this(String.Format("brunet.{0}://{1}:{2}", TATypeToString(t), host, port))
 {
     _type = t;
     _ips  = null;
 }
Beispiel #19
0
 public static string GetString(TransportAddress.TAType ta_type, int id)
 {
     return(String.Format("b.{0}://{1}", TransportAddress.TATypeToString(ta_type), id));
 }
Beispiel #20
0
 public IPTransportEnum(TransportAddress.TAType tat, int port, IEnumerable ips)
 {
     _tat  = tat;
     _port = port;
     _ips  = ips;
 }
Beispiel #21
0
 public static TransportAddress CreateInstance(TransportAddress.TAType t,
                                               IPEndPoint ep)
 {
     return(CreateInstance(t, ep.Address, ep.Port));
 }
Beispiel #22
0
 protected SimulationTransportAddress(int id, TransportAddress.TAType type) :
     this(GetString(type, id))
 {
     ID = id;
 }
Beispiel #23
0
 public FakeEdge(TransportAddress local, TransportAddress remote, TransportAddress.TAType tatype)
 {
   _tatype = tatype;
   local_add = local;
   remote_add = remote;
 }
    public SimulationEdgeListener(int id, double loss_prob, TAAuthorizer ta_auth,
        bool use_delay, TransportAddress.TAType type, INat nat)
    {
      _edges = new Dictionary<Edge, Edge>();
      _use_delay = use_delay;
      LocalID = id;
      _ploss_prob = loss_prob;
      if (ta_auth == null) {
        _ta_auth = new ConstantAuthorizer(TAAuthorizer.Decision.Allow);
      } else {
        _ta_auth = ta_auth;
      }
      _ta_type = type;

      Nat = nat;
      _is_started = false;
    }
Beispiel #25
0
    /**
     * Create a node with a given local address and
     * a set of Routers.
     * @param addr Address for the local node
     * @param realm the Realm or Namespace this node belongs to
     */

    protected Node(Address addr, string realm)
    {
      //Start with the address hashcode:
      _sync = new Object();
      lock(_sync)
      {
        DemuxHandler = new DemuxHandler();
        /*
         * Make all the hashtables : 
         */
        _local_add = AddressParser.Parse( addr.ToMemBlock() );
        _realm = String.Intern(realm);
        
        /* Set up the heartbeat */
        _heart_period = 500; //500 ms, or 1/2 second.
        _heartbeat_handlers = new Dictionary<EventHandler, Brunet.Util.FuzzyEvent>();

        _task_queue = new NodeTaskQueue(this);
        _packet_queue = new BCon.LFBlockingQueue<IAction>();

        _running = 0;
        _send_pings = 1;

        TransportAddress.TAType[] ord = new TransportAddress.TAType[6];
        ord[0] = TransportAddress.TAType.S;
        ord[1] = TransportAddress.TAType.SO;
        ord[2] = TransportAddress.TAType.Function;
        ord[3] = TransportAddress.TAType.Udp;
        ord[4] = TransportAddress.TAType.Tcp;
        ord[5] = TransportAddress.TAType.Relay;

        //The default is pretty good, but add fallback handling of Relay:
        var erp = DefaultERPolicy.Create(Brunet.Relay.RelayERPolicy.Instance,
                                         addr, ord);
        _connection_table = new ConnectionTable(erp);
        _connection_table.ConnectionEvent += this.ConnectionHandler;

        //We start off offline.
        _con_state = Node.ConnectionState.Offline;
        
        /* Set up the ReqrepManager as a filter */
        _rrm = new ReqrepManager(this.ToString());
        DemuxHandler.GetTypeSource(PType.Protocol.ReqRep).Subscribe(_rrm, null);
        _rrm.Subscribe(this, null);
        this.HeartBeatEvent += _rrm.TimeoutChecker;
        /* Set up RPC */
        _rpc = new RpcManager(_rrm);
        DemuxHandler.GetTypeSource( PType.Protocol.Rpc ).Subscribe(_rpc, null);
        //Add a map-reduce handlers:
        _mr_handler = new MR.MapReduceHandler(this);
        //Subscribe it with the RPC handler:
        _rpc.AddHandler("mapreduce", _mr_handler);
        //Set up Fragmenting Handler:
        var fh = new FragmentingHandler(1024); //cache at most 1024 fragments
        DemuxHandler.GetTypeSource(
          FragmentingSender.FragPType ).Subscribe(fh, this);
        fh.Subscribe(this, fh);
        /*
         * Where there is a change in the Connections, we might have a state
         * change
         */
        _connection_table.ConnectionEvent += this.CheckForStateChange;
        _connection_table.DisconnectionEvent += this.CheckForStateChange;

#if !BRUNET_SIMULATOR
        _codeinjection = new Brunet.Services.CodeInjection(this);
        _codeinjection.LoadLocalModules();
#endif
        /*
         * We must later make sure the EdgeEvent events from
         * any EdgeListeners are connected to _cph.EdgeHandler
         */
        /**
         * Here are the protocols that every edge must support
         */
        /* Here are the transport addresses */
        _remote_ta = ImmutableList<TransportAddress>.Empty;
        /*@throw ArgumentNullException if the list ( new ArrayList()) is null.
         */
        /* EdgeListener's */
        _edgelistener_list = new ArrayList();
        _co_list = new List<ConnectionOverlord>();
        _edge_factory = new EdgeFactory();
        _ta_discovery = ImmutableList<Discovery>.Empty;
        StateChangeEvent += HandleTADiscoveryState;
        
        /* Initialize this at 15 seconds */
        _connection_timeout = new TimeSpan(0,0,0,0,15000);
        //Check the edges from time to time
        IAction cec_act = new HeartBeatAction(this, this.CheckEdgesCallback);
        _check_edges = Brunet.Util.FuzzyTimer.Instance.DoEvery(delegate(DateTime dt) {
          this.EnqueueAction(cec_act);
        }, 5000, 500);
      }
    }
Beispiel #26
0
 /**
  * Creates an IEnumerable of TransportAddresses for a fixed type and port,
  * over a list of IPAddress objects.
  * Each time this the result is enumerated, ips.GetEnumerator is called,
  * so, if it changes, that is okay, (this is like a map() over a list, and
  * the original list can change).
  */
 public static IEnumerable Create(TransportAddress.TAType tat, int port, IEnumerable ips)
 {
     return(new IPTransportEnum(tat, port, ips));
 }
Beispiel #27
0
 /// <summary>Retrieve a given EL Dictionary for the TA Type.  This could leak,
 /// though that would take the creation of many different EL types and in normal
 /// usage there will only be 1 or 2 types.</summary>
 static protected Dictionary <int, SimulationEdgeListener> GetEdgeListenerList(TransportAddress.TAType type)
 {
     if (!_el_map.ContainsKey(type))
     {
         _el_map[type] = new Dictionary <int, SimulationEdgeListener>();
     }
     return(_el_map[type]);
 }