Exemple #1
21
 public void HandleData(MemBlock payload, ISender return_path, object state) {
   if(_sub != null) {
     MemBlock rest = null;
     PType.Parse(payload, out rest);
     _sub.Handle(rest, return_path);
   }
 }
        void ChangePassword(ISender sender, string password)
        {
            if (!Storage.IsAvailable)
                throw new CommandError("No permissions plugin or data plugin is attached");

            var player = sender as Player;
            if (player == null)
            {
                sender.SendMessage("This is a player command", G: 0, B: 0);
                return;
            }
            else if (!player.IsAuthenticated())
            {
                sender.SendMessage("You are not authenticated.", G: 0, B: 0);
                return;
            }
            else if (password == null || password.Trim().Length < MinPasswordLength)
            {
                sender.SendMessage("Please specify a password longer than 5 characters.", G: 0, B: 0);
                return;
            }

            var auth = player.GetAuthenticatedAs();

            if (Authentication.UpdatePlayer(auth, password))
            {
                sender.SendMessage("Your password is now updated.", R: 0, B: 0);
            }
            else
            {
                sender.SendMessage("Failed to update your password.", G: 0, B: 0);
            }
        }
Exemple #3
0
 public void HandleRpc(ISender caller, string method, IList arguments, object request_state)
 {
   object result = null;
   MemBlock key;
   MemBlock value;
   int ttl;
     
   try {
     switch(method) {
       case "Register": 
         key = MemBlock.Reference((byte[]) arguments[0]);
         value = MemBlock.Reference((byte[]) arguments[1]);
         ttl = (int) arguments[2];
         result = Register(key, value, ttl);
         break;
       case "Unregister":
         key = MemBlock.Reference((byte[]) arguments[0]);
         value = MemBlock.Reference((byte[]) arguments[1]);
         result = Unregister(key, value);
         break;
       case "ListEntries":
         result = ListEntries();
         break;
       default:
         throw new Exception("Invalid method");
     }
   }
   catch (Exception e) {
     result = new AdrException(-32602, e);
   }
   _rpc.SendResult(request_state, result);
 }
Exemple #4
0
        public static void SetPoint(Server server, ISender sender, ArgumentList args)
        {
            string param;
            Player player = server.GetPlayerByName(sender.Name);

            if (args.TryGetString(0, out param))
            {
                switch (param.ToUpper())
                {
                    case "LOBBY":
                        player.PluginData["lobby"] = true;
                        player.sendMessage("Hit a block where you want the lobby to be", Login.plugin.chatColor);
                        break;
                    case "VALIDATED":
                        player.PluginData["validated"] = true;
                        player.sendMessage("Hit a block where you want the validated point to be", Login.plugin.chatColor);
                        break;
                    default:
                        player.sendMessage("You must specify either lobby or validated", Login.plugin.chatColor);
                        break;
                }
            }
            else
                player.sendMessage("You must specify either lobby or validated", Login.plugin.chatColor);
        }
Exemple #5
0
        public static void TestPoint(Server server, ISender sender, ArgumentList args)
        {
            string param;
            Player player = server.GetPlayerByName(sender.Name);

            if (args.TryGetString(0, out param))
            {
                switch (param.ToUpper())
                {
                    case "LOBBY":
                        player.sendMessage("Teleporting to the lobby", Login.plugin.chatColor);
                        Login.plugin.TeleportPlayerToPoint(player, Login.LOBBY);
                        break;
                    case "VALIDATED":
                        player.sendMessage("Teleporting to the validated point", Login.plugin.chatColor);
                        Login.plugin.TeleportPlayerToPoint(player, Login.VALIDATED);
                        break;
                    default:
                        player.sendMessage("You must specify either lobby or validated", Login.plugin.chatColor);
                        break;
                }
            }
            else
                player.sendMessage("You must specify either lobby or validated", Login.plugin.chatColor);
        }
        /// <summary>
        /// Adds a player or ip (Exception) to the ban list.
        /// </summary>
        /// <param name="sender">Sending player</param>
        /// <param name="args">Arguments sent with command</param>
        public static void Ban(ISender sender, ArgumentList args)
        {
            Player banee;
            string playerName = null;

            if (args.TryGetOnlinePlayer(0, out banee))
            {
                playerName = banee.Name;
                banee.Kick("You have been banned from this Server.");
                Server.BanList.addException(NetPlay.slots[banee.whoAmi].
                        remoteAddress.Split(':')[0]);
            }
            else if(!args.TryGetString(0, out playerName))
            {
                throw new CommandError("A player or IP was expected.");
            }

            Server.BanList.addException(playerName);

            Server.notifyOps(playerName + " has been banned {" + sender.Name + "}", true);
            if (!Server.BanList.Save())
            {
                Server.notifyOps("BanList Failed to Save due to " + sender.Name + "'s command", true);
            }
        }
        /// <summary>
        /// De-OPs a given Player.
        /// </summary>
        /// <param name="sender">Sending player</param>
        /// <param name="args">Arguments sent with command</param>
        public static void DeopPlayer(ISender sender, ArgumentList args)
        {
            var playerName = args.GetString(0);
            Player player;
            if (args.TryGetOnlinePlayer(0, out player))
            {
                playerName = player.Name;

                if (Player.isInOpList(playerName))
                {
                    player.sendMessage("You have been De-Opped!.", ChatColor.Green);
                }

                player.Op = false;
                if (player.HasClientMod)
                {
                    NetMessage.SendData(Packet.CLIENT_MOD, player.whoAmi);
                }
            }

            if (Player.isInOpList(playerName))
            {
                Server.notifyOps("De-Opping " + playerName + " {" + sender.Name + "}", true);
                Server.OpList.removeException(playerName + ":" + Player.GetPlayerPassword(playerName));
            }

            if (!Server.OpList.Save())
            {
                Server.notifyOps("OpList Failed to Save due. {" + sender.Name + "}", true);
                return;
            }
        }
        public void PrivateMessageReply(ISender sender, string message)
        {
            var playerFrom = sender as Player;
            if (playerFrom == null)
            {
                sender.SendMessage("This is a player command.", G: 0, B: 0);
                return;
            }

            if (String.IsNullOrEmpty(message))
            {
                sender.SendMessage("Invalid message", G: 0, B: 0);
                return;
            }

            var lastPlayerName = playerFrom.GetPluginData("LastPM", String.Empty);
            if(String.IsNullOrEmpty(lastPlayerName))
            {
                sender.SendMessage("You are required to have started a conversation.", G: 0, B: 0);
                return;
            }

            var playerTo = Tools.GetPlayerByName(lastPlayerName);
            if(playerTo == null || !playerTo.active)
            {
                sender.SendMessage($"Last PM'd user ({lastPlayerName}) is no longer online.", G: 0, B: 0);
                return;
            }

            playerTo.Message(255, Color.Orange, $"[PM] {playerFrom.SenderName}: {message}");
        }
Exemple #9
0
    /// <summary>Create a DtlsFilter.</summary>
    /// <param name="key">A CryptoKey initialized by the OpenSSL.NET library.</param>
    /// <param name="cert">The path to the certificate to use.</param>
    /// <param name="ca_cert">The path to the ca certificate to use.</param>
    /// <param name="client">Use client initialization parameters.</param>
    public DtlsAssociation(ISender sender, CertificateHandler ch, PType ptype,
        Ssl ssl, bool client) : base(sender, ch)
    {
      _ip = new IdentifierPair();
      PType = ptype;
      _ssl = ssl;
      _client = client;
      _ssl.SetReadAhead(1);
      // Buggy SSL versions have issue with compression and dtls
      _ssl.SetOptions((int) SslOptions.SSL_OP_NO_COMPRESSION);
      if(client) {
        _ssl.SetConnectState();
      } else {
        _ssl.SetAcceptState();
      }

      // The ssl object will take control
      _read = BIO.MemoryBuffer(false);
      _read.NonBlocking = true;
      _write = BIO.MemoryBuffer(false);
      _write.NonBlocking = true;

      _ssl.SetBIO(_read, _write);
      _ssl.DoHandshake();

      _buffer = new byte[Int16.MaxValue];
      _buffer_sync = new object();
      _fe_lock = 0;
    }
        void AddAccount(ISender sender, ArgumentList args)
        {
            if (!Storage.IsAvailable)
                throw new CommandError("No permissions plugin or data plugin is attached");

            var a = 0;
            string name, pass;
            APIAccount acc = null;

            //api addaccount "username" "password"
            if (!args.TryGetString(a++, out name))
                throw new CommandError("Expected username after addaccount");

            if (!args.TryGetString(a++, out pass))
                throw new CommandError("Expected password after username");

            acc = APIAccountManager.FindByName(name);
            if (acc == null)
            {
                acc = APIAccountManager.Create(name, pass);
                if (acc.Id > 0)
                {
                    sender.SendMessage("Successfully created account.", R: 0, B: 0);
                }
                else
                {
                    sender.SendMessage("Failed to create account.", G: 0, B: 0);
                }
            }
            else
            {
                throw new CommandError("Existing API account found by " + name);
            }
        }
 // 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);
 }
Exemple #12
0
    public void HandleData(MemBlock packet, ISender from, object node)
    {
      _message_count++;

      long stop_time, rt_ticks = -10000;

      if ( !from.Equals(node)) {
        if (packet[0] == 0) {
        //log.Debug("Echo Response:");
	  stop_time = System.DateTime.Now.Ticks;
	  int received_uid = NumberSerializer.ReadInt(packet, 1);
          if(uid_starttime.ContainsKey(received_uid)){
		rt_ticks = stop_time - (long)EchoTester.uid_starttime[received_uid];
	  }
	  double rt_ms = (double) rt_ticks/10000.0;
	  uid_brunetpingtime.Add(received_uid, rt_ms);
	  Console.WriteLine("Packet ID = {0}, Round-trip = {1}", received_uid, rt_ms); 	  
        }
        else {
        //log.Debug("Echo Request:");
        }

        //log.Debug(packet.ToString());

        //System.Console.WriteLine("{0}", packet.ToString());

        if (packet[0] > 0) {
          //Send a reply back, this is a request  
	  byte[] new_payload = new byte[ packet.Length ];
	  packet.CopyTo(new_payload, 0);
          new_payload[0] = (byte) 0;
          from.Send(new CopyList(PType.Protocol.Echo, MemBlock.Reference(new_payload)));
        }
      }
    }
 public InstructionPacketSetID(byte servoId, byte newId, ISender sender)
     : base(servoId, sender)
 {
     _instruction = 0x03;
     _lengthOfCommand = 0x04;
     _parameters.AddRange(new[] { (byte)0x03, newId });
 }
        private void WhoAmI(ISender sender, string args)
        {
            var player = sender as Player;
            if (player != null)
            {
                var sb = new StringBuilder();
                sb.Append("You are ");
                if (!player.IsAuthenticated()) sb.Append("not ");

                if (player.Op) sb.Append("an operator");
                else sb.Append("logged in");

                var groupName = String.Empty;
                if (Storage.IsAvailable)
                {
                    var grp = Storage.GetInheritedGroup(player);
                    if (grp != null) groupName = grp.Name;
                }

                if (!String.IsNullOrEmpty(groupName))
                {
                    sb.Append(" and are a part of the ");
                    sb.Append(groupName);
                    sb.Append(" group");
                }
                else sb.Append(" but not apart of any groups");

                sb.Append(".");
                sender.Message(sb.ToString(), Color.Orange);
            }
            else sender.Message("This command is for players only", Color.Red);
        }
        /// <summary>
        /// Enables or disables NPC spawning
        /// </summary>
        /// <param name="sender">Sending player</param>
        /// <param name="args">Arguments sent with command</param>
        public void NPCSpawning(ISender sender, ArgumentList args)
        {
            args.ParseNone();

            Core.StopNPCSpawning = !Core.StopNPCSpawning;
            sender.Message("NPC spawning is now " + (Core.StopNPCSpawning ? "off" : "on") + "!");
        }
 public static void ExampleCommand(ISender sender, ArgumentList args)
 {
     TDSM_Plugin MyPlugin = (TDSM_Plugin)args.Plugin; //Get the plugin object who's assigned to the "tdsmpluginexample"
     int arg;
     //if the user enters /tdsmpluginexample -test 1, it will retreive the next value '1' and put into 'arg' as an integer.
     if (args.TryParseOne<int>("-test", out arg))
     {
         sender.sendMessage(sender.Name + " Argument: " + arg);
     }
     else
     {
         //For new people, I would not really expect you to understand the following.
         //If needed I can simplify this down...
         string Platform = Terraria_Server.Definitions.Platform.Type.ToString();
         switch (Terraria_Server.Definitions.Platform.Type)
         {
             case Terraria_Server.Definitions.Platform.PlatformType.LINUX:
                 Platform = "Linux";
                 break;
             case Terraria_Server.Definitions.Platform.PlatformType.MAC:
                 Platform = "Mac";
                 break;
             case Terraria_Server.Definitions.Platform.PlatformType.WINDOWS:
                 Platform = "Windows";
                 break;
         }
         (sender as Player).sendMessage("TDSM Plugin Example, Running OS: " + Platform, ChatColor.DarkGreen);
     }
 }
Exemple #17
0
        void PasswordCommand(ISender sender, ArgumentList args)
        {
            Player player = sender as Player;
                Protection temp = new Protection ();
                Pair<Action, Protection> pair = new Pair<Action, Protection> (Action.NOTHING, null);

                if (args.Count != 1) {
                    player.SendMessage ("Usage: /cpassword <password>", 255, 255, 0, 0);
                    return;
                }

                string Extra = args[0];

                temp = new Protection ();
                temp.Owner = player.Name;
                temp.Type = Protection.PASSWORD_PROTECTION;
                temp.Data = SHA1.Hash (Extra);

                char[] pass = Extra.ToCharArray ();
                for (int index = 0; index < pass.Length; index++) {
                    pass [index] = '*';
                }

                pair.First = Action.CREATE;
                pair.Second = temp;

                player.SendMessage ("Password: "******"Open the chest to protect it!", 255, 0, 255, 0);

            // cache the action if it's not null!
            if (pair.First != Action.NOTHING) {
                ResetActions (player);
                Cache.Actions.Add (player.Name, pair);
            }
        }
        public static void roll(Server server, ISender sender, ArgumentList args)
        {
            Random random = new Random();
            int result = 0;
            int times = 1;
            int die = 6;

            if (args.Count > 0)
            {
                string[] arg = args[0].Split('d');
                times = Int32.Parse(arg[0]);
                die = Int32.Parse(arg[1]);
            }

            for (int i = 0; i < times; i++)
            {
                result += random.Next(1, die);
            }

            Player player = server.GetPlayerByName(sender.Name);

            if (! player.PluginData.ContainsKey("roll"))
            {
                player.PluginData.Add("roll", result);
            }
            else
            {
                player.PluginData["roll"] = result;
            }

            server.notifyAll(player.Name + " rolled a " + player.PluginData["roll"] + " on " + times.ToString() + "d" + die.ToString(), true);
        }
Exemple #19
0
    override public void Invoke(ISender target, Channel q, string method,
                                params object[] args)
    {
      IRpcHandler handler = null;
      string mname = null;
      lock( _sync ) {
        object[] info = (object[]) _method_cache[method];
        if( info == null ) {
          string[] parts = method.Split('.');
          string hname = parts[0];
          mname = parts[1];
          
          handler = (IRpcHandler)_method_handlers[ hname ];
          if( handler == null ) {
            //No handler for this.
            throw new AdrException(-32601, "No Handler for method: " + method);
          }
          info = new object[2];
          info[0] = handler;
          info[1] = mname;
          _method_cache[ method ] = info;
        }
        else {
          handler = (IRpcHandler)info[0];
          mname = (string)info[1];
        }
      }

      handler.HandleRpc(target, mname, args, q);
    }
        /// <summary>
        /// Refreshes a players area
        /// </summary>
        /// <param name="sender">Sending player</param>
        /// <param name="args">Arguments sent with command</param>
        public void Refresh(ISender sender, ArgumentList args)
        {
            args.ParseNone();

            var player = sender as Player;

            if (player == null)
            {
                sender.Message(255, "This is a player command");
                return;
            }

            if (player.whoAmI < 0)
                return;

            if (!player.Op)
            {
                var diff = DateTime.Now - player.GetLastCostlyCommand();

                if (diff < TimeSpan.FromSeconds(30))
                {
                    sender.Message(255, "You must wait {0:0} more seconds before using this command.", 30.0 - diff.TotalSeconds);
                    return;
                }

                player.SetLastCostlyCommand(DateTime.Now);
            }

            NetMessage.SendTileSquare(player.whoAmI, (int)(player.position.X / 16), (int)(player.position.Y / 16), 32);
        }
        /// <summary>
        /// Fast forwards time
        /// </summary>
        /// <param name="sender">Sending player</param>
        /// <param name="args">Arguments sent with command</param>
        public void FastForwardTime(ISender sender, ArgumentList args)
        {
            args.ParseNone();

            Core.TimeFastForwarding = !Core.TimeFastForwarding;
            sender.Message("Time is now " + (Core.TimeFastForwarding ? "fast" : "normal") + "!");
        }
 //TODO sort commands in alphabetical order.
 /// <summary>
 /// Shuts down an exists.
 /// </summary>
 /// <param name="sender">Sending entity</param>
 /// <param name="args">Arguments sent with command</param>
 public static void Clear(ISender sender, ArgumentList args)
 {
     if (sender is ConsoleSender)
     {
         Console.Clear();
     }
 }
 /// <summary>
 /// Allows users to log in.
 /// </summary>
 /// <param name="sender">Sending player</param>
 /// <param name="password">Password for verification</param>
 public void Auth(ISender sender, string password)
 {
     if (sender is Player)
     {
         var player = sender as Player;
         if (Storage.IsAvailable)
         {
             var existing = Authentication.GetPlayer(sender.SenderName);
             if (existing != null)
             {
                 if (existing.ComparePassword(sender.SenderName, password))
                 {
                     Utils.NotifyAllOps(
                         String.Format("{0} successfully logged in.", player.name)
                     );
                     player.SendMessage("Successfully logged in.", Color.DarkGreen);
                     player.SetAuthentication(sender.SenderName, "tdsm");
                     player.SetOp(existing.Operator);
                 }
                 else
                 {
                     sender.Message("Login failed", Color.DarkRed);
                 }
             }
             else
             {
                 sender.Message("Login failed", Color.DarkRed);
             }
         }
         else
             sender.Message("This function is unavailable", Color.DarkRed);
     }
 }
Exemple #24
0
 public void Subscribe(ISender sender)
 {
     sender.MessageAvailable += (o, args) =>
                                    {
                                        ReceivedMessage = args.Message;
                                    };
 }
        /// <summary>
        /// Prints a player list, Possibly readable by bots.
        /// </summary>
        /// <param name="sender">Sending player</param>
        /// <param name="args">Arguments sent with command</param>
        public void List(ISender sender, ArgumentList args)
        {
            args.ParseNone();

            var players = from p in Terraria.Main.player
                                   where p.active && !p.IsOp()
                                   select p.name;
            var ops = from p in Terraria.Main.player
                               where p.active && p.IsOp()
                               select p.name;

            var pn = players.Count();
            var on = ops.Count();

            if (on + pn == 0)
            {
                sender.Message("No players online.");
                return;
            }

            string ps = String.Empty;
            string os = String.Empty;

            if (pn > 0)
                ps = (on > 0 ? " | Players: " : "Players: ") + String.Join(", ", players);

            if (on > 0)
                os = "Ops: " + String.Join(", ", ops);

            sender.SendMessage(string.Concat(os, ps, " (", on + pn, "/", Netplay.MaxConnections, ")"), 255, 255, 240, 20);
        }
        public RequestCommand(ISender sender)
        {
            if (sender == null)
                throw new ArgumentNullException("sender");

            this.sender = sender;
        }
        /// <summary>
        /// Teleports specified player to sending player's location.
        /// </summary>
        /// <param name="sender">Sending player</param>
        /// <param name="args">Arguments sent with command</param>
        public void TeleportHere(ISender sender, ArgumentList args)
        {
            if (sender is Player)
            {
                Player player = ((Player)sender);
                Player subject;

                if (args.TryPopOne(out subject))
                {
                    if (subject == null)
                    {
                        sender.Message("Cannot find player");
                        return;
                    }

                    subject.Teleport(player);

                    Utils.NotifyAllOps("Teleported " + subject.name + " to " +
                        player.name + " [" + sender.SenderName + "]", true);
                }
            }
            else
            {
                throw new CommandError("This command is for players only");
            }
        }
 /// <summary>
 /// Bans a user from the server.
 /// </summary>
 /// <param name="sender">Sending entity</param>
 /// <param name="args">Arguments sent with command</param>
 public static void Ban(ISender sender, string player)
 {
     if (sender is ConsoleSender)
     {
         if (String.IsNullOrEmpty(player))
         {
             Tools.WriteLine("Usage: ban <player>");
         }
         else
         {
             bool found = false;
             var lowered = player.ToLower();
             for (int i = 0; i < 255; i++)
             {
                 if (Main.player[i].active && Main.player[i].name.ToLower() == lowered)
                 {
                     Callbacks.NetplayCallback.AddBan(i);
                     NetMessage.SendData(2, i, -1, "Banned from server.", 0, 0f, 0f, 0f, 0);
                     found = true;
                 }
             }
             if (!found) sender.Message("Failed to find a player by the name of {0}", player);
         }
     }
 }
        /// <summary>
        /// Heals one or all players.
        /// </summary>
        /// <param name="sender">Sending player</param>
        /// <param name="message">Message to send</param>
        public void Heal(ISender sender, ArgumentList args)
        {
            Player subject;

            if (args.TryPopOne(out subject))
            {
                subject = sender as Player;
                if (subject == null)
                {
                    sender.Message("Need a heal target");
                    return;
                }

                NetMessage.SendData((int)Packet.HEAL_PLAYER, -1, -1, String.Empty, subject.whoAmI, (float)subject.statLifeMax);
                subject.Message("You have been healed!", Color.Green);
            }
            else if (args.TryPop("-all"))
            {
                foreach (var plr in Main.player)
                {
                    if (plr.active)
                    {
                        NetMessage.SendData((int)Packet.HEAL_PLAYER, -1, -1, String.Empty, plr.whoAmI, (float)plr.statLifeMax);
                        plr.Message("You have been healed!", Color.Green);
                    }
                }
            }
            else if (sender is Player)
            {
                var plr = sender as Player;
                NetMessage.SendData((int)Packet.HEAL_PLAYER, -1, -1, String.Empty, plr.whoAmI, (float)plr.statLifeMax);
                plr.Message("You have been healed!", Color.Green);
            }
            else throw new CommandError("Nobody specified to heal");
        }
        public static void ExampleCommand(ISender sender, ArgumentList args)
        {
            TDSM_Plugin MyPlugin = (TDSM_Plugin)args.Plugin; //Get the plugin object who's assigned to the "tdsmpluginexample"

            //if the user enters /tdsmpluginexample -test 1, it will retreive the next value '1' and put into 'arg' as an integer.
            int arg;
            if (args.TryParseOne<int>("-test", out arg))
                sender.sendMessage(sender.Name + " Argument: " + arg);
            else
            {
                //For new people to .NET, I would not really expect you to understand everything just yet.
                string platform = Platform.Type.ToString();
                switch (Platform.Type)
                {
                    case Platform.PlatformType.LINUX:
                        platform = "Linux";
                        break;
                    case Platform.PlatformType.MAC:
                        platform = "Mac";
                        break;
                    case Platform.PlatformType.WINDOWS:
                        platform = "Windows";
                        break;
                }

                (sender as Player).sendMessage("TDSM Plugin Example, Running OS: " + platform, ChatColor.DarkGreen);
            }
        }
Exemple #31
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();
                    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]);
                    ContinueGet(token, rs);
                    return;
                }

                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);
        }
Exemple #32
0
 public BucketVariableProvider(ISender sender, IDocumentSerializer documentSerializer)
 {
     _sender             = sender;
     _documentSerializer = documentSerializer;
 }
Exemple #33
0
 public MediaLinkMessageReceiver(ISender sender)
 {
     _sender = sender;
 }
 public TalkBack(ISender sender)
 {
     this.sender = sender;
 }
Exemple #35
0
 public GamesController(ISender sender)
 {
     _sender = sender;
 }
Exemple #36
0
 public PlainTextMessageReceiver(ISender sender, Settings settings)
 {
     _sender   = sender;
     _settings = settings;
 }
Exemple #37
0
 virtual public void HandleData(MemBlock b, ISender return_path, object state)
 {
     Handle(b, return_path);
 }
 public void UnregisterSender(ISender sender)
 {
     senderList.Remove(sender);
 }
Exemple #39
0
        /**
         * This starts a linking operation on the given edge
         */
        public IDictionary Start(IDictionary link_message, ISender edge)
        {
            if (ProtocolLog.LinkDebug.Enabled)
            {
                ProtocolLog.Write(ProtocolLog.LinkDebug, String.Format(
                                      "{0} -start- sys:link.Start", _node.Address));
            }

            Edge        from = GetEdge(edge);
            LinkMessage lm   = new LinkMessage(link_message);

            if (ProtocolLog.LinkDebug.Enabled)
            {
                ProtocolLog.Write(ProtocolLog.LinkDebug, String.Format(
                                      "{0} -args- sys:link.Start({1},{2})", _node.Address, lm, from));
            }

            CphState cph = new CphState(from, lm);

            lock ( _sync ) {
                if (!_edge_to_cphstate.ContainsKey(from))
                {
                    _edge_to_cphstate[from] = cph;
                }
                else
                {
                    throw new AdrException((int)ErrorMessage.ErrorCode.InProgress,
                                           "Already have a link in progress on this edge");
                }
            }
            ErrorMessage err = null;

            if (CanConnect(cph, out err))
            {
                try {
                    //If the CloseEvent was already called, this throws an exception
                    from.CloseEvent += this.CloseHandler;
                }
                catch {
                    CloseHandler(from, null);
                    throw new AdrException((int)ErrorMessage.ErrorCode.EdgeClosed,
                                           "Edge Closed after receiving message");
                }
            }
            else
            {
                lock ( _sync ) {
                    _edge_to_cphstate.Remove(from);
                }
            }
            //Now we prepare our response
            LinkMessage lm_resp = null;

            if (err == null)
            {
                //We send a response:
                NodeInfo n_info      = NodeInfo.CreateInstance(_node.Address, from.LocalTA);
                NodeInfo remote_info = NodeInfo.CreateInstance(null, from.RemoteTA);
                lm_resp = new LinkMessage(lm.ConTypeString, n_info, remote_info, _node.Realm, lm.Token);
            }
            else
            {
                if (err.Ec == ErrorMessage.ErrorCode.AlreadyConnected)
                {
                    /**
                     * When we send the ErrorCode.AlreadyConnected,
                     * we could have a stale connection, lets try pinging
                     * the other node, if they are there, but have lost
                     * the Edge, this may trigger the edge to close, causing
                     * us to remove the Connection.
                     * @todo consider putting this address on a "fast track"
                     * to removal if we don't hear from it soon
                     */
                    ConnectionTable tab = _node.ConnectionTable;
                    Connection      c   = tab.GetConnection(lm.ConnectionType,
                                                            lm.Local.Address);
                    if (c != null)
                    {
                        RpcManager rpc = _node.Rpc;
                        rpc.Invoke(c.Edge, null, "sys:link.Ping", String.Empty);
                    }
                }
            }
            if (err != null)
            {
                throw new AdrException((int)err.Ec, err.Message);
            }
            if (ProtocolLog.LinkDebug.Enabled)
            {
                ProtocolLog.Write(ProtocolLog.LinkDebug, String.Format(
                                      "{0} -end- sys:link.Start()->{1}", _node.Address, lm_resp));
            }
            return(lm_resp.ToDictionary());
        }
Exemple #40
0
        /**
         * Get a StatusMessage for this node
         */
        public IDictionary GetStatus(IDictionary status_message, ISender edge)
        {
            //we just got s status request
            if (1 == _disconnecting)
            {
                throw new AdrException((int)ErrorMessage.ErrorCode.Disconnecting, "disconnecting");
            }

            StatusMessage sm   = new StatusMessage(status_message);
            Edge          from = GetEdge(edge);

            if (ProtocolLog.LinkDebug.Enabled)
            {
                ProtocolLog.Write(ProtocolLog.LinkDebug, String.Format(
                                      "{0} -start- sys:link.GetStatus({1},{2})", _node.Address, sm, edge));
            }

            CphState cphstate = null;

            if (from != null)
            {
                cphstate = _edge_to_cphstate[from] as CphState;
            }

            /**
             * StatusMessage objects are used to verify the completion
             * of the Link protocol.  If we receive a StatusMessage request
             * after we send a LinkMessage response, we know the other
             * Node got our LinkMessage response, and the connection
             * is active
             */
            StatusMessage   response = null;
            ConnectionTable tab      = _node.ConnectionTable;

            if (cphstate != null)
            {
                try {
                    LinkMessage lm_to_add = cphstate.LM;
                    //This is part of connection process:
                    response = _node.GetStatus(sm.NeighborType, lm_to_add.Local.Address);
                    Connection con = new Connection(from,
                                                    lm_to_add.Local.Address,
                                                    lm_to_add.ConTypeString,
                                                    sm,
                                                    lm_to_add);
                    tab.Add(con);
                }
                finally {
                    from.CloseEvent -= this.CloseHandler;
                    CloseHandler(from, null);
                }
            }
            else
            {
                //This is just a "regular" status request
                //update our table:
                Address    fadd = null;
                Connection c    = tab.GetConnection(from);
                if (c != null)
                {
                    fadd = c.Address;
                    tab.UpdateStatus(c, sm);
                }
                response = _node.GetStatus(sm.NeighborType, fadd);
            }

            if (ProtocolLog.LinkDebug.Enabled)
            {
                ProtocolLog.Write(ProtocolLog.LinkDebug, String.Format(
                                      "{0} -end- sys:link.GetStatus()->{1}", _node.Address, response));
            }

            return(response.ToDictionary());
        }
Exemple #41
0
 public AuthorizationController(ISender mediator)
 {
     _mediator = mediator;
 }
Exemple #42
0
 public OptionNativeContentReceiver(ISender sender)
 {
     _sender = sender;
 }
Exemple #43
0
 private LoginApi(ISender sender) : base(ID, sender)
 {
 }
Exemple #44
0
 public static LoginApi Create(ISender sender) => new LoginApi(sender);
Exemple #45
0
 public PlaybackController(ISender parent)
 {
     this.parent = parent;
 }
Exemple #46
0
        private void ProcessFirstUpdate(ISender sender)
        {
            var data = Repository.GetAllData().Select(c => c.Data).ToList();

            sender.Update(data);
        }
Exemple #47
0
 /// <summary>
 /// Creates a new email instance with overrides for the rendering and sending engines.
 /// </summary>
 /// <param name="renderer">The template rendering engine</param>
 /// <param name="sender">The email sending implementation</param>
 public Email(ITemplateRenderer renderer, ISender sender)
     : this(renderer, sender, null, null)
 {
 }
Exemple #48
0
 /// <inheritdoc />
 public override bool CanExecuteFrom(ISender sender) => _client.Equals(sender);
 public void Setup(INodeParameters _nodeParameters, ILogger _logger)
 {
     variable = new Variable().Set(null as object);
     sender   = _nodeParameters.GetSender();
     _nodeParameters.AddOutput(true, "Object", "Unity collision object");
 }
 public void Setup(INodeParameters _node, ILogger _logger)
 {
     _node.AddInput(this, true, "a");
     sender = _node.GetSender();
     _node.AddOutput(false, "Closest power of two");
 }
 public ClientsController(ISender sender)
 {
     fSender = sender;
 }
Exemple #52
0
 public LightweightSendingAgent(Uri destination, ISender sender, CompositeTransportLogger logger, BusSettings settings)
     : base(destination, sender, logger, settings, new LightweightRetryAgent(sender, settings.Retries))
 {
 }
 public URLPrefixSender(string urlPrefix, ISender inner)
 {
     this.urlPrefix = urlPrefix;
     this.inner     = inner;
 }
Exemple #54
0
        /** Handle incoming data on an Edge
         */
        public void HandleData(MemBlock data, ISender retpath, object state)
        {
            MemBlock rest_of_data;
            PType    p;

            if (state == null)
            {
                try {
                    p = PType.Parse(data, out rest_of_data);
                } catch (ParseException) {
                    ProtocolLog.WriteIf(ProtocolLog.Pathing, "Invalid PType from: " + data);
                    return;
                }
                p = PType.Parse(data, out rest_of_data);
            }
            else
            {
                //a demux has already happened:
                p            = (PType)state;
                rest_of_data = data;
            }

            if (PType.Protocol.Pathing.Equals(p))
            {
                /*
                 * We use a special PType to denote this transaction so
                 * we don't confuse it with other RepRep communication
                 */
                _rrm.HandleData(rest_of_data, retpath, null);
            }
            else if (PType.Protocol.Rpc.Equals(p))
            {
                /*
                 * Send this to the RpcHandler
                 */
                Rpc.HandleData(rest_of_data, retpath, null);
            }
            else
            {
                /*
                 * This is some other data
                 * It is either:
                 * 1) Time to announce an already created edge.
                 * 2) Assume this is a "default path" edge creation, to be backwards
                 * compatible
                 */
                Edge     e  = null;
                PathEdge pe = null;
                try {
                    e = (Edge)retpath;
                    PathEdgeListener pel = null;
                    lock ( _sync ) {
                        if (_unannounced.TryGetValue(e, out pe))
                        {
                            //
                            _unannounced.Remove(e);
                            pel = _pel_map[pe.LocalPath];
                        }
                    }
                    if (pe == null)
                    {
                        if (!_pel_map.ContainsKey(Root))
                        {
                            ProtocolLog.WriteIf(ProtocolLog.Pathing, "No root, can't create edge");
                            if (e != null)
                            {
                                e.Close();
                            }
                            return;
                        }

                        /*
                         * This must be a "default path" incoming connection
                         */
                        pel = _pel_map[Root];
                        pe  = new PathEdge(this, e, Root, Root);
                    }
                    pel.SendPathEdgeEvent(pe);
                    pe.Subscribe();
                    pe.ReceivedPacketEvent(data);
                }
                catch (Exception x) {
                    if (pe != null)
                    {
                        //This closes both edges:
                        pe.Close();
                    }
                    else if (e != null)
                    {
                        ProtocolLog.WriteIf(ProtocolLog.Pathing,
                                            String.Format("Closing ({0}) due to: {1}", e, x));
                        e.Close();
                    }
                }
            }
        }
        protected void HandleReply(ReqrepType rt, int idnum, MemBlock rest, ISender ret_path)
        {
            RequestState reqs;

            if (_req_state_table.TryGet(idnum, out reqs))
            {
                IReplyHandler handler = null;
                lock ( _sync ) {
                    if (reqs.AddReplier(ret_path))
                    {
                        TimeSpan rtt = DateTime.UtcNow - reqs.ReqDate;

                        /*
                         * Let's look at how long it took to get this reply:
                         */
                        if (reqs.GotAck)
                        {
                            //Use more standard deviations for acked messages.  We
                            //just don't want to let it run forever.
                            _acked_reqtimeout = ComputeNewTimeOut(rtt.TotalMilliseconds,
                                                                  _acked_rtt_stats,
                                                                  _MINIMUM_TIMEOUT, 3 * _STD_DEVS);
                        }
                        else if (ret_path is Edge)
                        {
                            _edge_reqtimeout = ComputeNewTimeOut(rtt.TotalMilliseconds,
                                                                 _edge_rtt_stats,
                                                                 _MINIMUM_TIMEOUT, _STD_DEVS);
                        }
                        else
                        {
                            _nonedge_reqtimeout = ComputeNewTimeOut(rtt.TotalMilliseconds,
                                                                    _nonedge_rtt_stats, _MINIMUM_TIMEOUT, _STD_DEVS);
                        }
                        handler = reqs.ReplyHandler;
                    }
                }

                /*
                 * Now handle this reply
                 */
                if (null != handler)
                {
                    MemBlock   payload;
                    PType      pt         = PType.Parse(rest, out payload);
                    Statistics statistics = new Statistics();
                    statistics.SendCount = reqs.SendCount;
  #if REQREP_DEBUG
                    Console.Error.WriteLine("[ReqrepManager: {0}] Receiving reply on request id: {1}, from: {2}",
                                            _info, idnum, ret_path);
  #endif

                    //Don't hold the lock while calling the ReplyHandler:
                    bool continue_listening = handler.HandleReply(this, rt, idnum, pt, payload,
                                                                  ret_path, statistics, reqs.UserState);
                    //the request has been served
                    if (!continue_listening)
                    {
                        StopRequest(idnum, handler);
                    }
                }
            }
            else
            {
                //We are ignoring this reply, it either makes no sense, or we have
                //already handled it
            }
        }
Exemple #56
0
 /// <param name="sender">The ISender that will take care of the actual sending as well as storing the items to be sent</param>
 /// <param name="serialization">The object that is used to serialize the spans into Thrift</param>
 protected internal JaegerThriftTransport(ISender sender, ISerialization serialization = null)
 {
     _sender = sender;
     _jaegerThriftSerialization = serialization ?? new JaegerThriftSerialization();
 }
Exemple #57
0
 public static SenderRet Send(ISender sender, PushChannelModel channel, PushMsgModel msg)
 {
     return(sender.Send(channel, msg));
 }
 public Client(ISender sender, ISerializer serializer)
 {
     this.sender     = sender;
     this.serializer = serializer;
 }
Exemple #59
0
 public static SenderRet Send(ISender sender, PushChannelModel channel, List <PushMsgModel> msgList)
 {
     return(sender.SendList(channel, msgList));
 }
 private void Execute(ISender client, GetStartupItemsResponse message)
 {
     OnReport(message.StartupItems);
 }