Esempio n. 1
0
        protected void FriendPing(string address)
        {
            Address addr = AddressParser.Parse(address);
            Channel q    = new Channel();

            q.CloseAfterEnqueue();
            q.CloseEvent += delegate(object obj, EventArgs eargs) {
                try {
                    RpcResult res      = (RpcResult)q.Dequeue();
                    string    result   = (string)res.Result;
                    string[]  parts    = result.Split(DELIM);
                    string    dht_key  = parts[0];
                    string    response = parts[1];
                    if (response == "online")
                    {
                        SocialUser friend = _friends[dht_key];
                        friend.Time = DateTime.Now.ToString();
                    }
                    ProtocolLog.Write(SocialLog.SVPNLog, "PING FRIEND REPLY: " +
                                      result);
                } catch (Exception e) {
                    ProtocolLog.Write(SocialLog.SVPNLog, e.Message);
                    ProtocolLog.Write(SocialLog.SVPNLog, "PING FRIEND FAILURE: " +
                                      address);
                }
            };
            ISender sender = new AHExactSender(_node, addr);

            _rpc.Invoke(sender, q, "SocialVPN.FriendPing", _local_user.DhtKey);
        }
Esempio n. 2
0
        protected void SendControlPacket(EndPoint end, int remoteid, int localid,
                                         ControlCode c, object state)
        {
            using (MemoryStream ms = new MemoryStream()) {
                NumberSerializer.WriteInt((int)c, ms);
                if (c == ControlCode.EdgeDataAnnounce)
                {
                    UdpEdge e = (UdpEdge)_id_ht[localid];
                    if ((e != null) && (e.RemoteID == remoteid))
                    {
                        Hashtable t = new Hashtable();
                        t["RemoteTA"] = e.RemoteTA.ToString();
                        t["LocalTA"]  = e.LocalTA.ToString();
                        AdrConverter.Serialize(t, ms);
                    }
                    else
                    {
                        if (ProtocolLog.UdpEdge.Enabled)
                        {
                            ProtocolLog.Write(ProtocolLog.UdpEdge, String.Format(
                                                  "Problem sending EdgeData: EndPoint: {0}, remoteid: {1}, " +
                                                  "localid: {2}, Edge: {3}", end, remoteid, localid, e));
                        }
                    }
                }

                _send_queue.Enqueue(new UdpMessage(localid, ~remoteid, MemBlock.Reference(ms.ToArray()), end));
                if (ProtocolLog.UdpEdge.Enabled)
                {
                    ProtocolLog.Write(ProtocolLog.UdpEdge, String.Format(
                                          "Sending control {1} to: {0}", end, c));
                }
            }
        }
Esempio n. 3
0
        /**
         * Add local certificate to the DHT.
         */
        public void PublishCertificate()
        {
            byte[]   key_bytes = Encoding.UTF8.GetBytes(_local_user.DhtKey);
            MemBlock keyb      = MemBlock.Reference(key_bytes);
            MemBlock value     = MemBlock.Reference(_local_cert.X509.RawData);

            Channel q = new Channel();

            q.CloseAfterEnqueue();
            q.CloseEvent += delegate(Object o, EventArgs eargs) {
                try {
                    bool success = (bool)(q.Dequeue());
                    if (success)
                    {
                        ProtocolLog.Write(SocialLog.SVPNLog, "PUBLISH CERT SUCCESS: " +
                                          _local_user.DhtKey);
                    }
                } catch (Exception e) {
                    ProtocolLog.Write(SocialLog.SVPNLog, e.Message);
                    ProtocolLog.Write(SocialLog.SVPNLog, "PUBLISH CERT FAILURE: " +
                                      _local_user.DhtKey);
                }
            };
            this.Dht.AsPut(keyb, value, DHTTTL, q);
        }
Esempio n. 4
0
 public override void Start()
 {
     //Make sure the Node is listening to this node
     try {
         //This will throw an exception if _e is already closed:
         _e.CloseEvent += this.CloseHandler;
         //_e must not be closed, let's start listening to it:
         _e.Subscribe(_node, _e);
         /* Make the call */
         Channel results = new Channel();
         results.CloseAfterEnqueue();
         results.CloseEvent += this.LinkCloseHandler;
         RpcManager rpc = _node.Rpc;
         if (ProtocolLog.LinkDebug.Enabled)
         {
             ProtocolLog.Write(ProtocolLog.LinkDebug,
                               String.Format("LPS target: {0} Invoking Start() over edge: {1}", _linker.Target, _e));
         }
         rpc.Invoke(_e, results, "sys:link.Start", MakeLM().ToDictionary());
     }
     catch (Exception e) {
         //The Edge must have closed, move on to the next TA
         if (ProtocolLog.LinkDebug.Enabled)
         {
             ProtocolLog.Write(ProtocolLog.LinkDebug,
                               String.Format("LPS target: {0} Start() over edge: {1}, hit exception: {2}",
                                             _linker.Target, _e, e));
         }
         Finish(Result.MoveToNextTA);
     }
 }
Esempio n. 5
0
        /**
         * Add friend by retreiving certificate from DHT.
         * @param key the DHT key for friend's certificate.
         */
        public void AddDhtFriend(string key)
        {
            if (key == _local_user.DhtKey || _friends.ContainsKey(key))
            {
                if (key != _local_user.DhtKey)
                {
                    _srh.PingFriend(_friends[key]);
                }
                return;
            }

            Channel q = new Channel();

            q.CloseAfterEnqueue();
            q.CloseEvent += delegate(Object o, EventArgs eargs) {
                try {
                    DhtGetResult dgr      = (DhtGetResult)q.Dequeue();
                    byte[]       certData = dgr.value;
                    AddCertificate(certData, key);
                    ProtocolLog.Write(SocialLog.SVPNLog, "ADD DHT SUCCESS: " +
                                      key);
                } catch (Exception e) {
                    ProtocolLog.Write(SocialLog.SVPNLog, e.Message);
                    ProtocolLog.Write(SocialLog.SVPNLog, "ADD DHT FAILURE: " +
                                      key);
                }
            };
            this.Dht.AsGet(key, q);
        }
Esempio n. 6
0
File: Dht.cs Progetto: pcbing/brunet
        /// <summary>This helps us leave the Get early if we either have no results or
        /// our remaining results will not reach a majority due to too many nodes
        /// missing data.  This closes the clients returns queue.</summary>
        /// <param name="adgs">The AsDhtGetState to qualify for leaving early</param>
        protected void GetLeaveEarly(AsDhtGetState adgs)
        {
            int left = adgs.queueMapping.Count;
            // Maybe we can leave early
            bool got_all_values = true;

            foreach (DictionaryEntry de in adgs.results)
            {
                int val = ((Hashtable)de.Value).Count;
                if (val < MAJORITY && ((val + left) >= MAJORITY))
                {
                    got_all_values = false;
                    break;
                }
            }

            // If we got to leave early, we must clean up
            if (got_all_values)
            {
                if (Dht.DhtLog.Enabled)
                {
                    ProtocolLog.Write(Dht.DhtLog, String.Format(
                                          "GetLeaveEarly found:left:total = {0}:{1}:{2}",
                                          adgs.results.Count, left, DEGREE));
                }
                adgs.returns.Close();
                adgs.GotToLeaveEarly = true;
            }
        }
Esempio n. 7
0
 public void Start()
 {
     try {
         //This edge could have been closed, which will
         //cause the Rpc to throw an exception
         Node.CallGetStatus(ConType, Neighbor);
     }
     catch (EdgeClosedException) {
         //Just ignore this connection if it is closed
     }
     catch (EdgeException ex) {
         if (!ex.IsTransient)
         {
             //Make sure this Edge is closed before going forward
             //@TODO this is not safe, EdgeException should keep a ref to the edge that threw
             Neighbor.State.Edge.Close();
         }
     }
     catch (Exception x) {
         if (ProtocolLog.Exceptions.Enabled)
         {
             ProtocolLog.Write(ProtocolLog.Exceptions, String.Format(
                                   "CallGetStatus() on {0} failed: {1}", Neighbor, x));
         }
     }
 }
Esempio n. 8
0
        /**
         * <summary>Disk caching is unsupported at this time.</summary>
         */
        /* When we have a cache eviction, we must write it to disk, we take
         * each entry, convert it explicitly into a hashtable, and then use adr
         * to create a stream and write it to disk
         */
        public void CacheEviction(Object o, EventArgs args)
        {
            Brunet.Collections.Cache.EvictionArgs eargs = (Brunet.Collections.Cache.EvictionArgs)args;
            MemBlock key = (MemBlock)eargs.Key;

            if (Dht.DhtLog.Enabled)
            {
                ProtocolLog.Write(Dht.DhtLog, String.Format(
                                      "Evicted out of cache {0}, entries in dht {1}, entries in cache {2}",
                                      (new BigInteger(key)).ToString(16), Count, _data.Count));
            }
            if (eargs.Value != null && ((LinkedList <Entry>)eargs.Value).Count > 0)
            {
                LinkedList <Entry> data = (LinkedList <Entry>)eargs.Value;
                // AdrConverter doesn't support LinkedLists
                Entry[] entries = new Entry[data.Count];
                data.CopyTo(entries, 0);
                Hashtable[] ht_entries = new Hashtable[entries.Length];
                int         index      = 0;
                foreach (Entry entry in entries)
                {
                    ht_entries[index++] = (Hashtable)entry;
                }

                string dir_path, filename;
                string file_path = GeneratePath(key, out dir_path, out filename);
                if (!Directory.Exists(dir_path))
                {
                    Directory.CreateDirectory(dir_path);
                }
                using (FileStream fs = File.Open(file_path, FileMode.Create)) {
                    AdrConverter.Serialize(ht_entries, fs);
                }
            }
        }
Esempio n. 9
0
        /**
         * Disconnect from the network.
         */
        public void Disconnect()
        {
            if (ProtocolLog.NodeLog.Enabled)
            {
                ProtocolLog.Write(ProtocolLog.NodeLog, String.Format(
                                      "Called Node.Disconnect: {0}", this.Address));
            }
            bool changed_state = false;

            try {
                SetConState(Node.ConnectionState.Leaving, out changed_state);
                if (changed_state)
                {
                    ProtocolLog.WriteIf(ProtocolLog.NodeLog, String.Format(
                                            "[Connect: {0}] deactivating task queue", _local_add));
                    _task_queue.IsActive = false;
                    Interlocked.Exchange(ref _send_pings, 0);
                    _connection_table.Close();
                }
            }
            finally {
                if (changed_state)
                {
                    SendStateChange(Node.ConnectionState.Leaving);
                }
            }
        }
Esempio n. 10
0
        protected void SendThread()
        {
            byte[] buffer   = new byte[8 + Int16.MaxValue];
            bool   timedout = false;

            while (_running == 1)
            {
                UdpMessage to_send = _send_queue.Dequeue(-1, out timedout);
                if (to_send == null)
                {
                    break;
                }
                NumberSerializer.WriteInt(to_send.LocalID, buffer, 0);
                NumberSerializer.WriteInt(to_send.RemoteID, buffer, 4);

                try {
                    int length = to_send.Data.CopyTo(buffer, 8);
                    _s.SendTo(buffer, 8 + length, SocketFlags.None, to_send.Dst);
                } catch (SocketException x) {
                    if ((1 == _running) && ProtocolLog.UdpEdge.Enabled)
                    {
                        ProtocolLog.Write(ProtocolLog.UdpEdge, x.ToString());
                    }
                }
            }
        }
Esempio n. 11
0
        public List <string> GetFingerprints(string uid)
        {
            if (_online)
            {
                return(_provider.GetFingerprints(uid));
            }

            List <string> fingerprints = new List <string>();

            DhtGetResult[] dgrs = null;

            string key = DHTPREFIX + uid;

            try {
                dgrs = _dht.Get(key);
            } catch (Exception e) {
                ProtocolLog.Write(SocialLog.SVPNLog, e.Message);
                ProtocolLog.Write(SocialLog.SVPNLog, "DHT GET FPR FAILURE: " + key);
            }
            foreach (DhtGetResult dgr in dgrs)
            {
                fingerprints.Add(dgr.valueString);
            }
            return(fingerprints);
        }
Esempio n. 12
0
        public override void Reduce(Channel q, object reduce_arg,
                                    object current_result, RpcResult child_rpc)
        {
            bool    done         = false;
            ISender child_sender = child_rpc.ResultSender;
            //the following can throw an exception, will be handled by the framework
            object child_result = child_rpc.Result;


            //child result is a valid result
            if (current_result == null)
            {
                q.Enqueue(new Brunet.Collections.Pair <object, bool>(child_result, done));
                return;
            }


            ArrayList   retval   = current_result as ArrayList;
            IDictionary my_entry = (IDictionary)retval[0];

            my_entry["next_con"] = child_sender.ToUri();
            retval.AddRange((IList)child_result);

            if (LogEnabled)
            {
                ProtocolLog.Write(ProtocolLog.MapReduce,
                                  String.Format("{0}: {1}, reduce list count: {2}.", this.TaskName, _node.Address, retval.Count));
            }
            q.Enqueue(new Brunet.Collections.Pair <object, bool>(retval, done));
        }
Esempio n. 13
0
        /// <summary>Called by HandleIPOut if the current packet has a Multicast
        /// address in its destination field.  This sends the multicast packet
        /// to all members of the multicast group stored in the dht.</summary>
        /// <param name="ipp">The IP Packet destined for multicast.</param>
        /// <returns>This returns true since this is implemented.</returns>
        protected override bool HandleMulticast(IPPacket ipp)
        {
            if (!_ipop_config.EnableMulticast)
            {
                return(true);
            }

            WaitCallback wcb = delegate(object o) {
                Hashtable[] results = null;
                try {
                    results = AppNode.Dht.Get(Encoding.UTF8.GetBytes(_ipop_config.IpopNamespace + ".multicast.ipop"));
                } catch {
                    return;
                }
                foreach (Hashtable result in results)
                {
                    try {
                        AHAddress target = (AHAddress)AddressParser.Parse(Encoding.UTF8.GetString((byte[])result["value"]));
                        if (IpopLog.PacketLog.Enabled)
                        {
                            ProtocolLog.Write(IpopLog.PacketLog, String.Format(
                                                  "Brunet destination ID: {0}", target));
                        }
                        SendIP(target, ipp.Packet);
                    }
                    catch {}
                }
            };

            ThreadPool.QueueUserWorkItem(wcb, ipp);
            return(true);
        }
        /**
         * Checks if the shortcut connection is still optimal, and trims it if not optimal.
         * @param random_target random target pointing to the start of the range for connection candidates.
         * @param score_table candidate addresses sorted by scores.
         * @param sc_address address of the current connection.
         */
        protected void CheckShortcutCallback(Address random_target, SortedList score_table, Address sc_address)
        {
            if (LogEnabled)
            {
                ProtocolLog.Write(ProtocolLog.SCO,
                                  String.Format("SCO local: {0}, Checking shortcut optimality: {1}.",
                                                _node.Address, sc_address));
            }

            int max_rank = (int)Math.Ceiling(0.2 * score_table.Count);

            if (!IsConnectionOptimal(sc_address, score_table, max_rank))
            {
                Address min_target = (Address)score_table.GetByIndex(0);
                //find the connection and trim it.
                Connection to_trim = null;
                foreach (Connection c in _node.ConnectionTable.GetConnections(STRUC_SHORT))
                {
                    string token = c.PeerLinkMessage.Token;
                    if (token == null || token == String.Empty)
                    {
                        continue;
                    }

                    // First half of the token should be the connection initiator
                    string initiator_address = token.Substring(0, token.Length / 2);
                    if (initiator_address == _node.Address.ToString() && c.Address.Equals(sc_address))
                    {
                        to_trim = c;
                        break;
                    }
                }

                if (to_trim != null)
                {
                    if (LogEnabled)
                    {
                        ProtocolLog.Write(ProtocolLog.SCO,
                                          String.Format("SCO local: {0}, Trimming shortcut : {1}, min_target: {2}.",
                                                        _node.Address, to_trim.Address, min_target));
                    }
                    lock (_sync) {
                        double total_secs = (DateTime.UtcNow - to_trim.CreationTime).TotalSeconds;
                        _sum_con_lifetime += total_secs;
                        _trim_count++;
                    }
                    _node.GracefullyClose(to_trim.Edge);
                }
            }
            else
            {
                if (LogEnabled)
                {
                    ProtocolLog.Write(ProtocolLog.SCO,
                                      String.Format("SCO local: {0}, Shortcut is optimal: {1}.",
                                                    _node.Address, sc_address));
                }
            }
        }
Esempio n. 15
0
 protected void Log(string format_string, params object[] format_args)
 {
     if (LogEnabled)
     {
         string s = String.Format(format_string, format_args);
         ProtocolLog.Write(ProtocolLog.MapReduce,
                           String.Format("{0}: {1}, {2}", _node.Address, this.GetType(), s));
     }
 }
Esempio n. 16
0
 /**
  * This just echos back the object passed to it
  */
 public object Ping(object o, ISender edge)
 {
     if (ProtocolLog.LinkDebug.Enabled)
     {
         ProtocolLog.Write(ProtocolLog.LinkDebug, String.Format(
                               "{0} sys:link.Ping({1},{2})", _node.Address, o, edge));
     }
     return(o);
 }
Esempio n. 17
0
 private void PostEvent(Events.EventInfo eventInfo)
 {
     lock (_events)
     {
         _events.Enqueue(eventInfo);
         _eventReceived.Set();
     }
     ProtocolLog.Write(eventInfo);
 }
Esempio n. 18
0
    /**
    <summary>The _listen_threads method, reads from sockets and let's the node
    handle the incoming data.</summary>
    */
    protected void Listen() {
      if (Thread.CurrentThread.Name == null) {
        Thread.CurrentThread.Name = "iphandler_thread";
      }
      ArrayList sockets = new ArrayList();
      sockets.Add(_uc);
      if(_mc != null) {
        sockets.Add(_mc);
      }

      byte[] buffer =  new byte[Int16.MaxValue];
      DateTime last_debug = DateTime.UtcNow;
      TimeSpan debug_period = TimeSpan.FromSeconds(5);
      while(1 == _running) {
        if (ProtocolLog.Monitor.Enabled) {
          DateTime now = DateTime.UtcNow;
          if (now - last_debug > debug_period) {
            last_debug = now;
            ProtocolLog.Write(ProtocolLog.Monitor, String.Format("I am alive: {0}", now));
          }
        }
        try {
          ArrayList readers = (ArrayList) sockets.Clone();
          Socket.Select(readers, null, null, 10000000); //10 seconds
          foreach(Socket socket in readers) {
            EndPoint ep = new IPEndPoint(IPAddress.Any, 0);
            int rec_bytes = socket.ReceiveFrom(buffer, ref ep);
            Subscriber s = _sub;
            //s can't change once we've read it.
            if( s != null && rec_bytes > 0) {
              MemBlock packet = MemBlock.Copy(buffer, 0, rec_bytes);
              MemBlock cookie = packet.Slice(0, 4);
              if(cookie.Equals(MagicCookie)) {
                packet = packet.Slice(4);
                ISender sender = CreateUnicastSender(ep);
                s.Handle(packet, sender);
              }
            }
          }
        }
        catch(ObjectDisposedException odx) {
          //If we are no longer running, this is to be expected.
          if(1 == _running) {
          //If we are running print it out
            ProtocolLog.WriteIf(ProtocolLog.Exceptions, odx.ToString());
          }
          break;
        }
        catch(Exception x) {
          if(0 == _running) {
            ProtocolLog.WriteIf(ProtocolLog.Exceptions, x.ToString());
          }
        }
      }
    }
Esempio n. 19
0
            /**
             * Update the ReadSocks and ErrorSocks to see which sockets might be
             * ready for reading or need closing.
             */
            public void Select()
            {
                ReadSocks.Clear();
                ErrorSocks.Clear();
                WriteSocks.Clear();
                ReadSocks.AddRange(AllSockets);
                //Also listen for incoming connections:
                ReadSocks.Add(ListenSock);

                /*
                 * POB: I cannot find any documentation on what, other than
                 * out-of-band data, might be signaled with these.  As such
                 * I am commenting them out.  If we don't see a reason to put
                 * it back soon, please delete ErrorSocks from the code.
                 * 11/19/2008
                 * ErrorSocks.AddRange(AllSockets);
                 */
                //Here we do non-blocking connecting:
                WriteSocks.AddRange(_con_socks);
                //Here we add the sockets that are waiting to write:
                WriteSocks.AddRange(_socks_to_send);
                //An error signals that the connection failed
                ErrorSocks.AddRange(_con_socks);

                /*
                 * Now we are ready to do our select and we only act on local
                 * variables
                 */
                try {
                    //Socket.Select(ReadSocks, null, ErrorSocks, TIMEOUT_MS * 1000);
                    Socket.Select(ReadSocks, WriteSocks, ErrorSocks, TIMEOUT_MS * 1000);
                    //Socket.Select(ReadSocks, null, null, TIMEOUT_MS * 1000);
                }
                catch (System.ObjectDisposedException) {
                    /*
                     * This happens if one of the edges is closed while
                     * a select call is in progress.  This is not weird,
                     * just ignore it
                     */
                    ReadSocks.Clear();
                    ErrorSocks.Clear();
                    WriteSocks.Clear();
                }
                catch (Exception x) {
                    /*
                     * There could be an OS error, in principle.  If this
                     * happens, log it, and just sleep for the period of time
                     * we would have waited (to prevent us from spinning in
                     * this thread).
                     */
                    ProtocolLog.Write(ProtocolLog.Exceptions, x.ToString());
                    Thread.Sleep(TIMEOUT_MS);
                }
            }
Esempio n. 20
0
        /**
         * When we're here, we have the status message
         */
        protected void StatusCloseHandler(object q, EventArgs args)
        {
            try {
                Channel resq = (Channel)q;
                //If we got no result
                RpcResult     res = (RpcResult)resq.Dequeue();
                StatusMessage sm  = new StatusMessage((IDictionary)res.Result);
                if (_node.EdgeVerifyMethod != null)
                {
                    if (!_node.EdgeVerifyMethod(_node, _e, LinkMessageReply.Local.Address))
                    {
                        throw new Exception("Edge verification failed!");
                    }
                }

                Connection c = new Connection(_e, LinkMessageReply.Local.Address,
                                              _contype, sm, LinkMessageReply);
                _node.ConnectionTable.Add(c);
                _con.Value = c;
                Finish(Result.Success);
            }
            catch (InvalidOperationException) {
                /*
                 * This is unexpected.
                 */
                string message = String.Format(
                    "No StatusMessage returned from open({1}) Edge: {0}",
                    _e, !_e.IsClosed);
                if (ProtocolLog.LinkDebug.Enabled)
                {
                    ProtocolLog.Write(ProtocolLog.LinkDebug, message);
                }

                /*
                 * We got a link message from this guy, but not a status response,
                 * so let's try this TA again.
                 */
                Finish(Result.RetryThisTA);
            }
            catch (Exception x) {
                /*
                 * Clearly we got some response from this edge, but something
                 * unexpected happened.  Let's try it this edge again if we
                 * can
                 */
                if (ProtocolLog.LinkDebug.Enabled)
                {
                    ProtocolLog.Write(ProtocolLog.LinkDebug, String.Format(
                                          "LPS.StatusResultHandler Exception: {0}", x));
                }
                Finish(Result.RetryThisTA);
            }
        }
        /**
         * Checks if we have the optimal bypass connection, and trims the ones that are unnecessary.
         * @param start random target pointing to the start of the range for connection candidates.
         * @param score_table candidate addresses sorted by scores.
         * @param bp_address address of the current connection (nullable).
         */
        protected void CheckBypassCallback(Address start, SortedList score_table, Address bp_address)
        {
            if (ProtocolLog.SCO.Enabled)
            {
                ProtocolLog.Write(ProtocolLog.SCO,
                                  String.Format("SCO local: {0}, Checking bypass optimality.",
                                                _node.Address));
            }

            ArrayList bypass_cons = new ArrayList();

            foreach (Connection c in _node.ConnectionTable.GetConnections(STRUC_BYPASS))
            {
                string token = c.State.PeerLinkMessage.Token;
                if (token == null || token.Equals(_node.Address.ToString()))
                {
                    continue;
                }
                bypass_cons.Add(c);
            }

            int max_rank = bypass_cons.Count > 1 ? 0: (int)Math.Ceiling(0.2 * score_table.Count);

            foreach (Connection bp in bypass_cons)
            {
                if (!IsConnectionOptimal(bp.Address, score_table, max_rank))
                {
                    Address min_target = (Address)score_table.GetByIndex(0);
#if TRACE
                    if (ProtocolLog.SCO.Enabled)
                    {
                        ProtocolLog.Write(ProtocolLog.SCO,
                                          String.Format("SCO local: {0}, Trimming bypass : {1}, min_target: {2}.",
                                                        _node.Address, bp.Address, min_target));
                    }
#endif
                    lock (_sync) {
                        double total_secs = (DateTime.UtcNow - bp.CreationTime).TotalSeconds;
                        _sum_con_lifetime += total_secs;
                        _trim_count++;
                    }
                    bp.Close(_node.Rpc, String.Empty);
#if TRACE
                }
                else if (ProtocolLog.SCO.Enabled)
                {
                    ProtocolLog.Write(ProtocolLog.SCO,
                                      String.Format("SCO local: {0}, Bypass is optimal: {1}.",
                                                    _node.Address, bp));
#endif
                }
            }
        }
        /**
         * Initiates creation of a bypass connection.
         *
         */
        protected void CreateBypass()
        {
            if (LogEnabled)
            {
                ProtocolLog.Write(ProtocolLog.SCO,
                                  String.Format("SCO local: {0}, Selecting bypass to create.",
                                                _node.Address));
            }
            double logk = Math.Log((double)_node.NetworkSize, 2.0);

            _target_selector.ComputeCandidates(_node.Address, (int)Math.Ceiling(logk), CreateBypassCallback, null);
        }
Esempio n. 23
0
            public override void Start(SocketState ss)
            {
                DateTime now = DateTime.UtcNow;

                if (now - _last_debug > _debug_period)
                {
                    _last_debug = now;
                    ProtocolLog.Write(ProtocolLog.Monitor, String.Format("I am alive: {0}", now));
                }
                //Run ourselves again later.
                _q.Enqueue(this);
            }
Esempio n. 24
0
 /**
  * Timer event handler.
  * @param obj the default object.
  */
 public void TimerHandler(Object obj)
 {
     try {
         UpdateFriends();
         _snode.PublishCertificate();
         _timer_thread.Change(INTERVALTIME, INTERVALTIME);
     } catch (Exception e) {
         _timer_thread.Change(INTERVALTIME, INTERVALTIME);
         ProtocolLog.Write(SocialLog.SVPNLog, e.Message);
         ProtocolLog.Write(SocialLog.SVPNLog, "TIMER HANDLER FAILURE " +
                           DateTime.Now.ToString());
     }
 }
Esempio n. 25
0
 /// <summary>Sends the IP Packet to the specified target address.</summary>
 /// <param name="target"> the Brunet Address of the target</param>
 /// <param name="packet"> the data to send to the recepient</param>
 protected virtual void SendIP(Address target, MemBlock packet)
 {
     if (!_conn_handler.Send(target, packet))
     {
         if (IpopLog.PacketLog.Enabled)
         {
             IPPacket ipp = new IPPacket(packet);
             ProtocolLog.Write(IpopLog.PacketLog, String.Format(
                                   "No connection to destination (IP / P2P): {0} / {1}",
                                   ipp.SourceIP, target));
         }
     }
 }
Esempio n. 26
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)
                {
                    _verified_cache.Update(ip, addr);
                    _attempts.Remove(ip);
                }

                _queued.Remove(ip);
                _mapping.Remove(queue);
            }

            if (addr == null)
            {
                var handler = MissedMapping;
                if (handler != null)
                {
                    if (_incoming_cache.TryGetValue(ip, out addr))
                    {
                        handler(ips, addr);
                    }
                }
            }
        }
Esempio n. 27
0
        protected void ListenThread()
        {
            Thread.CurrentThread.Name = "udp_listen_thread";
            BufferAllocator ba        = new BufferAllocator(8 + Int16.MaxValue);
            EndPoint        end       = new IPEndPoint(IPAddress.Any, 0);
            int             rec_bytes = 0;

            MonitorLogSwitch();
            ProtocolLog.Monitor.SwitchedSetting += MonitorLogSwitch;

            while (1 == _running)
            {
                int max = ba.Capacity;
                try {
                    rec_bytes = _s.ReceiveFrom(ba.Buffer, ba.Offset, max,
                                               SocketFlags.None, ref end);
                } catch (SocketException x) {
                    if ((1 == _running) && ProtocolLog.UdpEdge.Enabled)
                    {
                        ProtocolLog.Write(ProtocolLog.UdpEdge, x.ToString());
                    }
                }

                if (rec_bytes < 8)
                {
                    continue;
                }

                int remoteid = NumberSerializer.ReadInt(ba.Buffer, ba.Offset);
                int localid  = NumberSerializer.ReadInt(ba.Buffer, ba.Offset + 4);

                MemBlock packet_buffer = MemBlock.Reference(ba.Buffer, ba.Offset + 8, rec_bytes - 8);
                ba.AdvanceBuffer(rec_bytes);

                if (localid < 0)
                {
                    // Negative ids are control messages
                    HandleControlPacket(remoteid, localid, packet_buffer, end);
                }
                else
                {
                    HandleDataPacket(remoteid, localid, packet_buffer, end, null);
                }
            }
            ProtocolLog.Monitor.SwitchedSetting -= MonitorLogSwitch;
            //Let everyone know we are out of the loop
            _listen_finished_event.Set();
            _s.Close();
            //Allow garbage collection
            _s = null;
        }
 protected void CreateBypassCallback(Address start, SortedList score_table, Address current)
 {
     if (score_table.Count > 0)
     {
         Address min_target = (Address)score_table.GetByIndex(0);
         if (LogEnabled)
         {
             ProtocolLog.Write(ProtocolLog.SCO,
                               String.Format("SCO local: {0}, Connecting (bypass) to min_target: {1}",
                                             _node.Address, min_target));
         }
         ConnectTo(min_target, STRUC_BYPASS);
     }
 }
Esempio n. 29
0
        /** Starts the computation. */
        public void Start()
        {
            //invoke map
            try {
                Channel map_res = new Channel(1);
                map_res.CloseEvent += this.MapHandler;
                if (LogEnabled)
                {
                    ProtocolLog.Write(ProtocolLog.MapReduce,
                                      String.Format("MapReduce: {0}, about to call Map", _node.Address));
                }
                _mr_task.Map(map_res, _mr_args.MapArg);
            }
            catch (Exception x) {
                //Simulate the above except with the Exception enqueued
                if (LogEnabled)
                {
                    ProtocolLog.Write(ProtocolLog.MapReduce,
                                      String.Format("MapReduce: {0}, Exception in Map: {1}", _node.Address, x));
                }
                HandleException(null, x);
            }
            if (_state.Done)
            {
                return;
            }

            /* Our local Map was not enough
             * to finish the computation, look
             * for children
             */
            try {
                Channel gentree_res = new Channel(1);
                gentree_res.CloseEvent += this.GenTreeHandler;
                if (LogEnabled)
                {
                    ProtocolLog.Write(ProtocolLog.MapReduce,
                                      String.Format("MapReduce: {0}, about to call GenerateTree", _node.Address));
                }
                _mr_task.GenerateTree(gentree_res, _mr_args);
            }
            catch (Exception x) {
                if (LogEnabled)
                {
                    ProtocolLog.Write(ProtocolLog.MapReduce,
                                      String.Format("MapReduce: {0}, Exception in GenerateTree: {1}", _node.Address, x));
                }
                HandleException(null, x);
            }
        }
        override public void Set(Address addr)
        {
            if (!_cache.Update(addr, true))
            {
                return;
            }

            if (ProtocolLog.PolicyBasedCO.Enabled)
            {
                ProtocolLog.Write(ProtocolLog.PolicyBasedCO, String.Format(
                                      "Set: {0} at {1}", addr, DateTime.UtcNow));
            }
            ConnectTo(addr);
        }