Exemplo n.º 1
0
        public void StreetDesignator()
        {
            var addresses = new[]
            {
                "2790 Yew Street",
                "2790 Yew street, apt. 408",
                "2790 Yew str., apt. 408",
                "2790 Yew St.",
            };

            foreach (var address in addresses)
            {
                Assert.AreEqual("Street", AddressParser.Parse(address).StreetDesignator, "Address: " + address);
            }
        }
Exemplo n.º 2
0
        public void It_should_handle_single_column_address()
        {
            //arrange
            var          parser = new AddressParser();
            const string line   = "Shelby Macias	P.O. Box 954	1 66 890 3865-9584	[email protected]";

            //act
            var address = parser.Parse(line);

            //assert
            Assert.That(address.Address, Is.EqualTo("P.O. Box 954"));
            Assert.That(address.City, Is.Empty);
            Assert.That(address.Province, Is.Empty);
            Assert.That(address.PostCode, Is.Empty);
            Assert.That(address.Country, Is.Empty);
        }
Exemplo n.º 3
0
        public void SimpleAddress_IsParsed()
        {
            // arrange
            var systemUnderTest = new AddressParser();

            // act
            var result = systemUnderTest.Parse("123 Main Street Hartford CT 06101");

            // assert
            Assert.Equal("123", result.StreetNumber);
            Assert.Equal("Main", result.StreetName);
            Assert.Equal("Street", result.StreetType);
            Assert.Equal("Hartford", result.Town);
            Assert.Equal("CT", result.State);
            Assert.Equal("06101", result.ZipCode);
        }
Exemplo n.º 4
0
        public void StreetName()
        {
            var addresses = new[]
            {
                "2790 Marine Drive SW",
                "2790 Marine drive sw, apt. 408",
                "2790 Marine",
                "408-2790 Marine dr.",
                "#408-2790 sw Marine DR."
            };

            foreach (var address in addresses)
            {
                Assert.AreEqual("Marine", AddressParser.Parse(address).StreetName, "Address: " + address);
            }
        }
Exemplo n.º 5
0
        /// <summary>This is the work horse method.</summary>
        public override void Run()
        {
            // This handles the whole process of preparing the Brunet.Node.
            _app_node = CreateNode(_node_config);
            // Each Brunet.Node contains a DemuxHandler, this object allows us to
            // request that any message with a specific PType arrive here at the
            // HandleData method.  In this case, we want the PType("HelloWorld"),
            // to arrive here, and without state.
            _app_node.Node.DemuxHandler.GetTypeSource(HW).Subscribe(this, null);

            // Services include XmlRpcManager and Dht over XmlRpcManager
            // Start the Brunet.Node and allow it to connect to remote nodes
            Thread thread = new Thread(_app_node.Node.Connect);

            thread.Start();

            // We finally are at the hello world
            // This is our address, you can copy and paste this locally and at other
            // sites to communicate
            Console.WriteLine("Your address is: " + _app_node.Node.Address + "\n");

            // We will continue on, until we get to the Disconnected states.  Assumming
            // you are running this on a supported platform, that would be triggered
            // initially by ctrl-c
            while (_app_node.Node.ConState != Node.ConnectionState.Disconnected)
            {
                // First we need the address of the remote node
                Console.Write("Send message to: ");
                string  address_string = Console.ReadLine().Trim(new char[] { ' ', '\t' });
                Address addr           = null;
                try {
                    addr = AddressParser.Parse(address_string);
                } catch {
                    Console.WriteLine("Invalid address!\n");
                    continue;
                }

                // Get a message
                Console.Write("Message: ");
                string message = Console.ReadLine();

                //Call the Send Message passing in a MemBlock which happens to implement ICopyable
                SendMessage(addr, MemBlock.Reference(Encoding.UTF8.GetBytes(message)));
                Console.WriteLine("Sent...\n");
            }
        }
Exemplo n.º 6
0
        public void CheckEmptyTest()
        {
            var lines       = File.ReadAllLines(Address);
            var count       = lines.Where(string.IsNullOrEmpty).Count();
            var parser      = new AddressParser();
            var parserCount = 0;

            foreach (var line in lines)
            {
                var result = parser.Parse(line);
                if (result.IsEmpty)
                {
                    parserCount++;
                }
            }
            Assert.AreEqual(count, parserCount);
        }
Exemplo n.º 7
0
        // Provides a method for local apps to add certificates to Brunet without
        // being loaded with Brunet.
        public void HandleRpc(ISender caller, string method, IList args, object rs)
        {
            object result = null;

            try {
                if (method.Equals("AddCertificate"))
                {
                    ReqrepManager.ReplyState rqrs = caller as ReqrepManager.ReplyState;
                    if (rqrs == null || !(rqrs.ReturnPath is Node))
                    {
                        throw new Exception("Call must be made locally for security reasons!");
                    }
                    string path = (string)args[0];
                    result = _ch.AddCertificate(path);
                }
                else if (method.Equals("GetState"))
                {
                    if (args.Count != 1)
                    {
                        throw new Exception("Not enough arguments");
                    }
                    else if (!(args[0] is string))
                    {
                        throw new Exception("Argument should be a string");
                    }
                    Address             addr = AddressParser.Parse(args[0] as string);
                    SecurityAssociation sa   = CheckForSecureSender(addr);
                    if (sa == null)
                    {
                        result = "No SA";
                    }
                    else
                    {
                        result = sa.ToString();
                    }
                }
                else
                {
                    result = new Exception("Invalid method");
                }
            } catch (Exception e) {
                result = e;
            }
            _node.Rpc.SendResult(rs, result);
        }
Exemplo n.º 8
0
        public SocialUser AddFriend(string address, string cert, string uid,
                                    string ip)
        {
            if (_friends.ContainsKey(address))
            {
                throw new Exception("Address already exists");
            }

            Address    addr   = AddressParser.Parse(address);
            string     new_ip = _marad.AddIPMapping(ip, addr);
            SocialUser user   = new SocialUser(cert, new_ip, null);

            Bso.CertificateHandler.AddCACertificate(user.X509);
            _mco.Set(addr);
            _friends = _friends.InsertIntoNew(address, user);

            return(user);
        }
Exemplo n.º 9
0
 public void UnitNumber()
 {
     Assert.AreEqual("408", AddressParser.Parse("408-2790 Yew St.").UnitNumber);
     Assert.AreEqual("408", AddressParser.Parse("  408 - 2790 Yew St.").UnitNumber);
     Assert.AreEqual("408", AddressParser.Parse("#408-2790 Yew St.").UnitNumber);
     Assert.AreEqual("408", AddressParser.Parse("# 408  - 2790 Yew St.").UnitNumber);
     Assert.AreEqual("408", AddressParser.Parse("2790 Yew St., #408").UnitNumber);
     Assert.AreEqual("408", AddressParser.Parse("apt.408, 2790 Yew St.").UnitNumber);
     Assert.AreEqual("408", AddressParser.Parse("2790 Yew St., Apt. 408, floor 4").UnitNumber);
     Assert.AreEqual("408", AddressParser.Parse(" Unit 408, 2790 Yew St.").UnitNumber);
     Assert.AreEqual("408", AddressParser.Parse("2790 Yew St., unit 408").UnitNumber);
     Assert.AreEqual("408", AddressParser.Parse("2790 Yew St., suite 408").UnitNumber);
     Assert.AreEqual("408", AddressParser.Parse("Suite 408 - 2790 Yew St.").UnitNumber);
     Assert.AreEqual("408", AddressParser.Parse("2790 Yew St., apartment 408").UnitNumber);
     Assert.AreEqual("408", AddressParser.Parse("Apartment 408 - 2790 Yew St.").UnitNumber);
     Assert.AreEqual("408-S", AddressParser.Parse("408-S - 2790 Yew St.").UnitNumber);
     Assert.AreEqual("408-S", AddressParser.Parse("2790 Yew St., #408-S").UnitNumber);
 }
Exemplo n.º 10
0
        public void It_should_parse_pipe_delimitted_address_string()
        {
            //arrange
            var          parser = new AddressParser();
            const string line   = "Shelby Macias	3027 Lorem St.|Kokomo|Hertfordshire|L9T 3D5|Finland	1 66 890 3865-9584	[email protected]";

            //act
            var address = parser.Parse(line);

            //assert
            Assert.That(address.Address, Is.EqualTo("3027 Lorem St."));
            Assert.That(address.City, Is.EqualTo("Kokomo"));
            Assert.That(address.Province, Is.EqualTo("Hertfordshire"));
            Assert.That(address.PostCode, Is.EqualTo("L9T 3D5"));
            Assert.That(address.Country, Is.EqualTo("Finland"));
            Assert.That(address.Name, Is.EqualTo("Shelby Macias"));
            Assert.That(address.Phone, Is.EqualTo("1 66 890 3865-9584"));
            Assert.That(address.Email, Is.EqualTo("*****@*****.**"));
        }
Exemplo n.º 11
0
        public void Test()
        {
            RandomNumberGenerator rng     = new RNGCryptoServiceProvider();
            AHAddress             tmp_add = new AHAddress(rng);
            Node             n            = new StructuredNode(tmp_add, "unittest");
            AHSender         ah           = new AHSender(n, AddressParser.Parse("brunet:node:JOJZG7VO6RFOEZJ6CJJ2WOIJWTXRVRP4"));
            ForwardingSender fs           = new ForwardingSender(n,
                                                                 AddressParser.Parse("brunet:node:JOJZG7VO6RFOEZJ6CJJ2WOIJWTXRVRP4"),
                                                                 AddressParser.Parse("brunet:node:5FMQW3KKJWOOGVDO6QAQP65AWVZQ4VUQ"));

            string  uri = "sender:ah?dest=JOJZG7VO6RFOEZJ6CJJ2WOIJWTXRVRP4&mode=exact";
            ISender s   = SenderFactory.CreateInstance(n, uri);

            Assert.IsTrue(s is AHSender);
            Assert.AreEqual(uri, s.ToUri());
            uri = "sender:ah?dest=JOJZG7VO6RFOEZJ6CJJ2WOIJWTXRVRP4&mode=greedy";

            //Create the above programatically
            IDictionary <string, string> param_args = new Dictionary <string, string>();

            param_args["dest"] = "JOJZG7VO6RFOEZJ6CJJ2WOIJWTXRVRP4";
            param_args["mode"] = "greedy";
            string uri0 = SenderFactory.EncodeUri("ah", param_args);

            Assert.AreEqual(uri, uri0, "EncodeUri works");
            //Check decode:
            string scheme;

            param_args = SenderFactory.DecodeUri(uri, out scheme);
            Assert.AreEqual(scheme, "ah", "Scheme decoded");
            Assert.AreEqual(param_args.Count, 2, "2 parameters in uri");
            Assert.AreEqual(param_args["dest"], "JOJZG7VO6RFOEZJ6CJJ2WOIJWTXRVRP4", "Extracted address");
            Assert.AreEqual(param_args["mode"], "greedy", "got mode");

            s = SenderFactory.CreateInstance(n, uri);
            Assert.IsTrue(s is AHSender);
            Assert.AreEqual(uri, s.ToUri());
            string furi = "sender:fw?relay=JOJZG7VO6RFOEZJ6CJJ2WOIJWTXRVRP4&init_mode=greedy&dest=5FMQW3KKJWOOGVDO6QAQP65AWVZQ4VUQ&ttl=3&mode=path";

            s = SenderFactory.CreateInstance(n, furi);
            Assert.IsTrue(s is ForwardingSender);
            Assert.AreEqual(furi, s.ToUri());
        }
Exemplo n.º 12
0
        protected void HandleGetInformation(Object o, EventArgs ea)
        {
            Channel   queue = (Channel)o;
            Hashtable ht    = null;

            try {
                RpcResult rpc_reply = (RpcResult)queue.Dequeue();
                ht = (Hashtable)rpc_reply.Result;
            }
            catch {
                // Remote end point doesn't have LocalCO enabled.
                return;
            }

            try {
                string remote_realm = (string)ht["namespace"];
                if (!remote_realm.Equals(_node.Realm))
                {
                    return;
                }
                ArrayList string_tas = (ArrayList)ht["tas"];
                ArrayList remote_tas = new ArrayList();
                foreach (string ta in string_tas)
                {
                    remote_tas.Add(TransportAddressFactory.CreateInstance(ta));
                }
                _node.UpdateRemoteTAs(remote_tas);

                AHAddress new_address = (AHAddress)AddressParser.Parse((string)ht["address"]);
                lock (_sync) {
                    int pos = _local_addresses.BinarySearch(new_address, addr_compare);
                    if (pos < 0)
                    {
                        pos = ~pos;
                        _local_addresses.Insert(pos, new_address);
                    }
                }
            }
            catch (Exception e) {
                ProtocolLog.WriteIf(ProtocolLog.Exceptions, "Unexpected exception: " + e);
            }
        }
Exemplo n.º 13
0
 /**
  * This dispatches the particular methods this class provides
  */
 public void HandleRpc(ISender caller, string method, IList args, object req_state)
 {
     if (method == "Echo")
     {
         Echo();
         _rpc.SendResult(req_state, new object[] {});
     }
     else if (method == "EchoVivaldiState")
     {
         Hashtable ht = EchoVivaldiState();
         _rpc.SendResult(req_state, ht);
     }
     else if (method == "ComputePathLatencyTo")
     {
         ComputePathLatencyTo((AHAddress)AddressParser.Parse((string)args[0]), req_state);
     }
     else
     {
         throw new AdrException(-32601, "No Handler for method: " + method);
     }
 }
Exemplo n.º 14
0
        /// <summary>This is the asynchronous callback for Miss.  This contains the
        /// lookup results from the Dht.  If there is a valid mapping it is added to
        /// the cache.  Either way, new queries can now be run for the IP address
        /// after the completion of this method.</summary>
        /// <param name="o">Contains the Channel where the results are stored.</param>
        /// <param name="args">Null.</param>
        protected void MissCallback(Object o, EventArgs args)
        {
            Channel queue = (Channel)o;
            // Requires synchronized reading
            MemBlock ip = null;

            lock (_sync) {
                ip = _mapping[queue];
            }
            String  ips  = Utils.MemBlockToString(ip, '.');
            Address addr = null;

            try {
                Hashtable dgr = (Hashtable)queue.Dequeue();
                addr = AddressParser.Parse(Encoding.UTF8.GetString((byte[])dgr["value"]));
                if (IpopLog.ResolverLog.Enabled)
                {
                    ProtocolLog.Write(IpopLog.ResolverLog, String.Format(
                                          "Got result for {0} ::: {1}.", ips, addr));
                }
            } catch {
                if (IpopLog.ResolverLog.Enabled)
                {
                    ProtocolLog.Write(IpopLog.ResolverLog, String.Format(
                                          "Failed for {0}.", Utils.MemBlockToString(ip, '.')));
                }
            }

            lock (_sync) {
                if (addr != null)
                {
                    _cache.Update(ip, addr);
                    _attempts.Remove(ip);
                }

                _queued.Remove(ip);
                _mapping.Remove(queue);
            }
        }
Exemplo n.º 15
0
        public TunnelTransportAddress(string s) : base(s)
        {
            /** String representing the tunnel TA is as follows: brunet.tunnel://A/X1+X2+X3
             *  A: target address
             *  X1, X2, X3: forwarders, each X1, X2 and X3 is actually a slice of the initial few bytes of the address.
             */
            int k  = s.IndexOf(":") + 3;
            int k1 = s.IndexOf("/", k);

            byte [] addr_t = Base32.Decode(s.Substring(k, k1 - k));
            _target     = AddressParser.Parse(MemBlock.Reference(addr_t));
            k           = k1 + 1;
            _forwarders = new ArrayList();
            while (k < s.Length)
            {
                byte [] addr_prefix = Base32.Decode(s.Substring(k, 8));
                _forwarders.Add(MemBlock.Reference(addr_prefix));
                //jump over the 8 characters and the + sign
                k = k + 9;
            }
            _forwarders.Sort();
        }
Exemplo n.º 16
0
 /**
  * This dispatches the particular methods this class provides
  */
 public void HandleRpc(ISender caller, string method, IList args, object req_state)
 {
     if (method == "GetRttTo")
     {
         ISender         dest = new AHGreedySender(_node, AddressParser.Parse((string)args[0]));
         EchoSendHandler esh  = new EchoSendHandler(_node, dest, req_state);
         //This will be garbage collected after the request is done:
         esh.SendEchoRequest();
     }
     else if (method == "GetRouteTo")
     {
         DoTraceRouteTo((AHAddress)AddressParser.Parse((string)args[0]), req_state);
     }
     else if (method == "RecursiveCall")
     {
         RecursiveCall(args, req_state);
     }
     else
     {
         throw new AdrException(-32601, "No Handler for method: " + method);
     }
 }
Exemplo n.º 17
0
            protected void CrawlHandler(object o, EventArgs ea)
            {
                Address addr = _node.Address;
                Channel q    = (Channel)o;

                try {
                    RpcResult res = (RpcResult)q.Dequeue();
                    Hashtable ht  = (Hashtable)res.Result;

                    Address left    = AddressParser.Parse((String)ht["left"]);
                    Address next    = AddressParser.Parse((String)ht["right"]);
                    Address current = AddressParser.Parse((String)ht["self"]);
                    if (left.Equals(_previous))
                    {
                        _consistency++;
                    }
                    else if (_previous == null)
                    {
                        _first_left = left;
                    }

                    if (current.Equals(_first_left) && _node.Address.Equals(next))
                    {
                        _consistency++;
                    }

                    _previous = current;
                    addr      = next;
                } catch (Exception e) {
                    if (_log)
                    {
                        Console.WriteLine("Crawl failed due to exception...");
                        Console.WriteLine(e);
                    }
                }
                CrawlNext(addr);
            }
        /**
         * Periodically check if our connections are still optimal.
         */
        protected void CheckConnectionOptimality(object node, EventArgs eargs)
        {
            DateTime now = DateTime.UtcNow;

            lock (_sync) {
                if ((now - _last_optimize_time).TotalSeconds < OPTIMIZE_DELAY)
                {
                    return;
                }
                _last_optimize_time = now;
            }

            if (LogEnabled)
            {
                ProtocolLog.Write(ProtocolLog.SCO,
                                  String.Format("SCO local: {0}, Selcting a random shortcut to optimize.",
                                                _node.Address));
            }
            double logk = Math.Log((double)_node.NetworkSize, 2.0);

            //Get a random shortcut:
            ArrayList shortcuts = new ArrayList();

            foreach (Connection sc in _node.ConnectionTable.GetConnections(STRUC_SHORT))
            {
                /**
                 * Only if we initiated it, we check if the connection is optimal.
                 * First half of the token is initiator address, while the other half
                 * is the start of the range.
                 */
                string token = sc.PeerLinkMessage.Token;
                if (token == null || token == String.Empty)
                {
                    continue;
                }

                string initiator_addr = token.Substring(0, token.Length / 2);
                if (initiator_addr == _node.Address.ToString())
                {
                    shortcuts.Add(sc);
                }
            }


            if (shortcuts.Count > 0)
            {
                // Pick a random shortcut and check for optimality.
                Connection sc    = (Connection)shortcuts[_rand.Next(shortcuts.Count)];
                string     token = sc.PeerLinkMessage.Token;
                // Second half of the token is the random target for the shortcut.
                Address random_target = AddressParser.Parse(token.Substring(token.Length / 2));
                if (LogEnabled)
                {
                    ProtocolLog.Write(ProtocolLog.SCO,
                                      String.Format("SCO local: {0}, Optimizing shortcut connection: {1}, random_target: {2}.",
                                                    _node.Address, sc.Address, random_target));
                }

                _target_selector.ComputeCandidates(random_target, (int)Math.Ceiling(logk),
                                                   CheckShortcutCallback, sc.Address);
            }
            else
            {
                if (LogEnabled)
                {
                    ProtocolLog.Write(ProtocolLog.SCO,
                                      String.Format("SCO local: {0}, Cannot find a shortcut to optimize.",
                                                    _node.Address));
                }
            }

            //also optimize the bypass connections.
            if (LogEnabled)
            {
                ProtocolLog.Write(ProtocolLog.SCO,
                                  String.Format("SCO local: {0}, Selecting a bypass to optimize.",
                                                _node.Address));
            }
            _target_selector.ComputeCandidates(_node.Address, (int)Math.Ceiling(logk), CheckBypassCallback, null);
        }
Exemplo n.º 19
0
        /**
         * This is a recursive function over the network
         * It helps do a link-reliable procedure call on the
         * on the overlay network.
         */
        protected void RecursiveCall(IList margs, object req_state)
        {
            //first argument is the target node.
            AHAddress a = (AHAddress)AddressParser.Parse((string)margs[0]);

            /*
             * First find the Connection pointing to the node closest to dest, if
             * there is one closer than us
             */

            ConnectionTable tab          = _node.ConnectionTable;
            ConnectionList  structs      = tab.GetConnections(ConnectionType.Structured);
            Connection      next_closest = structs.GetNearestTo((AHAddress)_node.Address, a);

            //Okay, we have the next closest:
            if (next_closest != null)
            {
                Channel result = new Channel();
                //We only want one result, so close the queue after we get the first
                result.CloseAfterEnqueue();
                result.CloseEvent += delegate(object o, EventArgs args) {
                    Channel q = (Channel)o;
                    if (q.Count > 0)
                    {
                        try {
                            RpcResult rres = (RpcResult)q.Dequeue();
                            _rpc.SendResult(req_state, rres.Result);
                        }
                        catch (Exception x) {
                            string    m  = String.Format("<node>{0}</node> trying <connection>{1}</connection> got <exception>{2}</exception>", _node.Address, next_closest, x);
                            Exception nx = new Exception(m);
                            _rpc.SendResult(req_state, nx);
                        }
                    }
                    else
                    {
                        //We got no results.
                        _rpc.SendResult(req_state, null);
                    }
                };
                object [] new_args = new object[margs.Count];
                margs.CopyTo(new_args, 0);
                _rpc.Invoke(next_closest.State.Edge, result, "trace.RecursiveCall", new_args);
            }
            else
            {
                //We are the end of the line, send the result:
                //Console.Error.WriteLine("Doing a local invocation");
                Channel result = new Channel();
                result.CloseAfterEnqueue();
                result.CloseEvent += delegate(object o, EventArgs args) {
                    Channel q = (Channel)o;
                    if (q.Count > 0)
                    {
                        try {
                            //Console.Error.WriteLine("Got result.");
                            RpcResult rres = (RpcResult)q.Dequeue();
                            _rpc.SendResult(req_state, rres.Result);
                        }
                        catch (Exception x) {
                            string    m  = String.Format("<node>{0}</node> local invocation got <exception>{1}</exception>", _node.Address, x);
                            Exception nx = new Exception(m);
                            _rpc.SendResult(req_state, nx);
                        }
                    }
                    else
                    {
                        //We got no results.
                        _rpc.SendResult(req_state, null);
                    }
                };

                string    method_name = (string)margs[1];
                object [] new_args    = new object[margs.Count - 2];
                margs.RemoveAt(0); //extract destination address
                margs.RemoveAt(0); //extract method name
                margs.CopyTo(new_args, 0);
                //Console.Error.WriteLine("Calling method: {0}, args_count: {1}", method_name, new_args.Length);
                //for (int i = 0; i < new_args.Length; i++) {
                //Console.Error.WriteLine(new_args[i]);
                //}
                _rpc.Invoke(_node, result, method_name, new_args);
            }
        }
Exemplo n.º 20
0
        public List <ObjectNode> Parse(string source)
        {
            var bestVariant = new List <ObjectNode>();

            foreach (Variant variant in parser.Parse(source))
            {
                List <ObjectNode> lastFindedNodes = null;

                foreach (var versionObj in variant)
                {
                    if (versionObj.Type?.Level == 9)
                    {
                        var roomNodes = GetRoomsGUIDVariants(versionObj, lastFindedNodes);
                        if (roomNodes.Count > 0)
                        {
                            lastFindedNodes = roomNodes;
                        }
                    }
                    else if (versionObj.Type?.Level == 8)
                    {
                        var houseNodes = GetHousesGUIDVariants(versionObj, lastFindedNodes);
                        if (houseNodes.Count > 0)
                        {
                            lastFindedNodes = houseNodes;
                        }
                    }
                    else
                    {
                        var f = IterateAddressObject(versionObj, lastFindedNodes);
                        if (f.Count > 0)
                        {
                            lastFindedNodes = f;
                        }
                        else
                        {
                            break;
                        }
                    }
                }


                if (lastFindedNodes?.Count > 0)
                {
                    if (bestVariant.Count == 0)
                    {
                        bestVariant = lastFindedNodes;
                    }
                    else
                    {
                        if (lastFindedNodes[0].Type > bestVariant[0].Type)
                        {
                            bestVariant = lastFindedNodes;
                        }
                        else if ((lastFindedNodes[0].Type == bestVariant[0].Type) && (lastFindedNodes.Count < bestVariant.Count))
                        {
                            bestVariant = lastFindedNodes;
                        }
                    }
                }
                var lastObject = variant.GetAddressObject(variant.GetCount() - 1);
                if (bestVariant.Count == 1 && bestVariant[0].Name.ToLower() == lastObject.Name.ToLower())
                {
                    return(bestVariant);
                }
            }
            return(bestVariant);
        }
Exemplo n.º 21
0
        /**
         * Generates tree for bounded broadcast. Algorithm works as follows:
         * The goal is to broadcast to all nodes in range [local_address, end).
         * Given a range [local_address, b), determine all connections that belong to this range.
         * Let the connections be b_1, b_2, ..... b_n.
         * To connection bi assign the range [b_i, b_{i+1}).
         * To the connection bn assign range [b_n, end).]
         */
        public override void GenerateTree(Channel q, MapReduceArgs mr_args)
        {
            object gen_arg   = mr_args.GenArg;
            string end_range = gen_arg as string;

            Log("generating child tree, range end: {0}.", end_range);
            AHAddress end_addr   = (AHAddress)AddressParser.Parse(end_range);
            AHAddress start_addr = _node.Address as AHAddress;
            //we are at the start node, here we go:
            ConnectionTable tab     = _node.ConnectionTable;
            ConnectionList  structs = tab.GetConnections(ConnectionType.Structured);
            ArrayList       retval  = new ArrayList();

            if (structs.Count > 0)
            {
                Connection curr_con = structs.GetLeftNeighborOf(_node.Address);
                int        curr_idx = structs.IndexOf(curr_con.Address);
                //keep going until we leave the range
                int       count    = 0;
                ArrayList con_list = new ArrayList();
                while (count++ < structs.Count && ((AHAddress)curr_con.Address).IsBetweenFromLeft(start_addr, end_addr))
                {
                    con_list.Add(curr_con);
                    //Log("adding connection: {0} to list.", curr_con.Address);
                    curr_idx = (curr_idx + 1) % structs.Count;
                    curr_con = structs[curr_idx];
                }

                Log("{0}: {1}, number of child connections: {2}",
                    this.TaskName, _node.Address, con_list.Count);
                for (int i = 0; i < con_list.Count; i++)
                {
                    MapReduceInfo mr_info = null;
                    ISender       sender  = null;
                    Connection    con     = (Connection)con_list[i];
                    sender = (ISender)con.Edge;
                    //check if last connection
                    if (i == con_list.Count - 1)
                    {
                        mr_info = new MapReduceInfo((ISender)sender,
                                                    new MapReduceArgs(this.TaskName,
                                                                      mr_args.MapArg,   //map argument
                                                                      end_range,        //generate argument
                                                                      mr_args.ReduceArg //reduce argument
                                                                      ));

                        Log("{0}: {1}, adding address: {2} to sender list, range end: {3}",
                            this.TaskName, _node.Address,
                            con.Address, end_range);
                        retval.Add(mr_info);
                    }
                    else
                    {
                        string child_end = ((Connection)con_list[i + 1]).Address.ToString();
                        mr_info = new MapReduceInfo(sender,
                                                    new MapReduceArgs(this.TaskName,
                                                                      mr_args.MapArg,
                                                                      child_end,
                                                                      mr_args.ReduceArg));
                        Log("{0}: {1}, adding address: {2} to sender list, range end: {3}",
                            this.TaskName, _node.Address,
                            con.Address, child_end);
                        retval.Add(mr_info);
                    }
                }
            }
            q.Enqueue(retval.ToArray(typeof(MapReduceInfo)));
        }
Exemplo n.º 22
0
        public void Unblock(string address)
        {
            SocialUser user = _friends[address];

            _marad.AddIPMapping(user.IP, AddressParser.Parse(address));
        }
Exemplo n.º 23
0
        /**
         * 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);
            }
        }
Exemplo n.º 24
0
    public static int Main(string[] args)
    {
        /**
         * Get the arguments
         */
        if (args.Length < 2)
        {
            Console.Error.WriteLine("usage: SNodeExample.exe [tcp|udp] port remota_ta0 remote_ta1 ...");
            return(0);
        }

        /**
         * Make the edge listener:
         */
        EdgeListener el   = null;
        int          port = Int32.Parse(args[1]);

        if (args[0].ToLower() == "tcp")
        {
            el = new TcpEdgeListener(port);
        }
        else if (args[0].ToLower() == "udp")
        {
            el = new UdpEdgeListener(port);
        }

        /**
         * Create a random address for our node.
         * Some other application might want to select the address
         * a particular way, or reuse a previously selected random
         * address.  If the addresses are not random (or the output
         * of secure hashes) the network might not behave correctly.
         */
        RandomNumberGenerator rng     = new RNGCryptoServiceProvider();
        AHAddress             tmp_add = new AHAddress(rng);

        Console.WriteLine("Address: {0}", tmp_add);

        /**
         * Make the node that lives in a particular
         * using Brunet.Messaging;
         * namespace (or realm) called "testspace"
         */
        Node          tmp_node = new StructuredNode(tmp_add, "testspace");
        ReqrepManager rrman    = tmp_node.Rrm;
        ReqrepExample irh      = new ReqrepExample();

        tmp_node.GetTypeSource(PType.Protocol.Chat).Subscribe(irh, tmp_node);

        /**
         * Add the EdgeListener
         */
        tmp_node.AddEdgeListener(el);

        /**
         * Tell the node who it can connect to:
         */
        for (int i = 2; i < args.Length; i++)
        {
            tmp_node.RemoteTAs.Add(TransportAddressFactory.CreateInstance(args[i]));
        }

        /**
         * Now we connect
         */
        tmp_node.Connect();
        Console.WriteLine("Connected");

        /**
         * In a real application, we would create some IAHPacketHandler
         * objects and do:
         * tmp_node.Subscribe( )
         * finally, we could send packets using tmp_node.Send( ) or
         * tmp_node.SendTo( )
         */
        string msg = "";

        System.Text.Encoding coder = new System.Text.ASCIIEncoding();
        while (true)
        {
            Console.Write("To: ");
            msg = Console.ReadLine();
            if (msg == "q")
            {
                break;
            }
            Address dest = AddressParser.Parse(msg);
            while (msg != ".")
            {
                msg = Console.ReadLine();
                int    length  = coder.GetByteCount(msg);
                byte[] payload = new byte[length];
                coder.GetBytes(msg, 0, msg.Length, payload, 0);
                ISender sender = new AHSender(tmp_node, dest);
                rrman.SendRequest(sender, ReqrepManager.ReqrepType.Request,
                                  new CopyList(PType.Protocol.Chat, MemBlock.Reference(payload)),
                                  irh, null);
            }
        }

        return(1);
    }
Exemplo n.º 25
0
 public bool IsAllowed(string address)
 {
     return(_marad.mcast_addr.Contains(AddressParser.Parse(address)));
 }
Exemplo n.º 26
0
 public void AddressParserValidation(string input, Address output)
 {
     Assert.Equal(output, AddressParser.Parse(input), new AddressComparer());
 }
Exemplo n.º 27
0
        /// <summary>Process a new results and determine whether or not to execute
        /// more tests on this node and the neighbors it returned.</summary>
        protected void ProcessResults(Address addr, RpcResult result)
        {
            ResultState rs = null;

            lock (_sync) {
                rs = _results[addr];
            }

            if (result == null || result.Statistics.SendCount != 1)
            {
                rs.RTTs[rs.CurrentAttempt] = TimeSpan.MinValue;
                rs.Hops[rs.CurrentAttempt] = -1;
            }
            else
            {
                rs.RTTs[rs.CurrentAttempt] = DateTime.UtcNow - rs.StartTime;
                rs.Hops[rs.CurrentAttempt] = (result.ResultSender as AHSender).HopsTaken;
            }

            rs.CurrentAttempt++;

            List <ResultState> to_invoke = new List <ResultState>();
            bool finished = false;

            Hashtable data = null;

            if (result != null)
            {
                data = result.Result as Hashtable;
            }

            lock (_sync) {
                if (rs.CurrentAttempt == 3)
                {
                    _outstanding.Remove(addr);
                }
                else
                {
                    to_invoke.Add(rs);
                }
                if (data != null)
                {
                    foreach (string peer in data.Values)
                    {
                        Address peer_addr = AddressParser.Parse(peer);
                        if (_results.ContainsKey(peer_addr))
                        {
                            continue;
                        }
                        ResultState nrs = new ResultState(peer_addr);
                        to_invoke.Add(nrs);
                        _results[peer_addr]     = nrs;
                        _outstanding[peer_addr] = true;
                    }
                }
                if (_outstanding.Count == 0)
                {
                    finished = true;
                }
            }

            if (finished)
            {
                ThreadPool.QueueUserWorkItem(delegate(object o) { Finished(); });
            }

            foreach (ResultState nrs in to_invoke)
            {
                nrs.StartTime = DateTime.UtcNow;
                Invoke(nrs.Target);
            }
        }
Exemplo n.º 28
0
 public void SimpleUsageTest()
 {
     var address    = "426011, Удмуртская Республика, г. Ижевск, 10 Лет Октября,17 а, номера помещений на поэтажном плане 122-137";
     var parser     = new AddressParser();
     var normalized = parser.Parse(address);
 }
Exemplo n.º 29
0
        /// <summary>Creates an ApplicationNode and prepares it for connection to
        /// the overlay.  For historical reasons it is linked to _node, _dht,
        /// _rpc_dht, and _bso.</summary>
        public virtual ApplicationNode CreateNode(NodeConfig node_config)
        {
            // Get a Node ID for the new Node
            AHAddress address = null;

            try {
                address = (AHAddress)AddressParser.Parse(node_config.NodeAddress);
            } catch {
                address = Utils.GenerateAHAddress();
            }

            // Create the Node state
            StructuredNode node = new StructuredNode(address, node_config.BrunetNamespace);

            _shutdown.OnExit += node.Disconnect;
            IEnumerable addresses = IPAddresses.GetIPAddresses(node_config.DevicesToBind);

            SecurityOverlord so = null;

            // Enable Security if requested
            if (node_config.Security.Enabled)
            {
                if (node_config.Security.SelfSignedCertificates)
                {
                    SecurityPolicy.SetDefaultSecurityPolicy(SecurityPolicy.DefaultEncryptor,
                                                            SecurityPolicy.DefaultAuthenticator, true);
                }

                byte[] blob = null;
                using (FileStream fs = File.Open(node_config.Security.KeyPath, FileMode.Open)) {
                    blob = new byte[fs.Length];
                    fs.Read(blob, 0, blob.Length);
                }

                RSACryptoServiceProvider rsa_private = new RSACryptoServiceProvider();
                rsa_private.ImportCspBlob(blob);

                CertificateHandler ch = null;
                if (node_config.Security.Dtls)
                {
                    ch = new OpenSslCertificateHandler(node_config.Security.CertificatePath,
                                                       address.ToString());
                }
                else
                {
                    ch = new CertificateHandler(node_config.Security.CertificatePath,
                                                address.ToString());
                }


                if (node_config.Security.SecureEdges)
                {
                    node.EdgeVerifyMethod = EdgeVerify.AddressInSubjectAltName;
                }

                // A hack to enable a test for security that doesn't require each peer
                // to exchange certificates
                if (node_config.Security.TestEnable)
                {
                    blob = rsa_private.ExportCspBlob(false);
                    RSACryptoServiceProvider rsa_pub = new RSACryptoServiceProvider();
                    rsa_pub.ImportCspBlob(blob);
                    CertificateMaker cm = new CertificateMaker("United States", "UFL",
                                                               "ACIS", "David Wolinsky", "*****@*****.**", rsa_pub,
                                                               "brunet:node:abcdefghijklmnopqrs");
                    Certificate cacert = cm.Sign(cm, rsa_private);

                    cm = new CertificateMaker("United States", "UFL",
                                              "ACIS", "David Wolinsky", "*****@*****.**", rsa_pub,
                                              address.ToString());
                    Certificate cert = cm.Sign(cacert, rsa_private);
                    ch.AddCACertificate(cacert.X509);
                    ch.AddSignedCertificate(cert.X509);
                }

                if (node_config.Security.Dtls)
                {
                    OpenSslCertificateHandler ssl_ch = ch as OpenSslCertificateHandler;
                    so = new DtlsOverlord(rsa_private, ssl_ch, new PType(20));
                    node.GetTypeSource(new PType(20)).Subscribe(so, null);
                }
                else
                {
                    so = new SymphonySecurityOverlord(node, rsa_private, ch, node.Rrm);
                    node.GetTypeSource(PeerSecOverlord.Security).Subscribe(so, null);
                }
                so.Subscribe(node, null);
            }

            // Add Dht
            new TableServer(node);
            IDht        dht       = new Dht(node, 3, 20);
            RpcDhtProxy dht_proxy = new RpcDhtProxy(dht, node);

            // Setup Vivaldi if requested
            IRelayOverlap ito       = null;
            NCService     ncservice = null;

            if (node_config.NCService.Enabled)
            {
                ncservice = new NCService(node, node_config.NCService.Checkpoint);

                if (node_config.NCService.OptimizeShortcuts)
                {
                    node.Ssco.TargetSelector = new VivaldiTargetSelector(node, ncservice);
                }
                ito = new NCRelayOverlap(ncservice);
            }
            else
            {
                ito = new SimpleRelayOverlap();
            }

            // Create the ApplicationNode
            ApplicationNode app_node = new ApplicationNode(node, dht, dht_proxy, ncservice, so);

            // Add Edge listeners
            EdgeListener el = null;

            foreach (NodeConfig.EdgeListener item in node_config.EdgeListeners)
            {
                el = CreateEdgeListener(item, app_node, addresses);
                if (node_config.Security.SecureEdgesEnabled)
                {
                    el = new SecureEdgeListener(el, so);
                }
                node.AddEdgeListener(el);
            }

            // Create the tunnel and potentially wrap it in a SecureEL
            el = new Relay.RelayEdgeListener(node, ito);
            if (node_config.Security.SecureEdgesEnabled)
            {
                el = new SecureEdgeListener(el, so);
            }
            node.AddEdgeListener(el);

            List <TransportAddress> RemoteTAs = null;

            if (node_config.RemoteTAs != null)
            {
                RemoteTAs = new List <TransportAddress>();
                foreach (String ta in node_config.RemoteTAs)
                {
                    RemoteTAs.Add(TransportAddressFactory.CreateInstance(ta));
                }
                node.RemoteTAs = RemoteTAs;
            }

            // Add XmlRpc
            if (node_config.XmlRpcManager.Enabled)
            {
                if (_xrm == null)
                {
                    _xrm = new XmlRpcManagerServer(node_config.XmlRpcManager.Port);
                }
                _xrm.Add(node, GetXmlRpcUri(app_node));
                new RpcDht(dht, node);
            }

            if (node_config.PrivateNodeConfig != null &&
                node_config.PrivateNodeConfig.Enabled)
            {
                CreatePrivateNode(app_node, NodeConfig.GetPrivateNodeConfig(node_config));
            }
            return(app_node);
        }