Пример #1
0
        protected void Start()
        {
            _start = true;
            for (int i = 0; i < _parameters.Size; i++)
            {
                AddNode();
            }

            TransportAddress broken_ta = TransportAddressFactory.CreateInstance("b.s://" + 0);

            for (int idx = 0; idx < Nodes.Count; idx++)
            {
                NodeMapping nm   = Nodes.Values[idx];
                var         tas  = new List <TransportAddress>();
                int         cidx = idx + 1;
                cidx = cidx == Nodes.Count ? 0 : cidx;
                tas.Add(Nodes.Values[cidx].Node.LocalTAs[0]);
                if (_broken != 0)
                {
                    tas.Add(broken_ta);
                }
                nm.Node.RemoteTAs = tas;
            }
            foreach (NodeMapping nm in Nodes.Values)
            {
                nm.Node.Connect();
            }
            _start = false;
        }
Пример #2
0
        public void Test()
        {
            string           ta_string = "brunet.tunnel://UBU72YLHU5C3SY7JMYMJRTKK4D5BGW22/FE4QWASN+FE4QWASM";
            TransportAddress ta        = TransportAddressFactory.CreateInstance("brunet.tunnel://UBU72YLHU5C3SY7JMYMJRTKK4D5BGW22/FE4QWASN+FE4QWASM");

            Assert.AreEqual(ta.ToString(), ta_string, "testing tunnel TA parsing");
            //Console.WriteLine(ta);

            RelayTransportAddress tun_ta = (RelayTransportAddress)TransportAddressFactory.CreateInstance("brunet.tunnel://OIHZCNNUAXTLLARQIOBNCUWXYNAS62LO/CADSL6GV+CADSL6GU");

            ArrayList fwd = new ArrayList();

            fwd.Add(new AHAddress(Base32.Decode("CADSL6GVVBM6V442CETP4JTEAWACLC5A")));
            fwd.Add(new AHAddress(Base32.Decode("CADSL6GUVBM6V442CETP4JTEAWACLC5A")));

            RelayTransportAddress test_ta = new RelayTransportAddress(tun_ta.Target, fwd);

            Assert.AreEqual(tun_ta, test_ta, "testing tunnel TA compression enhancements");
            //Console.WriteLine(tun_ta.ToString());
            //Console.WriteLine(test_ta.ToString());
            Assert.AreEqual(tun_ta.ToString(), test_ta.ToString(), "testing tunnel TA compression enhancements (toString)");

            Assert.AreEqual(tun_ta.ContainsForwarder(new AHAddress(Base32.Decode("CADSL6GVVBM6V442CETP4JTEAWACLC5A"))), true,
                            "testing tunnel TA contains forwarder (1)");

            Assert.AreEqual(tun_ta.ContainsForwarder(new AHAddress(Base32.Decode("CADSL6GUVBM6V442CETP4JTEAWACLC5A"))), true,
                            "testing tunnel TA contains forwarder (2)");
        }
Пример #3
0
 public override void UpdateLocalTAs(Edge e, TransportAddress ta)
 {
     if (e.TAType == TAType)
     {
         Nat.UpdateTAs(e.RemoteTA, ta);
     }
 }
Пример #4
0
 public SimulationEdgeListener(int id, double loss_prob, TAAuthorizer ta_auth, bool use_delay) :
     this(id, loss_prob, ta_auth, use_delay, TransportAddress.TAType.S,
          new PublicNat(TransportAddressFactory.CreateInstance(
                            String.Format("b.{0}://{1}",
                                          TransportAddress.TATypeToString(TransportAddress.TAType.S), id))))
 {
 }
Пример #5
0
        /// <summary>Creates an XmppEdge.</summary>
        public override void CreateEdgeTo(TransportAddress ta, EdgeCreationCallback ecb)
        {
            if (_ready == 0)
            {
                ecb(false, null, new Exception("Xmpp is not authenticated"));
            }

            XmppTransportAddress xta = ta as XmppTransportAddress;

            if (xta == null)
            {
                ecb(false, null, new Exception("TA Type is not Xmpp!"));
                return;
            }
            else if (!_xmpp.IsUserOnline(xta.JID))
            {
                ecb(false, null, new Exception("Xmpp user, " + xta.JID + ", is not online."));
                return;
            }

            XmppEdge xe = new XmppEdge(this, _local_ta, xta, false);

            _it.Add(xe);
            xe.CloseEvent += CloseHandler;
            ecb(true, xe, null);
        }
Пример #6
0
        public override void CreateEdgeTo(TransportAddress ta, EdgeCreationCallback ecb)
        {
            SubringTransportAddress sta = ta as SubringTransportAddress;

            if (sta == null)
            {
                ecb(false, null, new Exception("TA Type is not Subring!"));
            }
            else if (!sta.Namespace.Equals(_shared_node.Realm))
            {
                ecb(false, null, new Exception("Namespace mismatch"));
            }
            else if (sta.Target.Equals(_private_node.Address))
            {
                ecb(false, null, new Exception("You are me!"));
            }
            else
            {
                SubringEdge se = new SubringEdge(_local_ta, sta, false,
                                                 new AHExactSender(_shared_node, sta.Target), _ptype);
                se.CloseEvent += CloseHandler;
                _it.Add(se);
                ecb(true, se, null);
            }
        }
Пример #7
0
        /// <summary>Constructor for a TunnelEdge, RemoteID == -1 for out bound.</summary>
        public TunnelEdge(IEdgeSendHandler send_handler, TunnelTransportAddress local_ta,
                          TunnelTransportAddress remote_ta, IForwarderSelector ias, List <Connection> overlap,
                          int remote_id) : base(send_handler, remote_id != -1)
        {
            _remote_id = remote_id;
            lock (_rand) {
                LocalID = _rand.Next();
            }
            byte[] bid = new byte[8];
            NumberSerializer.WriteInt(LocalID, bid, 0);
            NumberSerializer.WriteInt(_remote_id, bid, 4);
            _mid       = MemBlock.Reference(bid);
            _local_ta  = local_ta;
            _remote_ta = remote_ta;
            _tunnels   = new List <Connection>(overlap);
            _ias       = ias;
            _ias.Update(_tunnels);

            AHHeader ahh = new AHHeader(1, 20, local_ta.Target, remote_ta.Target,
                                        AHHeader.Options.Exact);
            ICopyable header = new CopyList(PType.Protocol.AH, ahh,
                                            PType.Protocol.Tunneling);

            Header = MemBlock.Copy(header);
        }
 public Task <int> Intercept()
 {
     if (Options.AudioPort <= 0)
     {
         Console.Error.WriteLine("Setting --no-audio to true because --audio-port is not specified.");
         Options.NoAudio = true;
     }
     else
     {
         if (!TransportAddress.IsIPAddress(Options.AudioIPAddress))
         {
             Console.Error.WriteLine("--audio-ip-address is invalid.");
             return(Task.FromResult(1));
         }
     }
     if (Options.VideoPort <= 0)
     {
         Console.Error.WriteLine("Setting --no-video to true because --video-port is not specified.");
         Options.NoVideo = true;
     }
     else
     {
         if (!TransportAddress.IsIPAddress(Options.VideoIPAddress))
         {
             Console.Error.WriteLine("--video-ip-address is invalid.");
             return(Task.FromResult(1));
         }
     }
     return(Receive());
 }
Пример #9
0
        protected TransportAddress GetTransportAddress(int id)
        {
            string tas = String.Format("b.{0}://{1}",
                                       TransportAddress.TATypeToString(TAType), id);

            return(TransportAddressFactory.CreateInstance(tas));
        }
Пример #10
0
        public static NodeInfo CreateInstance(IDictionary d)
        {
            Address address = null;
            IList   tas;
            object  addr_str = d["address"];

            if (addr_str != null)
            {
                address = AddressParser.Parse((string)addr_str);
            }
            IList trans = d["transports"] as IList;

            if (trans != null)
            {
                int count = trans.Count;
                tas = new TransportAddress[count];
                for (int i = 0; i < count; i++)
                {
                    tas[i] = TransportAddressFactory.CreateInstance((string)trans[i]);
                }
                NodeInfo ni = CreateInstance(address, tas);
                return(ni);
            }
            else
            {
                NodeInfo ni = CreateInstance(address);
                return(ni);
            }
        }
Пример #11
0
        public void Test()
        {
            SimulationTransportAddress.Enable();
            SimulationTransportAddressOther.Enable();
            TransportAddress tas = TransportAddressFactory.CreateInstance("b.s://234580");

            Assert.AreEqual(tas.ToString(), "b.s://234580", "Simulation string");
            Assert.AreEqual((tas as SimulationTransportAddress).ID, 234580, "Simulation id");
            Assert.AreEqual(TransportAddress.TAType.S, tas.TransportAddressType, "Simulation ta type");

            TransportAddress taso = TransportAddressFactory.CreateInstance("b.so://234580");

            Assert.AreEqual(taso.ToString(), "b.so://234580", "Simulation string");
            Assert.AreEqual((taso as SimulationTransportAddressOther).ID, 234580, "Simulation id");
            Assert.AreEqual(TransportAddress.TAType.SO, taso.TransportAddressType, "Simulation ta type");

            Assert.AreNotEqual(taso, tas, "TAs not equal");
            Assert.AreNotEqual(taso.TransportAddressType, tas.TransportAddressType, "Type not equal");

            var tas1 = TransportAddressFactory.CreateInstance("b.s://-234581");

            Assert.AreEqual(-234581, (tas1 as SimulationTransportAddress).ID);
            var tas2 = (tas as SimulationTransportAddress).Invert();

            Assert.AreEqual(tas1, tas2, "Invert equal");
        }
Пример #12
0
        /**
         * When a ConnectionEvent occurs, this handler registers the
         * information with the node
         */
        public virtual void ConnectionHandler(object ct, EventArgs args)
        {
            ConnectionEventArgs ce_args = (ConnectionEventArgs)args;
            Edge edge = ce_args.Edge;

            edge.Subscribe(this, edge);
            //Our peer's remote is us
            TransportAddress reported_ta =
                ce_args.Connection.PeerLinkMessage.Remote.FirstTA;
            //Our peer's local is them
            TransportAddress remote_ta =
                ce_args.Connection.PeerLinkMessage.Local.FirstTA;

            /*
             * Make a copy so that _remote_ta never changes while
             * someone is using it
             */
            ArrayList new_remote_ta = new ArrayList();

            foreach (EdgeListener el in _edgelistener_list)
            {
                //Update our local list:
                el.UpdateLocalTAs(edge, reported_ta);
                el.UpdateRemoteTAs(new_remote_ta, edge, remote_ta);
            }
            UpdateRemoteTAs(new_remote_ta);
        }
Пример #13
0
        public void TestWriteAndParse()
        {
            RandomNumberGenerator rng = new RNGCryptoServiceProvider();
            Address          a        = new AHAddress(rng);
            TransportAddress ta       = TransportAddressFactory.CreateInstance("brunet.tcp://127.0.0.1:5000");
            NodeInfo         ni       = NodeInfo.CreateInstance(a, ta);

            RoundTripHT(ni);
            RoundTrip(ni);

            //Test multiple tas:
            ArrayList tas = new ArrayList();

            tas.Add(ta);
            for (int i = 5001; i < 5010; i++)
            {
                tas.Add(TransportAddressFactory.CreateInstance("brunet.tcp://127.0.0.1:" + i.ToString()));
            }
            NodeInfo ni3 = NodeInfo.CreateInstance(a, tas);

            RoundTripHT(ni3);
            RoundTrip(ni3);

            //Test null address:
            NodeInfo ni4 = NodeInfo.CreateInstance(null, ta);

            RoundTripHT(ni4);
            RoundTrip(ni4);

            //No TAs:
            NodeInfo ni5 = NodeInfo.CreateInstance(a);

            RoundTripHT(ni5);
            RoundTrip(ni5);
        }
Пример #14
0
        protected static NodeInfo CreateInstance(Address a, IList tas, TransportAddress ta)
        {
            NodeInfo result   = null;
            var      ni_cache = Interlocked.Exchange <WeakValueTable <int, NodeInfo> >(ref _cache, null);

            if (ni_cache != null)
            {
                try {
                    //Set up the key:
                    _cache_key._done_hash = false;
                    _cache_key._address   = a;
                    if (tas == null)
                    {
                        if (ta == null)
                        {
                            _cache_key._tas = EmptyTas;
                        }
                        else
                        {
                            _ta_list[0]     = ta;
                            _cache_key._tas = _ta_list;
                        }
                    }
                    else
                    {
                        _cache_key._tas = tas;
                    }

                    result = ni_cache.GetValue(_cache_key.GetHashCode());
                    if (!_cache_key.Equals(result))
                    {
                        //This may look weird, but we are using a NodeInfo as a key
                        //to lookup NodeInfos, this will allow us to only keep one
                        //identical NodeInfo in scope at a time.
                        if (ta == null)
                        {
                            //Note, if ta == null that implies tas is not null
                            result = new NodeInfo(a, tas);
                        }
                        else
                        {
                            result = new NodeInfo(a, ta);
                        }
                        ni_cache.Replace(result.GetHashCode(), result);
                    }
                } finally {
                    Interlocked.Exchange <WeakValueTable <int, NodeInfo> >(ref _cache, ni_cache);
                }
            }
            else if (ta == null)
            {
                //Note, if ta == null that implies tas is not null
                result = new NodeInfo(a, tas);
            }
            else
            {
                result = new NodeInfo(a, ta);
            }
            return(result);
        }
Пример #15
0
        public static NodeInfo CreateInstance(Address a, TransportAddress ta)
        {
            NodeInfo result   = null;
            Cache    ni_cache = Interlocked.Exchange <Cache>(ref _cache, null);

            if (ni_cache != null)
            {
                //Only one thread at the time can be in here:
                try {
                    //Set up the key:
                    _cache_key._done_hash = false;
                    _cache_key._address   = a;
                    _ta_list[0]           = ta;
                    _cache_key._tas       = _ta_list;

                    result = (NodeInfo)ni_cache[_cache_key];
                    if (result == null)
                    {
                        //This may look weird, but we are using a NodeInfo as a key
                        //to lookup NodeInfos, this will allow us to only keep one
                        //identical NodeInfo in scope at a time.
                        result           = new NodeInfo(a, ta);
                        ni_cache[result] = result;
                    }
                }
                finally {
                    Interlocked.Exchange <Cache>(ref _cache, ni_cache);
                }
            }
            else
            {
                result = new NodeInfo(a, ta);
            }
            return(result);
        }
Пример #16
0
        static public void AddNat(IEnumerable el_list, NatTypes type)
        {
            SimulationEdgeListener simel = null;

            foreach (EdgeListener el in el_list)
            {
                simel = el as SimulationEdgeListener;
                if (simel != null)
                {
                    break;
                }
            }

            if (simel == null)
            {
                throw new Exception("There was no SimulationEdgeListener");
            }

            TransportAddress ta = null;

            foreach (TransportAddress lta in simel.LocalTAs)
            {
                ta = lta;
                break;
            }

            if (ta == null)
            {
                throw new Exception("How did we get a null TA?");
            }

            simel.Nat = GetNat(ta, type);
        }
Пример #17
0
        public void SMTest()
        {
            Address          a  = new DirectionalAddress(DirectionalAddress.Direction.Left);
            TransportAddress ta = TransportAddressFactory.CreateInstance("brunet.tcp://127.0.0.1:5000");
            NodeInfo         ni = NodeInfo.CreateInstance(a, ta);

            //Test with one neighbor:
            ArrayList neighbors = new ArrayList();

            neighbors.Add(ni);
            StatusMessage sm1 = new StatusMessage(ConnectionType.Structured, neighbors);

            RoundTripHT(sm1);
            //Console.Error.WriteLine("\n{0}\n", sm1);
            //Test with many neighbors:

            for (int i = 5001; i < 5010; i++)
            {
                neighbors.Add(NodeInfo.CreateInstance(a,
                                                      TransportAddressFactory.CreateInstance("brunet.tcp://127.0.0.1:"
                                                                                             + i.ToString())));
            }
            StatusMessage sm2 = new StatusMessage(ConnectionType.Unstructured, neighbors);

            RoundTripHT(sm2);
            //Console.Error.WriteLine("\n{0}\n", sm2);

            //Here is a StatusMessage with no neighbors (that has to be a possibility)
            StatusMessage sm3 = new StatusMessage("structured", new ArrayList());

            RoundTripHT(sm3);
            //Console.Error.WriteLine("\n{0}\n", sm3);
        }
Пример #18
0
        /** creates a new outgoing Edge using the pathing protocol
         */
        public override void CreateEdgeTo(TransportAddress ta,
                                          EdgeListener.EdgeCreationCallback ecb)
        {
            if (!IsStarted)
            {
                throw new EdgeException("PathEdgeListener is not started");
            }
            string           rempath;
            TransportAddress base_ta = PathELManager.SplitPath(ta, out rempath);

            if (_path == PathELManager.Root && rempath == PathELManager.Root)
            {
                /*
                 * This is "normal" case, and we can skip all this stuff
                 */
                _el.CreateEdgeTo(ta, ecb);
            }
            else
            {
                CreateState cs = new CreateState(this, rempath, _path, ecb);

                /*
                 * Make the underlying Edge:
                 */
                _el.CreateEdgeTo(base_ta, cs.HandleEC);
            }
        }
Пример #19
0
        /**
         * This creates a TaskWorker that represents the next step that should
         * be taken for the ta.  It can only be two tasks: create the edge
         * (EdgeWorker) or wait and try again (RestartState).
         *
         * We return null if:
         *  - the TA is null
         *  - Linker is finished
         *  - a Connection was already created
         *  - this TA has been restarted too many times
         *
         * If we cannot get a ConnectionTable.Lock with SetTarget, we return a
         * RestartState to wait a little while to try to get the lock again.
         *
         * @returns the next TaskWorker that should be enqueued, does not start or
         * Enqueue it.
         */
        protected BC.TaskWorker StartAttempt(TransportAddress next_ta)
        {
            BC.TaskWorker next_task = null;
            if ((next_ta == null) || (_added_cons != 0) || IsFinished || ConnectionInTable)
            {
                //Looks like we are already connected...
                return(null);
            }
            try {
#if LINK_DEBUG
                if (BU.ProtocolLog.LinkDebug.Enabled)
                {
                    BU.ProtocolLog.Write(BU.ProtocolLog.LinkDebug,
                                         String.Format("{0}: Linker ({1}) attempting to lock {2}", _local_n.Address, _lid, _target));
                }
#endif

                /*
                 * If we cannot set this address as our target, we
                 * stop before we even try to make an edge.
                 *
                 * Locks flow around in complex ways, but we
                 * (or one of our LinkProtocolState)
                 * will hold the lock
                 */
                SetTarget();
#if LINK_DEBUG
                if (BU.ProtocolLog.LinkDebug.Enabled)
                {
                    BU.ProtocolLog.Write(BU.ProtocolLog.LinkDebug,
                                         String.Format("{0}: Linker ({1}) acquired lock on {2}", _local_n.Address, _lid, _target));
                    BU.ProtocolLog.Write(BU.ProtocolLog.LinkDebug,
                                         String.Format("{0}: Linker: ({1}) Trying TA: {2}", _local_n.Address, _lid, next_ta));
                }
#endif
                next_task              = new EdgeWorker(_local_n, next_ta);
                next_task.FinishEvent += this.EdgeWorkerHandler;
            }
            catch (CTLockException) {
                /*
                 * If we cannot get a lock on the address in SetTarget()
                 * we wait and and try again
                 */
#if LINK_DEBUG
                if (BU.ProtocolLog.LinkDebug.Enabled)
                {
                    BU.ProtocolLog.Write(BU.ProtocolLog.LinkDebug,
                                         String.Format("{0}: Linker ({1}) failed to lock {2}", _local_n.Address, _lid, _target));
                }
#endif
                next_task = GetRestartState(next_ta);
            }
            catch (ConnectionExistsException) {
                //We already have a connection to the target
            }
            catch (Exception) {
            }
            return(next_task);
        }
Пример #20
0
 public static NodeInfo CreateInstance(Address a, TransportAddress ta)
 {
     if (null == ta)
     {
         throw new System.ArgumentNullException("TransportAddress cannot be null");
     }
     return(CreateInstance(a, null, ta));
 }
Пример #21
0
 public RestartState(Linker l, TransportAddress ta,
                     int remaining_attempts)
 {
     _linker           = l;
     _ta               = ta;
     _restart_attempts = remaining_attempts;
     _first_start      = 1;
 }
Пример #22
0
        /** return the base TransportAddress and the path associated with it
         */
        public static TransportAddress SplitPath(TransportAddress ta, out string path)
        {
            Uri orig_u = ta.Uri;

            path = orig_u.AbsolutePath;
            string base_uri = String.Format("{0}://{1}", orig_u.Scheme, orig_u.Authority);

            return(TransportAddressFactory.CreateInstance(base_uri));
        }
Пример #23
0
 public EdgeCreationWrapper(TransportAddress ta, EdgeListener.EdgeCreationCallback ecb,
                            Edge edge, WrapperEdgeListener parent)
 {
     ExternalECB = ecb;
     TA          = ta;
     Parent      = parent;
     _edge       = edge;
     _called     = 0;
 }
Пример #24
0
 /// <summary>Create a XmppEdge.</summary>
 public XmppEdge(IEdgeSendHandler send_handler, XmppTransportAddress local_ta,
                 XmppTransportAddress remote_ta, bool inbound) :
     base(send_handler, inbound)
 {
     _ip        = new IdentifierPair();
     _local_ta  = local_ta;
     _remote_ta = remote_ta;
     To         = remote_ta.JID;
 }
Пример #25
0
 /// <summary>Constructor for an outgoing edge, since we don't know the remote
 /// id yet, it must be outgoing!</summary>
 public SubringEdge(TransportAddress local_ta, TransportAddress remote_ta,
                    bool inbound, ISender sender, PType ptype) :
     base(null, inbound)
 {
     _ip             = new IdentifierPair();
     _local_ta       = local_ta;
     _remote_ta      = remote_ta;
     _ptype          = ptype;
     _overlay_sender = sender;
 }
Пример #26
0
 public void UpdateTAs(TransportAddress remote_ta, TransportAddress local_ta)
 {
     if (_known_tas.Length == 2)
     {
         return;
     }
     _known_tas = new TransportAddress[2] {
         _internal_ta[0], local_ta
     };
     _allow_inbound = true;
 }
Пример #27
0
 public override TAAuthorizer.Decision Authorize(TransportAddress a)
 {
     if (_denied_id == ((SimulationTransportAddress)a).ID)
     {
         return(TAAuthorizer.Decision.Deny);
     }
     else
     {
         //else this decision should not matter
         return(TAAuthorizer.Decision.None);
     }
 }
Пример #28
0
        public void CacheTest()
        {
            RandomNumberGenerator rng = new RNGCryptoServiceProvider();
            Address          a        = new AHAddress(rng);
            Address          a2       = new AHAddress(a.ToMemBlock());
            TransportAddress ta       = TransportAddressFactory.CreateInstance("brunet.tcp://127.0.0.1:5000");
            TransportAddress ta2      = TransportAddressFactory.CreateInstance("brunet.tcp://127.0.0.1:5000");
            NodeInfo         ni       = NodeInfo.CreateInstance(a, ta);
            NodeInfo         ni2      = NodeInfo.CreateInstance(a2, ta2);

            Assert.AreSame(ni, ni2, "Reference equality of NodeInfo objects");
        }
Пример #29
0
        /*
         * Implements the EdgeListener function to
         * create edges of this type.
         */
        public override void CreateEdgeTo(TransportAddress ta, EdgeCreationCallback ecb)
        {
            if (!IsStarted)
            {
                // it should return null and not throw an exception
                // for graceful disconnect and preventing others to
                // connect to us after we've disconnected.
                ecb(false, null, new EdgeException("Not started"));
                return;
            }
            else if (ta.TransportAddressType != this.TAType)
            {
                //Can't make an edge of this type
                ecb(false, null, new EdgeException("Can't make edge of this type"));
                return;
            }
            else if (_ta_auth.Authorize(ta) == TAAuthorizer.Decision.Deny)
            {
                //Not authorized.  Can't make this edge:
                ecb(false, null, new EdgeException(ta.ToString() + " is not authorized"));
                return;
            }

            int remote_id      = ((SimulationTransportAddress)ta).ID;
            int real_remote_id = (remote_id >= 0) ? remote_id : ~remote_id;

            //Outbound edge:
            int delay = 0;

            if (_use_delay)
            {
                if (LatencyMap != null)
                {
                    int local  = LocalID % LatencyMap.Count;
                    int remote = real_remote_id % LatencyMap.Count;
                    delay = LatencyMap[local][remote] / 1000;
                }
                else
                {
                    delay = 100;
                }
            }

            SimulationEdge se_l = new SimulationEdge(this, LocalID, remote_id, false, delay, _ta_type);

            if (real_remote_id == remote_id)
            {
                CreateRemoteEdge(se_l);
            }
            ecb(true, se_l, null);
        }
Пример #30
0
        /**
         * If there is another TA in the _ta_queue, dequeue and return it,
         * otherwise, return null
         */
        protected TransportAddress NextTA()
        {
            bool             succ;
            TransportAddress next_ta = _ta_queue.TryDequeue(out succ);

            if (succ)
            {
                return(next_ta);
            }
            else
            {
                return(null);
            }
        }
Пример #31
0
    public override TAAuthorizer.Decision Authorize(TransportAddress a) {
      int id = ((SimulationTransportAddress) a).ID;
      if(id == 0) {
        return TAAuthorizer.Decision.Allow;
      }

      if(!_allowed.Contains(id)) {
        if(_rand.NextDouble() > _prob) {
          _allowed[id] = TAAuthorizer.Decision.Allow;
        } else {
          _allowed[id] = TAAuthorizer.Decision.Deny;
        }
      }

      return (TAAuthorizer.Decision) _allowed[id];
    }
Пример #32
0
    /**
     * Implements the EdgeListener function to 
     * create edges of this type.
     */
    public override void CreateEdgeTo(TransportAddress ta, EdgeCreationCallback ecb)
    {
      Edge e = null;
      try {
      if( !IsStarted )
      {
	throw new EdgeException("UdpEdgeListener is not started");
      }
      else if( ta.TransportAddressType != this.TAType ) {
	throw new EdgeException(ta.TransportAddressType.ToString()
				+ " is not my type: " + this.TAType.ToString() );
      }
      else if( _ta_auth.Authorize(ta) == TAAuthorizer.Decision.Deny ) {
        //Too bad.  Can't make this edge:
	throw new EdgeException( ta.ToString() + " is not authorized");
      }
      else {
        IPAddress first_ip = ((IPTransportAddress) ta).GetIPAddress();
        IPEndPoint end = new IPEndPoint(first_ip, ((IPTransportAddress) ta).Port);
        /* We have to keep our mapping of end point to edges up to date */
        lock( _id_ht ) {
          //Get a random ID for this edge:
          int id;
          do {
            id = _rand.Next();
	    //Make sure we don't have negative ids
            if( id < 0 ) { id = ~id; }
          } while( _id_ht.Contains(id) || id == 0 );
          e = new UdpEdge(this, false, end, _local_ep, id, 0);
          _id_ht[id] = e;
        }
        NatDataPoint dp = new NewEdgePoint(DateTime.UtcNow, e);
        Interlocked.Exchange<NatHistory>(ref _nat_hist, _nat_hist + dp);
        Interlocked.Exchange<IEnumerable>(ref _nat_tas, new NatTAs( _tas, _nat_hist ));

        /* Tell me when you close so I can clean up the table */
        e.CloseEvent += this.CloseHandler;
        ecb(true, e, null);
      }
      } catch(Exception ex) {
        if( e != null ) {
          //Clean up the edge
          CloseHandler(e, null);
        }
	ecb(false, null, ex);
      }
    }
Пример #33
0
 /**
  * When a new Connection is added, we may need to update the list
  * of TAs to make sure it is not too long, and that the it is sorted
  * from most likely to least likely to be successful
  * @param e the new Edge
  * @param ta the TransportAddress our TA according to our peer
  */
 public override void UpdateLocalTAs(Edge e, TransportAddress ta) {
   if( e.TAType == this.TAType ) {
     UdpEdge ue = (UdpEdge)e;
     ue.PeerViewOfLocalTA = ta;
     NatDataPoint dp = new LocalMappingChangePoint(DateTime.UtcNow, e, ta);
     Interlocked.Exchange<NatHistory>(ref _nat_hist, _nat_hist + dp);
     Interlocked.Exchange<IEnumerable>(ref _nat_tas, new NatTAs( _tas, _nat_hist ));
   }
 }
Пример #34
0
    /// <summary>Constructor for a TunnelEdge, RemoteID == -1 for out bound.</summary>
    public TunnelEdge(IEdgeSendHandler send_handler, TunnelTransportAddress local_ta,
        TunnelTransportAddress remote_ta, IForwarderSelector ias, List<Connection> overlap,
        int remote_id) : base(send_handler, remote_id != -1)
    {
      _remote_id = remote_id;
      lock(_rand) {
        LocalID = _rand.Next();
      }
      byte[] bid = new byte[8];
      NumberSerializer.WriteInt(LocalID, bid, 0);
      NumberSerializer.WriteInt(_remote_id, bid, 4);
      _mid = MemBlock.Reference(bid);
      _local_ta = local_ta;
      _remote_ta = remote_ta;
      _tunnels = new List<Connection>(overlap);
      _ias = ias;
      _ias.Update(_tunnels);

      AHHeader ahh = new AHHeader(1, 20, local_ta.Target, remote_ta.Target,
          AHHeader.Options.Exact);
      ICopyable header = new CopyList(PType.Protocol.AH, ahh,
          PType.Protocol.Tunneling);
      Header = MemBlock.Copy(header);
    }
Пример #35
0
    /*
     * Implements the EdgeListener function to 
     * create edges of this type.
     */
    public override void CreateEdgeTo(TransportAddress ta,
                                      EdgeCreationCallback ecb)
    {
      if( !IsStarted )
      {
        // it should return null and not throw an exception
        // for graceful disconnect and preventing others to
        // connect to us after we've disconnected.
        ecb(false, null, new EdgeException("Not started"));
        return;
      }

#if FUNCTION_DEBUG
      foreach (TransportAddress local_ta in LocalTAs) {
	Console.Error.WriteLine("Create edge local: {0} <-> remote {1}.", local_ta, ta);
      }
#endif

      if( ta.TransportAddressType != this.TAType ) {
        //Can't make an edge of this type
#if FUNCTION_DEBUG
	Console.Error.WriteLine("Can't make edge of this type.");
#endif
        ecb(false, null, new EdgeException("Can't make edge of this type"));
	return;
      }
      
      if( _ta_auth.Authorize(ta) == TAAuthorizer.Decision.Deny ) {
        //Not authorized.  Can't make this edge:
#if FUNCTION_DEBUG
	Console.Error.WriteLine("Can't make edge. Remote TA {0} is not authorized locally.", ta);
#endif
        ecb(false, null,
            new EdgeException( ta.ToString() + " is not authorized") );
	return;
      }
      
      int remote_id = ((IPTransportAddress) ta).Port;
      //Get the edgelistener: 

      //Outbound edge:
      FunctionEdge fe_l = new FunctionEdge(this, _listener_id,
					   remote_id, false);
      lock( _listener_map ) { 
	FunctionEdgeListener remote
	  = (FunctionEdgeListener) _listener_map[remote_id];
	if( remote != null ) {
	  //
	  // Make sure that the remote listener does not deny 
	  // our TAs.
	  //

	  foreach (TransportAddress ta_local in LocalTAs) {
	    if (remote.TAAuth.Authorize(ta_local) == TAAuthorizer.Decision.Deny ) {
	      //Not authorized.  Can't make this edge:
#if FUNCTION_DEBUG
	      Console.Error.WriteLine("Can't make edge. local TA {0} is not authorized remotely by {1}.", ta_local, ta);
#endif
	      ecb(false, null,
		  new EdgeException( ta_local.ToString() + " is not authorized by remote node.") );
	      return;
	    }
	  }

	  FunctionEdge fe_r = new FunctionEdge(remote, remote_id,
					       _listener_id, true);
	  fe_l.Partner = fe_r;
	  fe_r.Partner = fe_l;
	  remote.SendEdgeEvent(fe_r);
	}
	else {
	  //There is no other edge, for now, we use "udp-like"
	  //behavior of just making an edge that goes nowhere.
	}
        ecb(true, fe_l, null);
      }
    }
Пример #36
0
       /**
        * It is imperative that the ECB be called and not ignored.  Not
        * calling back will leave the system in a stale state as it waits
        * for the CreateEdgeTo to complete.
        * @param ta TransportAddress to create an edge to
        * @param ecb the EdgeCreationCallback to call when done
        * @throw EdgeException if we try to call this before calling
        */
 public abstract void CreateEdgeTo(TransportAddress ta, EdgeCreationCallback ecb);
Пример #37
0
 ///<summary>This is passed tothe underlying EdgeListener.  By default we do
 ///nothing to this.</summary>
 public override void UpdateRemoteTAs(IList list, Edge e, TransportAddress ta) {
   WrapperEdge edge = e as WrapperEdge;
   _el.UpdateRemoteTAs(list, edge.WrappedEdge, ta);
 }
Пример #38
0
 public FakeEdge(TransportAddress local, TransportAddress remote) :
   this(local, remote, TransportAddress.TAType.Tcp)
 {
 }
Пример #39
0
    /// <summary>Creates an XmppEdge.</summary>
    public override void CreateEdgeTo(TransportAddress ta, EdgeCreationCallback ecb)
    {
      if(_ready == 0) {
        ecb(false, null, new Exception("Xmpp is not authenticated"));
      }

      XmppTransportAddress xta = ta as XmppTransportAddress;
      if(xta == null) {
        ecb(false, null, new Exception("TA Type is not Xmpp!"));
        return;
      } else if(!_xmpp.IsUserOnline(xta.JID)) {
        ecb(false, null, new Exception("Xmpp user, " + xta.JID + ", is not online."));
        return;
      }

      XmppEdge xe = new XmppEdge(this, _local_ta, xta, false);
      _it.Add(xe);
      xe.CloseEvent += CloseHandler;
      ecb(true, xe, null);
    }
Пример #40
0
 public FakeEdge(TransportAddress local, TransportAddress remote, TransportAddress.TAType tatype)
 {
   _tatype = tatype;
   local_add = local;
   remote_add = remote;
 }
Пример #41
0
 /// <summary>Does not immediately create an edge to a remote node, instead,
 /// it tells a timer to wait 5 seconds prior to attempting an edge.</summary>
 public override void CreateEdgeTo(TransportAddress ta, EdgeCreationCallback ecb)
 {
   TunnelTransportAddress tta = ta as TunnelTransportAddress;
   if(tta == null) {
     ecb(false, null, new Exception("TA Type is not Tunnel!"));
   } else {
     TunnelEdgeCallbackAction teca = new TunnelEdgeCallbackAction(tta, ecb);
     System.Action<DateTime> callback = delegate(DateTime now) {
       CreateEdgeTo(teca);
     };
     Brunet.Util.FuzzyTimer.Instance.DoAfter(callback, 10000, 0);
   }
 }
Пример #42
0
 /** return the base TransportAddress and the path associated with it
  */
 public static TransportAddress SplitPath(TransportAddress ta, out string path) {
   Uri orig_u = ta.Uri;
   path = orig_u.AbsolutePath;
   string base_uri = String.Format("{0}://{1}", orig_u.Scheme, orig_u.Authority);
   return TransportAddressFactory.CreateInstance(base_uri);
 }
Пример #43
0
 public EdgeCreationWrapper(TransportAddress ta, EdgeListener.EdgeCreationCallback ecb,
     Edge edge, WrapperEdgeListener parent)
 {
   ExternalECB = ecb;
   TA = ta;
   Parent = parent;
   _edge = edge;
   _called = 0;
 }
Пример #44
0
 /** Join a path to the end of a TransportAddress
  */
 public static TransportAddress JoinPath(TransportAddress ta, string path) {
   Uri orig_u = ta.Uri;
   string s = orig_u.ToString();
   if( s[s.Length - 1] == '/' ) {
     s = s.Substring(0, s.Length - 1);
   }
   if (path[0] == '/') {
     path = path.Substring(1);
   }
   return TransportAddressFactory.CreateInstance(String.Format("{0}/{1}", s, path));
 }
Пример #45
0
 ///<summary>This wraps the underlying CreateEdgeTo using EdgeCreationWrappers</summary>
 public override void CreateEdgeTo(TransportAddress ta, EdgeCreationCallback ecb) {
   EdgeCreationWrapper ecw = new EdgeCreationWrapper(ta, ecb, null, this);
   _el.CreateEdgeTo(ta, ecw.Callback);
 }
Пример #46
0
 /** creates a new outgoing Edge using the pathing protocol
  */
 public override void CreateEdgeTo(TransportAddress ta,
                                   EdgeListener.EdgeCreationCallback ecb) {
   if( !IsStarted ) {
     throw new EdgeException("PathEdgeListener is not started");
   }
   string rempath;
   TransportAddress base_ta = PathELManager.SplitPath(ta, out rempath);
   if( _path == PathELManager.Root && rempath == PathELManager.Root ) {
     /*
      * This is "normal" case, and we can skip all this stuff
      */
     _el.CreateEdgeTo(ta, ecb);
   }
   else {
     CreateState cs = new CreateState(this, rempath, _path, ecb);
     /*
      * Make the underlying Edge:
      */
     _el.CreateEdgeTo(base_ta, cs.HandleEC);
   }
 }
Пример #47
0
 /**
  * We learn RemotaTAs in case we need to get connected again in the
  * future.  These are TransportAddress objects that should be good
  * at some point in the future.
  * @param list the list of TransportAddress objects to update
  * @param e the new Edge
  * @param ta the TransportAddress the remote end of the
  * edge according to our peer
  */
 public virtual void UpdateRemoteTAs(IList list, Edge e, TransportAddress ta) {
   if( e.TAType == this.TAType ) {
     if( e.RemoteTANotEphemeral ) {
       //There is some chance this will be good again in the future
       //But, we only keep non-natted TAs, since NAT mappings change
       //so frequently, a NATed TA will probably be bad in the future
       if( ta.Equals( e.RemoteTA ) ) {
         //This node is not behind a NAT.
         int idx = list.IndexOf(ta);
         if( idx >= 0 ) {
           list.Remove(ta);
         }
         //Now put the i
         list.Insert(0, ta);
       }
     }
   }
 }
Пример #48
0
 /**
  * When a new Connection is added, we may need to update the list
  * of TAs to make sure it is not too long, and that the it is sorted
  * from most likely to least likely to be successful
  * @param e the new Edge
  * @param ta the TransportAddress our TA according to our peer
  */
 public virtual void UpdateLocalTAs(Edge e, TransportAddress ta) {
 
 }
Пример #49
0
 ///<summary>This is passed tothe underlying EdgeListener.  By default we do
 ///nothing to this.</summary>
 public override void UpdateLocalTAs(Edge e, TransportAddress ta) {
   WrapperEdge edge = e as WrapperEdge;
   _el.UpdateLocalTAs(edge.WrappedEdge, ta);
 }