Exemplo n.º 1
0
 /**
  * Add friend by retreiving certificate from DHT.
  * @param key the DHT key for friend's certificate.
  * @param access determines to give user network access.
  */
 public void AddDhtFriend(string key, bool access)
 {
     if(key != _local_user.DhtKey && !_friends.ContainsKey(key) &&
      key.Length >= 45 ) {
     ProtocolLog.WriteIf(SocialLog.SVPNLog,
                     String.Format("ADD DHT FETCH: {0} {1}",
                     DateTime.Now.TimeOfDay, key));
     Channel q = new Channel();
     q.CloseAfterEnqueue();
     q.CloseEvent += delegate(Object o, EventArgs eargs) {
       try {
     Hashtable result = (Hashtable) q.Dequeue();
     byte[] certData = (byte[]) result["value"];
     string tmp_key = SocialUtils.GetHashString(certData);
     tmp_key = SocialUser.DHTPREFIX + tmp_key;
     if(key == tmp_key) {
       ProtocolLog.WriteIf(SocialLog.SVPNLog,
                           String.Format("ADD DHT SUCCESS: {0} {1}",
                           DateTime.Now.TimeOfDay, key));
       if(access) {
         _queue.Enqueue(new QueueItem(
                        QueueItem.Actions.AddCertTrue, certData));
       }
       else {
         _queue.Enqueue(new QueueItem(
                        QueueItem.Actions.AddCertFalse, certData));
       }
     }
       } catch (Exception e) {
     ProtocolLog.WriteIf(SocialLog.SVPNLog,e.Message);
     ProtocolLog.WriteIf(SocialLog.SVPNLog,
                         String.Format("ADD DHT FAILURE: {0} {1}",
                         DateTime.Now.TimeOfDay, key));
       }
     };
     byte[] key_bytes = Encoding.UTF8.GetBytes(key);
     MemBlock keyb = MemBlock.Reference(key_bytes);
     this.Dht.AsyncGet(keyb, q);
       }
 }
Exemplo n.º 2
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 valueb = 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) {
            _cert_published = true;
            ProtocolLog.WriteIf(SocialLog.SVPNLog,
                                String.Format("PUBLISH CERT SUCCESS: {0} {1}",
                                DateTime.Now.TimeOfDay, _local_user.DhtKey));
              }
            } catch (Exception e) {
              ProtocolLog.WriteIf(SocialLog.SVPNLog,e.Message);
              ProtocolLog.WriteIf(SocialLog.SVPNLog,
                              String.Format("PUBLISH CERT FAILURE: {0} {1}",
                              DateTime.Now.TimeOfDay, _local_user.DhtKey));
            }
              };
              this.Dht.AsyncPut(keyb, valueb, DHTTTL, q);
        }
Exemplo n.º 3
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);
 }
Exemplo n.º 4
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);
        }
Exemplo n.º 5
0
 public void Test() {
   Channel q = new Channel(1);
   rpc.Invoke(null, q, "test.test");
   RpcResult res = (RpcResult) q.Dequeue();
   bool val = (bool) res.Result;
   Assert.IsTrue(val, "Reflection Test");
 }
Exemplo n.º 6
0
    public void HandleRpc(ISender caller, string method, IList args, object rs) {
      if(LocalUseOnly) {
        try {
          ReqrepManager.ReplyState _rs = (ReqrepManager.ReplyState) caller;
          Node node = (Node) _rs.ReturnPath;
          if(node != _node) {
            throw new Exception();
          }
        } catch {
          AdrException e = new AdrException(-32602, new Exception("Must send from local node!"));
          _node.Rpc.SendResult(rs, e);
          return;
        }
      }

      object result = null;
      try {
        switch(method) {
          case "Create":
          {
            // Needs to be Async so we don't deadlock!
            MemBlock key = MemBlock.Reference((byte[]) args[0]);
            MemBlock value = MemBlock.Reference((byte[]) args[1]);
            int ttl = (int) args[2];
            Channel returns = new Channel(1);
            returns.CloseEvent += delegate(object o, EventArgs eargs) {
              _node.Rpc.SendResult(rs, returns.Dequeue());
            };
            _dht.AsyncCreate(key, value, ttl, returns);
            return;
          }
          case "Put":
          {
            // Needs to be Async so we don't deadlock!
            MemBlock key = MemBlock.Reference((byte[]) args[0]);
            MemBlock value = MemBlock.Reference((byte[]) args[1]);
            int ttl = (int) args[2];
            Channel returns = new Channel(1);
            returns.CloseEvent += delegate(object o, EventArgs eargs) {
              _node.Rpc.SendResult(rs, returns.Dequeue());
            };
            _dht.AsyncPut(key, value, ttl, returns);
            return;
          }
          case "Get":
          {
            // Needs to be Async so we don't deadlock!
            MemBlock key = MemBlock.Reference((byte[]) args[0]);
            Channel returns = new Channel(1);
            returns.CloseEvent += delegate(object o, EventArgs eargs) {
              Hashtable []results = new Hashtable[returns.Count];
              int pos = 0;
              while(returns.Count > 0) {
                results[pos++] = (Hashtable) returns.Dequeue();
              }
              _node.Rpc.SendResult(rs, results);
            };
            _dht.AsyncGet(key, returns);
            return;
          }
          case "BeginGet":
          {
            MemBlock key = MemBlock.Reference((byte[]) args[0]);
            result = BeginGet(key);
            break;
          }
          case "ContinueGet":
          {
            MemBlock token = MemBlock.Reference((byte[]) args[0]);
            result = ContinueGet(token);
            break;
          }
          case "EndGet":
          {
            MemBlock token = MemBlock.Reference((byte[]) args[0]);
            EndGet(token);
            result = true;
            break;
          }
        }
      } catch (Exception e) {
        result = new AdrException(-32602, e);
      }
      _node.Rpc.SendResult(rs, result);
    }
Exemplo n.º 7
0
        /**
         * Makes the ping request to a friend.
         * @param address the address of the friend.
         * @param dhtKey the friend's dhtkey.
         */
        protected void FriendSearch(string address, string dhtKey, 
      string query)
        {
            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;
              UpdateDnsMapping(dhtKey, result);
              ProtocolLog.WriteIf(SocialLog.SVPNLog,
                          String.Format("SEARCH FRIEND REPLY: {0} {1} {2} {3}",
                          DateTime.Now.TimeOfDay, dhtKey, address, result));
            } catch(Exception e) {
              _friends[dhtKey].Time = SocialUser.TIMEDEFAULT;
              ProtocolLog.WriteIf(SocialLog.SVPNLog, e.Message);
              ProtocolLog.WriteIf(SocialLog.SVPNLog,
                             String.Format("SEARCH FRIEND FAILURE: {0} {1} {2}",
                             DateTime.Now.TimeOfDay, dhtKey, address));
            }
              };
              ProtocolLog.WriteIf(SocialLog.SVPNLog,
                          String.Format("SEARCH FRIEND REQUEST: {0} {1} {2}",
                          DateTime.Now.TimeOfDay, dhtKey, address));

              ISender sender = new AHExactSender(_node, addr);
              _rpc.Invoke(sender, q, "SocialVPN.GetDnsMapping", _local_user.DhtKey,
                  query);
        }
Exemplo n.º 8
0
  /**
   * Send and request latest presence info for this Buddy:
   */
  public void SendPresence() {
    XmlSerializer ser = new XmlSerializer(typeof(Brunet.Chat.Presence));
    System.IO.StringWriter sw = new System.IO.StringWriter();
    XmlWriter w = new XmlTextWriter(sw);
    Brunet.Chat.Presence p = new Brunet.Chat.Presence();
    p.Show = User.Show;
    if( p.Show == Brunet.Chat.Presence.TypeValues.Unavailable ) {
      p.PresType = Brunet.Chat.Presence.TypeValues.Unavailable;
    }
    p.Status = User.Status;
    ser.Serialize(w, p);
    //Wait for one result:
    Channel results = new Channel(1);
    results.CloseEvent += delegate(object q, System.EventArgs args) {
      try {
        RpcResult res = results.Dequeue() as RpcResult;
        string p_str = (string)res.Result;
        XmlReader r = new XmlTextReader(new System.IO.StringReader(p_str));
        XmlSerializer pser = new XmlSerializer(typeof(Brunet.Chat.Presence));

        this.Presence = (Brunet.Chat.Presence)pser.Deserialize(r);
      }
      catch {
        //I guess this buddy is offline:
        Status = Brunet.Chat.Presence.TypeValues.Unavailable;
      }
    };
    _node.Rpc.Invoke(Sender, results, "example:chat.presence", sw.ToString());
  }
Exemplo n.º 9
0
    static void Ping(IList nodes) {
      Random my_r = new Random();
      int idx0 = my_r.Next(0, nodes.Count);
      int idx1 = my_r.Next(0, nodes.Count);
      Node n0 = (Node)nodes[idx0];
      Node n1 = (Node)nodes[idx1];
      RpcManager pinger = RpcManager.GetInstance( n0 );
      Channel results = new Channel();
      results.EnqueueEvent += delegate(object q, EventArgs a) {
        object result = results.Dequeue();
	RpcResult r = (RpcResult)result;
	IDictionary data = (IDictionary)r.Result;
	Console.WriteLine("target: {0}, rtt: {1}", data["target"], data["musec"]);
      };
      Console.WriteLine("Pinging: {0} -> {1}", n0.Address, n1.Address);
      try {
        pinger.Invoke(n0, results, "trace.GetRttTo", n1.Address.ToString());
      }
      catch(Exception x) {
        Console.WriteLine("Exception: {0}", x);
      }
    }
Exemplo n.º 10
0
    static void TraceRoute(IList nodes) {
      Random my_r = new Random();
      int idx0 = my_r.Next(0, nodes.Count);
      int idx1 = my_r.Next(0, nodes.Count);
      Node n0 = (Node)nodes[idx0];
      Node n1 = (Node)nodes[idx1];
      RpcManager pinger = RpcManager.GetInstance( n0 );
      Channel results = new Channel();
      Console.WriteLine("Traceroute: {0} -> {1}", n0.Address, n1.Address);
      results.EnqueueEvent += delegate(object q, EventArgs a) {
        object result = results.Dequeue();
	RpcResult r = (RpcResult)result;
	IList data = (IList)r.Result;
	int hop = 0;
	foreach(IDictionary d in data) {
          Console.WriteLine("Hop: {0} :: {1}\n  :: {2}", hop, d["node"], d["next_con"]);
	  hop++;
	}
      };
      try {
        pinger.Invoke(n0, results, "trace.GetRouteTo", n1.Address.ToString());
      }
      catch(Exception x) {
        Console.WriteLine("Exception: {0}", x);
      }
    }
Exemplo n.º 11
0
 /**
  * Call the GetStatus method on the given connection
  */
 protected void CallGetStatus(string type, Connection c) {
   ConnectionTable tab = this.ConnectionTable;
   if( c != null ) {
     StatusMessage req = GetStatus(type, c.Address);
     Channel stat_res = new Channel(1);
     EventHandler handle_result = delegate(object q, EventArgs eargs) {
       try {
         RpcResult r = (RpcResult)stat_res.Dequeue();
         StatusMessage sm = new StatusMessage( (IDictionary)r.Result );
         tab.UpdateStatus(c, sm);
       }
       catch(Exception) {
         //Looks like lc disappeared before we could update it
       }
     };
     stat_res.CloseEvent += handle_result;
     RpcManager rpc = RpcManager.GetInstance(this);
     rpc.Invoke(c.Edge, stat_res, "sys:link.GetStatus", req.ToDictionary() );
   }
 }
Exemplo n.º 12
0
    /// <summary>First we try to find a third party we can connect with for
    /// overlap, if that is successful, we attempt to connect to him, if that
    /// is successful, we create a new tunnel edge.</summary>
    protected void AttemptToCreateOverlap(TunnelEdgeCallbackAction teca)
    {
      WaitCallback create_connection = delegate(object o) {
        Address target = o as Address;
        if(o == null) {
          FailedEdgeCreate(teca);
          return;
        }

        ConnectionList cons = _connections;
        int index = cons.IndexOf(target);
        if(index < 0) {
          FailedEdgeCreate(teca);
          return;
        }

        List<Connection> overlap = new List<Connection>(1);
        overlap.Add(cons[index]);
        CreateEdge(teca, overlap);
      };

      Channel chan = new Channel(1);
      chan.CloseEvent += delegate(object o, EventArgs ea) {
        Address target = null;
        try {
          IDictionary msg = (chan.Dequeue() as RpcResult).Result as IDictionary;
          target = _ito.EvaluatePotentialOverlap(msg);
        } catch {
        }

        if(target == null) {
          FailedEdgeCreate(teca);
        } else {
          _oco.ConnectTo(target, create_connection);
        }
      };

      ISender s = new AHExactSender(_node, teca.TunnelTA.Target);
      _node.Rpc.Invoke(s, chan, "tunnel.RequestSync");
    }
Exemplo n.º 13
0
    /// <summary>
    /// Asynchronous get address method, use when making asynchronous calls
    /// </summary>
    public void AsGetAddress()
    {
        Channel q = new Channel();
        q.CloseAfterEnqueue();

        // Delegate function gets called when close event occurs
        q.CloseEvent += delegate(Object o, EventArgs eargs) {
          RpcResult res = (RpcResult)q.Dequeue();
          Hashtable hash = (Hashtable)res.Result;
          Console.WriteLine(_remEP + ":" + ((UnicastSender)res.ResultSender).EndPoint);
          foreach (DictionaryEntry de in hash) {
        Console.WriteLine("{0} = {1}", de.Key, de.Value);
          }
        };
        _brpc.Rpc.Invoke(_brpc.IPHandler.CreateUnicastSender(_remEP), q, "sys:link.GetNeighbors");
    }
Exemplo n.º 14
0
    ///<summary> If half of ttl time passed, this event handler is called. AlarmEventHandler calls
    ///"DhtClient.Put" command to insert the entry to other nodes. It restarts the timer.
    /// If error occurs during ASyncPut, it retries after 30 seconds</summary>
    /// <param name="o">Entry which initiates ttl time expire event</param>
    public void EntryCallback(object o)
    {
      Entry entry = o as Entry;
      Channel returns = new Channel(1);
      returns.CloseEvent += delegate(object obj, EventArgs eargs) {
        bool success = false;
        try {
          object ret = returns.Dequeue();
          if(ret is Exception) {
            throw (ret as Exception);
          }
          success = (bool) ret;
        } catch(Exception e) {
          ProtocolLog.WriteIf(ProtocolLog.Exceptions, "EntryCallback: " + e);
          success = false;
        }

        if(success && !entry.Working) {
          entry.Timer.Stop();
          entry.Working = true;
          int time = entry.Ttl * 1000 / 2;
          entry.Timer = new SimpleTimer(EntryCallback, entry, time, time);
          entry.Timer.Start();
        } else if(!success && entry.Working) {
          entry.Timer.Stop();
          entry.Working = false;
          entry.Timer = new SimpleTimer(EntryCallback, entry, RETRY_TIMEOUT, RETRY_TIMEOUT);
          entry.Timer.Start();
        }
      };

      _dht.AsyncPut(entry.Key, entry.Value, entry.Ttl, returns);
    }
Exemplo n.º 15
0
    /**
    <summary>Called by a Dht client to store data here, this supports both Puts
    and Creates by using the unique parameter.</summary>
    <remarks>Puts will store the value no matter what, Creates will only store
    the value if they are the first ones to store data on that key.  This is
    the first part of a Put operation.  This calls PutHandler on itself and
    the neighbor nearest to the key, which actually places the data into the
    store.  The result is returned to the client upon completion of the call
    to the neighbor, if that fails the data is removed locally and an exception
    is sent to the client indicating failure.</remarks>
    <param name="key">The index to store the data at.</param>
    <param name="value">Data to store at the key.</param>
    <param name="ttl">Dht lease time in seconds</param>
    <param name="unique">True if this should perform a create, false otherwise.
    </param>
    <param name="rs">The return state sent back to the RpcManager so that it
    knows who to return the result to.</param>
    <returns>True on success, thrown exception on failure</returns>
    <exception cref="Exception">Data is too large, unresolved remote issues,
    or the create is no successful</exception>
    */

    public bool Put(MemBlock key, MemBlock value, int ttl, bool unique, object rs) {
      if(value.Length > MAX_BYTES) {
        throw new Exception(String.Format(
          "Dht only supports storing data smaller than {0} bytes.", MAX_BYTES));
      }
      PutHandler(key, value, ttl, unique);
      Channel remote_put = new Channel();
      remote_put.CloseAfterEnqueue();
      remote_put.CloseEvent += delegate(Object o, EventArgs eargs) {
        object result = false;
        try {
          result = remote_put.Dequeue();
          RpcResult rpcResult = (RpcResult) result;
          result = rpcResult.Result;
          if(result.GetType() != typeof(bool)) {
            throw new Exception("Incompatible return value.");
          }
          else if(!(bool) result) {
            throw new Exception("Unknown error!");
          }
        }
        catch (Exception e) {
          lock(_sync) {
            _data.RemoveEntry(key, value);
          }
          result = new AdrException(-32602, e);
        }
        _rpc.SendResult(rs, result);
      };

      try {
        Address key_address = new AHAddress(key);
        ISender s = null;
        // We need to forward this to the appropriate node!
        if(((AHAddress)_node.Address).IsLeftOf((AHAddress) key_address)) {
          Connection con = _node.ConnectionTable.GetRightStructuredNeighborOf((AHAddress) _node.Address);
          s = con.Edge;
        }
        else {
          Connection con = _node.ConnectionTable.GetLeftStructuredNeighborOf((AHAddress) _node.Address);
          s = con.Edge;
        }
        _rpc.Invoke(s, remote_put, "dht.PutHandler", key, value, ttl, unique);
      }
      catch (Exception) {
        lock(_sync) {
          _data.RemoveEntry(key, value);
        }
        throw;
      }
      return true;
    }