public override void Process(int whoAmI, byte[] readBuffer, int length, int num)
        {
            var player = Main.players[whoAmI];

            player.HasClientMod = true;
            ProgramLog.Log(player.Name + " has logged in with the TDCM Client");

            //Update Client with server data.
            NetMessage.SendData(Packet.CLIENT_MOD, whoAmI);
        }
Exemple #2
0
        public void Save(bool log = true)
        {
            var tmpName = propertiesPath + ".tmp" + (uint)(DateTime.UtcNow.Ticks % uint.MaxValue);
            var writer  = new StreamWriter(tmpName);

            try
            {
                foreach (string line in header)
                {
                    if (line.Trim().Length > 0)
                    {
                        writer.WriteLine(HEADER + line);
                    }
                }

                foreach (KeyValuePair <String, String> pair in propertiesMap)
                {
                    if (pair.Value != null)
                    {
                        if (commentsMap.ContainsKey(pair.Key))
                        {
                            writer.WriteLine(COMMENT + commentsMap[pair.Key]);
                        }
                        writer.WriteLine(pair.Key + EQUALS + pair.Value);
                    }
                }
            }
            finally
            {
                writer.Close();
            }

            try
            {
                File.Replace(tmpName, propertiesPath, null, true);
                if (log)
                {
                    ProgramLog.Log("{1} \"{0}\".", propertiesPath, Languages.SavedFile);
                }
            }
            catch (IOException e)
            {
                if (log)
                {
                    ProgramLog.Log("{2} \"{0}\" {3}: {1}", propertiesPath, e.Message, Languages.SavedTo, Languages.Failed);
                }
            }
            catch (SystemException e)
            {
                if (log)
                {
                    ProgramLog.Log("{2} \"{0}\" {3}: {1}", propertiesPath, e.Message, Languages.SavedTo, Languages.Failed);
                }
            }
        }
Exemple #3
0
        //public static bool StartEclipse;
        //public static bool StartBloodMoon;

        public static void ProgramStart()
        {
            Console.Clear();
            Console.ForegroundColor = ConsoleColor.Yellow;
            ProgramLog.Log("TDSM Rebind API build {0}{1} running on {2}",
                           Globals.Build,
                           Globals.PhaseToSuffix(Globals.BuildPhase),
                           Tools.RuntimePlatform.ToString()
                           );
            Console.ForegroundColor = Command.ConsoleSender.DefaultColour;

            Globals.Touch();
            ID.Lookup.Initialise();

            try
            {
                var lis = new Logging.LogTraceListener();
                System.Diagnostics.Trace.Listeners.Clear();
                System.Diagnostics.Trace.Listeners.Add(lis);
                System.Diagnostics.Debug.Listeners.Clear();
                System.Diagnostics.Debug.Listeners.Add(lis);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            //This will setup the assembly resolves
            PluginManager.Initialize(Globals.PluginPath);
            PluginManager.SetHookSource(typeof(HookPoints));

            //Load the logs
            if (!ProgramLog.IsOpen)
            {
                var logFile = Globals.DataPath + System.IO.Path.DirectorySeparatorChar + "server.log";
                ProgramLog.OpenLogFile(logFile);
                ConsoleSender.DefaultColour = ConsoleColor.Gray;
            }

            //Load plugins
            PluginManager.LoadPlugins();

//            if (!Permissions.PermissionsManager.IsSet)
//            {
//                var file = System.IO.Path.Combine(Globals.DataPath, "permissions.xml");
//                //if (System.IO.File.Exists(file)) System.IO.File.Delete(file);
//                if (System.IO.File.Exists(file))
//                {
//                    var handler = new Permissions.XmlSupplier(file);
//                    if (handler.Load())
//                        Permissions.PermissionsManager.SetHandler(handler);
//                }
//            }
        }
        public static void OnServerInitialising(Entry core)
        {
            if (!String.IsNullOrEmpty(core.Config.Rcon_BindAddress))
            {
                _nonce       = core.Config.Rcon_HashNonce;
                _bindAddress = core.Config.Rcon_BindAddress;

                ProgramLog.Log("Starting RCON Server");
                Start(Path.Combine(Globals.DataPath, "rcon_logins.properties"));
            }
        }
        void OnPlayerDataReceived(ref HookContext ctx, ref HookArgs.PlayerDataReceived args)
        {
            ctx.SetKick("Malfunction during login process, try again.");

            if (!args.NameChecked)
            {
                string error;
                if (!args.CheckName(out error))
                {
                    ctx.SetKick(error);
                    return;
                }
            }

            var player = ctx.Player;

            if (player == null)
            {
                ProgramLog.Error.Log("Null player passed to Restrict.OnPlayerDataReceived.");
                return;
            }

            var    name  = args.Name;
            var    pname = NameTransform(name);
            var    oname = OldNameTransform(name);
            string entry = null;

            lock (users)
            {
                entry = users.getValue(pname) ?? users.getValue(oname);
            }

            if (entry == null)
            {
                if (allowGuests)
                {
                    ctx.SetResult(HookResult.DEFAULT);
                    player.AuthenticatedAs      = null;
                    ctx.Connection.DesiredQueue = 0;                     //(int)LoginPriority.QUEUE_LOW_PRIO;

                    ProgramLog.Log("<Restrict> Letting user {0} from {1} in as guest.", name, player.IPAddress);
                }
                else
                {
                    ProgramLog.Log("<Restrict> Unregistered user {0} from {1} attempted to connect.", name, player.IPAddress);
                    ctx.SetKick("Only registered users are allowed.");
                    return;
                }
                return;
            }

            ProgramLog.Log("<Restrict> Expecting password for user {0} from {1}.", name, player.IPAddress);
            ctx.SetResult(HookResult.ASK_PASS);
        }
        public static bool Initialise()
        {
            var npc  = new FileInfo(Path.Combine(Globals.DataPath, "npc.xml"));
            var item = new FileInfo(Path.Combine(Globals.DataPath, "item.xml"));

            //Always keep these in the data path, as we may use the update mechanism to update these definitions periodically
            var intNPC  = LoadDefinition <NPCInfo>("npc.xml");
            var intItem = LoadDefinition <ItemInfo>("item.xml");

            //If they already exist we must compare with the internal versions. Use the latest.
            if (npc.Exists)
            {
                var current = LoadDefinition <NPCInfo>(npc);
                if (current.Version < intNPC.Version)
                {
                    //Save new
                    Save <NPCInfo>(npc, intNPC);
                    ProgramLog.Log("NPC definitions were updated to v{0}", intNPC.Version);
                    _npc = intNPC;
                }
                else
                {
                    _npc = current;
                }
            }
            else
            {
                Save <NPCInfo>(npc, intNPC);
                _npc = intNPC;
            }
            if (item.Exists)
            {
                var current = LoadDefinition <ItemInfo>(item);
                if (current.Version < intItem.Version)
                {
                    //Save new
                    Save <ItemInfo>(item, intItem);
                    ProgramLog.Log("Item definitions were updated to v{0}", intItem.Version);
                    _item = intItem;
                }
                else
                {
                    _item = current;
                }
            }
            else
            {
                Save <ItemInfo>(item, intItem);
                _item = intItem;
            }

            return(true);
        }
Exemple #7
0
        internal bool Initialize(object state = null)
        {
            if (initialized)
            {
                ProgramLog.Error.Log("Double initialize of plugin {0}.", Name);
                return(true);
            }

            try
            {
                Initialized(state);
            }
            catch (Exception e)
            {
                ProgramLog.Log(e, "Exception in initialization handler of plugin " + Name);
                return(false);
            }

            if (!NotifyWorldLoaded())
            {
                return(false);
            }

            var methods = this.GetType().GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);

            foreach (var method in methods)
            {
                var attr = method.GetCustomAttributes(typeof(HookAttribute), true);
                if (attr.Length > 0)
                {
                    var ha     = attr[0] as HookAttribute;
                    var hpName = method.GetParameters()[1].ParameterType.GetElementType().Name;

                    var hookPoint = typeof(HookPoints).GetField(hpName).GetValue(null) as HookPoint;

                    Delegate callback;
                    if (method.IsStatic)                     // TODO: exception handling
                    {
                        callback = Delegate.CreateDelegate(hookPoint.DelegateType, method);
                    }
                    else
                    {
                        callback = Delegate.CreateDelegate(hookPoint.DelegateType, this, method);
                    }

                    HookBase(hookPoint, ha.order, callback);
                }
            }

            initialized = true;

            return(true);
        }
Exemple #8
0
 internal object Suspend()
 {
     try
     {
         return(SuspendedAndSaved());
     }
     catch (Exception e)
     {
         ProgramLog.Log(e, "Exception while saving plugin state of " + Name);
         return(null);
     }
 }
        public override void Process(int whoAmI, byte[] readBuffer, int length, int num)
        {
            int start       = num - 1;
            int playerIndex = ReadByte(readBuffer);

            if (playerIndex != whoAmI && Entry.EnableCheatProtection)
            {
                Terraria.Netplay.Clients[whoAmI].Kick("Cheating detected (KILL_PLAYER forgery).");
                return;
            }

            var player = Main.player[whoAmI];

            var ctx = new HookContext
            {
                Connection = (Terraria.Netplay.Clients[whoAmI] as ServerSlot).conn,
                Sender     = player,
                Player     = player,
            };

            var args = new HookArgs.ObituaryReceived
            {
                Direction = (int)ReadByte(readBuffer) - 1,
                Damage    = ReadInt16(readBuffer),
                PvpFlag   = ReadByte(readBuffer)
            };

            //string obituary;
            //if (!ParseString(readBuffer, num + 1, length - num - 1 + start, out obituary))
            //{
            //    tdsm.api.Callbacks.Netplay.slots[whoAmI].Kick("Invalid characters in obituary message.");
            //    return;
            //}
            args.Obituary = " " + ReadString(readBuffer);

            HookPoints.ObituaryReceived.Invoke(ref ctx, ref args);

            if (ctx.CheckForKick())
            {
                return;
            }

            if (ctx.Result == HookResult.IGNORE)
            {
                return;
            }

            ProgramLog.Log("{0} @ {1}: [Death] {2}{3}", player.IPAddress, whoAmI, player.Name ?? "<null>", args.Obituary);

            player.KillMe(args.Damage, args.Direction, args.PvpFlag == 1, args.Obituary);

            NewNetMessage.SendData(44, -1, whoAmI, args.Obituary, whoAmI, args.Direction, args.Damage, args.PvpFlag);
        }
        public void Load(string filePath)
        {
            var document = new XmlDocument();

            document.Load(Assembly.GetExecutingAssembly().GetManifestResourceStream(Registries.DEFINITIONS + filePath));
            var nodes = document.SelectNodes("/*/*");
            var ser   = new XmlSerializer(typeof(T));

            foreach (XmlNode node in nodes)
            {
                try
                {
                    var rdr = new XmlNodeReader(node);
                    var t   = (T)ser.Deserialize(rdr);

                    //ProgramLog.Debug.Log ("Created entity {0}, {1}", t.Type, t.Name);

                    t.Name = String.Intern(t.Name);
                    if (t.NetID == 0)
                    {
                        t.NetID = (short)t.Type;
                    }
                    //Networking.StringCache.Add (System.Text.Encoding.ASCII.GetBytes (t.Name), t.Name);
                    Networking.StringCache.Add(t.Name);

                    if (typeLookup.ContainsKey(t.Type))
                    {
                        List <T> values;
                        if (typeLookup.TryGetValue(t.Type, out values))
                        {
                            values.Add(t);
                        }
                    }
                    else
                    {
                        List <T> values = new List <T>();
                        values.Add(t);
                        typeLookup.Add(t.Type, values);
                    }

                    if (!nameLookup.ContainsKey(t.Name))
                    {
                        nameLookup.Add(t.Name, t);
                    }
                }
                catch (Exception e)
                {
                    ProgramLog.Log(e, "Error adding element");
                    ProgramLog.Error.Log("Element was:\n" + node.ToString());
                }
            }
        }
Exemple #11
0
 internal bool Resume(object state)
 {
     try
     {
         Resumed(state);
         return(true);
     }
     catch (Exception e)
     {
         ProgramLog.Log(e, "Exception while saving plugin state of " + Name);
         return(false);
     }
 }
        internal void ProcessLine(string line)
        {
            ProgramLog.Admin.Log("Remote command from {0} ({1}): \"{2}\"", Name, remoteAddress, line);

            try
            {
                Program.commandParser.ParseConsoleCommand(line, this.sender);
            }
            catch (Exception e)
            {
                ProgramLog.Log(e, "Issue parsing remote command from " + Id);
            }
        }
        public override void Process(ClientConnection conn, byte[] readBuffer, int length, int pos)
        {
            var slot = conn.SlotIndex;

            if (slot >= 0)
            {
                Process(slot, readBuffer, length, pos);
            }
            else
            {
                ProgramLog.Log("Attempt to process packet {0} before slot assignment.", GetPacket());
            }
        }
Exemple #14
0
        public void Save(bool log = true)
        {
            var tmpName = propertiesPath + ".tmp" + (uint)(DateTime.UtcNow.Ticks % uint.MaxValue);
            var writer  = new StreamWriter(tmpName);

            try
            {
                foreach (string line in header)
                {
                    if (line.Trim().Length > 0)
                    {
                        writer.WriteLine(HEADER + line);
                    }
                }

                foreach (KeyValuePair <String, String> pair in propertiesMap)
                {
                    if (pair.Value != null)
                    {
                        writer.WriteLine(pair.Key + EQUALS + pair.Value);
                    }
                }
            }
            finally
            {
                writer.Close();
            }

            try
            {
                File.Replace(tmpName, propertiesPath, null, true);
                if (log)
                {
                    ProgramLog.Log("Saved file \"{0}\".", propertiesPath);
                }
            }
            catch (IOException e)
            {
                if (log)
                {
                    ProgramLog.Log("Save to \"{0}\" failed: {1}", propertiesPath, e.Message);
                }
            }
            catch (SystemException e)
            {
                if (log)
                {
                    ProgramLog.Log("Save to \"{0}\" failed: {1}", propertiesPath, e.Message);
                }
            }
        }
Exemple #15
0
        void OnServerStateChange(ref HookContext ctx, ref HookArgs.ServerStateChange args)
        {
            ProgramLog.Log("Server state changed to: " + args.ServerChangeState.ToString());

            if (args.ServerChangeState == ServerState.Initialising)
            {
                if (!String.IsNullOrEmpty(RConBindAddress))
                {
                    ProgramLog.Log("Starting RCON Server");
                    RemoteConsole.RConServer.Start(Path.Combine(Globals.DataPath, "rcon_logins.properties"));
                }
            }
            if (args.ServerChangeState == ServerState.Stopping)
            {
                RemoteConsole.RConServer.Stop();
            }

            //if (args.ServerChangeState == ServerState.Initialising)
#if TDSMServer
            if (!Server.IsInitialised)
            {
                Server.Init();

                if (!String.IsNullOrEmpty(RConBindAddress))
                {
                    ProgramLog.Log("Starting RCON Server");
                    RemoteConsole.RConServer.Start(Path.Combine(Globals.DataPath, "rcon_logins.properties"));
                }

                if (!String.IsNullOrEmpty(_webServerAddress))
                {
                    ProgramLog.Log("Starting Web Server");
                    WebInterface.WebServer.Begin(_webServerAddress, _webServerProvider);

                    AddCommand("webauth")
                    .WithAccessLevel(AccessLevel.OP)
                    .Calls(WebInterface.WebServer.WebAuthCommand);
                }
            }

            if (args.ServerChangeState == ServerState.Stopping)
            {
                RemoteConsole.RConServer.Stop();
                WebInterface.WebServer.End();
                //if (properties != null && File.Exists(properties.PIDFile.Trim()))
                //File.Delete(properties.PIDFile.Trim());
            }

            ctx.SetResult(HookResult.IGNORE); //Don't continue on with vanilla code
#endif
        }
Exemple #16
0
        void OnDefaultServerStart(ref HookContext ctx, ref HookArgs.StartDefaultServer args)
        {
            if (RunServerCore)
            {
                ProgramLog.Log("Starting TDSM's slot server...");
                ctx.SetResult(HookResult.IGNORE);

                ServerCore.Server.StartServer();
            }
            else
            {
                ProgramLog.Log("Vanilla only specified, continuing on with Re-Logic code...");
            }
        }
        //private static int _textTimeout = 0;
        public static void OnStatusTextChange()
        {
            try
            {
                /* Check tolled tasks - OnStatusTextChanged is called without clients connected */
                Tasks.CheckTasks(); //This still may not be the best place for this.

#if Full_API
                if (Terraria.Main.oldStatusText != Terraria.Main.statusText)
                {
                    if (StatusTextChange != null)
                    {
                        StatusTextChange();
                    }
                    else
                    {
                        Terraria.Main.oldStatusText = Terraria.Main.statusText;
                        Tools.WriteLine(Terraria.Main.statusText);
                    }

                    /*var ctx = new HookContext()
                     * {
                     * Sender = HookContext.ConsoleSender
                     * };
                     * var args = new HookArgs.StatusTextChanged() { };
                     * HookPoints.StatusTextChanged.Invoke(ref ctx, ref args);
                     *
                     * if (ctx.Result == HookResult.DEFAULT)
                     * {
                     * Terraria.Main.oldStatusText = Terraria.Main.statusText;
                     * Tools.WriteLine(Terraria.Main.statusText);
                     * }*/
                    //_textTimeout = 0;
                }

                //else if (Terraria.Main.oldStatusText == String.Empty && Terraria.Main.statusText == String.Empty)
                //{
                //    if (_textTimeout++ > 1000)
                //    {
                //        _textTimeout = 0;
                //        Terraria.Main.statusText = String.Empty;
                //    }
                //}
                #endif
            }
            catch (Exception e)
            {
                ProgramLog.Log(e, "OnStatusTextChange error");
            }
        }
Exemple #18
0
        public static void Initialize(int maxSlots, int overlimitSlots = 0)
        {
            if (maxSlots < 1)
            {
                maxSlots = 1;
            }
            else if (maxSlots > MAX_SLOTS)
            {
                maxSlots = MAX_SLOTS;
            }

            if (overlimitSlots < 0)
            {
                overlimitSlots = 0;
            }
            else if (overlimitSlots > maxSlots)
            {
                overlimitSlots = maxSlots;
            }

            ProgramLog.Log("{2} {0}+{1} {3}.", maxSlots, overlimitSlots, "Initialising slot server for", "players");

            lock (syncRoot)
            {
                freeSlots.Clear();

                for (int i = maxSlots - 1; i >= 0; i--)
                {
                    isPrivileged[i] = false;
                    freeSlots.Push(i);
                }

                privFreeSlots.Clear();

                for (int i = MAX_SLOTS; i >= maxSlots; i--)
                {
                    isPrivileged[i] = true;
                    privFreeSlots.Push(i);
                }

                for (int q = 0; q < 4; q++)
                {
                    queues[q] = new Queue();
                }

                privSlotsInUse             = 0;
                SlotManager.maxSlots       = maxSlots;
                SlotManager.overlimitSlots = overlimitSlots;
            }
        }
Exemple #19
0
        //		public void ProcessSideBuffer ()
        //		{
        //			DecodeMessages (sideBuffer, ref sideBytes, ref sideLength);
        //			sideBuffer = null;
        //			sideBytes = 0;
        //			sideLength = 0;
        //		}

        protected override void ProcessRead()
        {
            //ProgramLog.Log ("Read (total={0}).", recvBytes);
            try
            {
                DecodeMessages(recvBuffer, ref recvBytes, ref messageLength);
            }
            catch (Exception e)
            {
                ProgramLog.Log("Error processing read from client {0} @ {1}\n{2}", RemoteAddress, assignedSlot, e);
                Kick("Server malfunction, please reconnect.");
            }
            //ProgramLog.Log ("After read (total={0}).", recvBytes);
        }
Exemple #20
0
        static NewNetMessage TakeSectionBuffer()
        {
            lock (sectionPool)
            {
                if (sectionPool.Count > 0)
                {
                    return(sectionPool.Pop());
                }
                sectionPoolCount += 1;
            }

            ProgramLog.Log("Section pool capacity: {0}", sectionPoolCount);
            return(new NewNetMessage(272250));
        }
Exemple #21
0
        /// <summary>
        /// Notifies all ops.
        /// </summary>
        /// <param name="message">Message.</param>
        /// <param name="writeToConsole">If set to <c>true</c> write to console.</param>
        public static void NotifyAllOps(string message, bool writeToConsole = true) //, SendingLogger Logger = SendingLogger.CONSOLE)
        {
            foreach (var player in Main.player)
            {
                if (player != null && player.active && player.IsOp())
                {
                    NetMessage.SendData((int)Packet.PLAYER_CHAT, player.whoAmI, -1, message, 255 /* PlayerId */, 176f, 196, 222f);
                }
            }

            if (writeToConsole)
            {
                ProgramLog.Log(message);
            }
        }
Exemple #22
0
        void ProcessPIDFile(string pidPath)
        {
            var PIDFile = pidPath.Trim();

            if (PIDFile.Length > 0)
            {
                string ProcessUID = Process.GetCurrentProcess().Id.ToString();
                bool   fail       = false;
                if (File.Exists(PIDFile))
                {
                    try
                    {
                        File.Delete(PIDFile);
                    }
                    catch (Exception e)
                    {
                        ProgramLog.Log(e);
                        ProgramLog.Console.Print("Issue deleting PID file, Continue? [Y/n]: ");
                        if (Console.ReadLine().ToLower() == "n")
                        {
                            ProgramLog.Console.Print("Press any key to exit...");
                            Console.ReadKey(true);
                            return;
                        }
                        fail = true;
                    }
                }
                if (!fail)
                {
                    try
                    {
                        File.WriteAllText(PIDFile, ProcessUID);
                    }
                    catch (Exception e)
                    {
                        ProgramLog.Log(e);
                        ProgramLog.Console.Print("Issue writing PID file, Continue? [Y/n]: ");
                        if (Console.ReadLine().ToLower() == "n")
                        {
                            ProgramLog.Console.Print("Press any key to exit...");
                            Console.ReadKey(true);
                            return;
                        }
                    }
                    ProgramLog.Log("PID file successfully created with: " + ProcessUID);
                }
            }
        }
        protected override void OutputThread()
        {
            thread.IsBackground = true;

            try
            {
                int timeout = 20;
                while (state != State.ONLINE)
                {
                    Thread.Sleep(1000);
                    timeout -= 1;
                    if (timeout == 0)
                    {
                        writer.WriteLine("");
                        writer.WriteLine("\x1b[1;37mTimed out.");
                        //socket.SafeShutdown ();
                        Thread.Sleep(250);
                        Close();
                    }
                }

                base.OutputThread();
            }
            catch (IOException e)
            {
                ProgramLog.Debug.Log("{0}: exception while sending ({1})", Id, e.Message);
            }
            catch (SocketException e)
            {
                ProgramLog.Debug.Log("{0}: exception while sending ({1})", Id, e.Message);
            }
            catch (ObjectDisposedException e)
            {
                ProgramLog.Debug.Log("{0}: exception while sending ({1})", Id, e.Message);
            }
            catch (Exception e)
            {
                ProgramLog.Log(e, "Exception within WriteThread of remote console " + Id);
            }

            lock (RConServer.deadClients)
                RConServer.deadClients.Enqueue(this);

            ProgramLog.RemoveTarget(this);

            //socket.SafeShutdown ();
            socket.SafeClose();
        }
        internal void ProcessLine(string line)
        {
            ProgramLog.Admin.Log("Remote command from {0} ({1}): \"{2}\"", Name, remoteAddress, line);

            try
            {
                TDSM.API.Callbacks.UserInput.CommandParser.ParseConsoleCommand(line, this.sender);
            }
            catch (TDSM.API.Misc.ExitException)
            {
            }
            catch (Exception e)
            {
                ProgramLog.Log(e, "Issue parsing remote command from " + Id);
            }
        }
        public static void LoadForAuthenticated(Player player, bool createIfNone = true)
        {
            var ssc = LoadPlayerData(player, createIfNone);

            if (ssc != null)
            {
                //Check to make sure the player is the same player (ie skin, clothes)
                //Add hooks for pre and post apply

                ssc.ApplyToPlayer(player);
            }
            else
            {
                ProgramLog.Log("No SSC data");
            }
        }
Exemple #26
0
 internal bool Disable()
 {
     if (Interlocked.CompareExchange(ref this.enabled, 0, 1) == 1)
     {
         try
         {
             Disabled();
         }
         catch (Exception e)
         {
             ProgramLog.Log(e, "Exception while disabling plugin " + Name);
             return(false);
         }
     }
     return(true);
 }
        internal void ProcessLine(string line)
        {
            ProgramLog.Admin.Log("Remote command from {0} ({1}): \"{2}\"", Name, remoteAddress, line);

            try
            {
                OTA.Commands.CommandManager.Parser.ParseAndProcess(this.sender, line);
            }
            catch (OTA.Misc.ExitException)
            {
            }
            catch (Exception e)
            {
                ProgramLog.Log(e, "Issue parsing remote command from " + Id);
            }
        }
Exemple #28
0
        /*public static BackupResult LoadWorld(string Name)
         * {
         *  WorldIO.LoadWorld(null, null, Statics.WorldPath + Path.DirectorySeparatorChar + Name);
         *
         *  if (WorldModify.loadFailed && !WorldModify.loadSuccess)
         *  {
         *      return BackupResult.LOAD_FAIL;
         *  }
         *
         *  return BackupResult.SUCCESS;
         * }*/

        public static BackupResult Compress(string worldPath)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            ProgramLog.Log("Compressing backup...");

            if (!File.Exists(worldPath))
            {
                ProgramLog.Error.Log("File not Found: " + worldPath);
                return(BackupResult.LOAD_FAIL);
            }

            FileInfo world       = new FileInfo(worldPath);
            String   archivePath = String.Concat(worldPath, ".zip");

            using (FileStream inStream = world.OpenRead())
            {
                using (FileStream outStream = File.Create(archivePath))
                {
                    using (GZipStream alg = new GZipStream(outStream, CompressionMode.Compress))
                    {
                        // copy the input file
                        // into the compression stream
                        inStream.CopyTo(alg);
                    }
                }
            }

            if (File.Exists(archivePath))
            {
                if (File.Exists(worldPath))
                {
                    File.Delete(worldPath);
                }
                stopwatch.Stop();
                ProgramLog.Log("Compression duration: " + stopwatch.Elapsed.Seconds + " Second(s)");
                return(BackupResult.SUCCESS);
            }
            else
            {
                stopwatch.Stop();
                ProgramLog.Error.Log("Compression Failed!");
                return(BackupResult.SAVE_FAIL);
            }
        }
Exemple #29
0
        public static BackupResult Decompress(string archivePath)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            ProgramLog.Log("Decompressing backup...");

            if (!File.Exists(archivePath))
            {
                ProgramLog.Error.Log("File not Found: " + archivePath);
                return(BackupResult.LOAD_FAIL);
            }

            FileInfo archive   = new FileInfo(archivePath);
            string   worldPath = archivePath.Remove(archivePath.Length - archive.Extension.Length);

            using (FileStream inStream = archive.OpenRead())
            {
                using (FileStream outStream = File.Create(worldPath))
                {
                    using (GZipStream alg = new GZipStream(inStream, CompressionMode.Decompress))
                    {
                        // copy the decompressions stream
                        // into the output file
                        alg.CopyTo(outStream);
                    }
                }
            }

            if (File.Exists(worldPath))
            {
                if (File.Exists(archivePath))
                {
                    File.Delete(archivePath);
                }
                stopwatch.Stop();
                ProgramLog.Log("Decompression duration: " + stopwatch.Elapsed.Seconds + " Second(s)");
                return(BackupResult.SUCCESS);
            }
            else
            {
                stopwatch.Stop();
                ProgramLog.Error.Log("Decompression Failed!");
                return(BackupResult.SAVE_FAIL);
            }
        }
        internal static void OnUpdate()
        {
            if (BackupsEnabled && (DateTime.Now - _lastBackup).TotalMinutes >= BackupIntervalMinutes)
            {
                _lastBackup = DateTime.Now;

                try
                {
                    BackupManager.AutoPurge();
                    BackupManager.PerformBackup();
                }
                catch (Exception e)
                {
                    ProgramLog.Log(e, "Error during the backup process");
                }
            }
        }