Esempio n. 1
0
        void ReceiveEvent(string data)
        {
            string[] strs = data.Split('\n');

            foreach (string str in strs)
            {
#if DEBUG
                if (m_showOutputDebug)
                {
                    ChiConsole.WriteLineLow("rcv: " + str.Replace("\x1b", "<esc>"));
                }
#endif

                ColorMessage colorMsg = Ansi.ParseAnsi(str, ref m_currentStyle);

                colorMsg = m_baseServicesDispatcher.DispatchReceiveColorMessage(colorMsg);

                if (colorMsg == null)
                {
                    return;
                }

                ChiConsole.WriteLine(colorMsg);
            }
        }
Esempio n. 2
0
    private static void ExactSpellingFalse_NonWindows()
    {
        int intManaged = 1000;
        int intNative  = 2000;

        Console.WriteLine("Method Unicode.Marshal_Int_InOut2: ExactSpelling = false");
        int int5 = intManaged;

        Assert.Throws <EntryPointNotFoundException>(() => Unicode.Marshal_Int_InOut2(int5));

        Console.WriteLine("Method Unicode.MarshalPointer_Int_InOut2: ExactSpelling = false");
        int int6 = intManaged;

        Assert.Throws <EntryPointNotFoundException>(() => Unicode.MarshalPointer_Int_InOut2(ref int6));

        Console.WriteLine("Method Ansi.Marshal_Int_InOut2: ExactSpelling = false");
        int int7 = intManaged;

        Assert.Throws <EntryPointNotFoundException>(() => Ansi.Marshal_Int_InOut2(int7));

        Console.WriteLine("Method Ansi.MarshalPointer_Int_InOut2: ExactSpelling = false");
        int int8 = intManaged;

        Assert.Throws <EntryPointNotFoundException>(() => Ansi.MarshalPointer_Int_InOut2(ref int8));
    }
Esempio n. 3
0
 static void Ansi_ESC6nEvent(object sender, EventArgs e)
 {
     if (_Server.Connected)
     {
         _Server.Write(Ansi.CursorPosition());
     }
 }
Esempio n. 4
0
 static void Ansi_ESC255nEvent(object sender, EventArgs e)
 {
     if (_Server.Connected)
     {
         _Server.Write(Ansi.CursorPosition(Crt.ScreenCols, Crt.ScreenRows));
     }
 }
Esempio n. 5
0
    private static void ExactSpellingTrue()
    {
        int intManaged = 1000;
        int intNative  = 2000;
        int intReturn  = 3000;

        Console.WriteLine("Method Unicode.Marshal_Int_InOut: ExactSpelling = true");
        int int1    = intManaged;
        int intRet1 = Unicode.Marshal_Int_InOut(int1);

        Verify(intReturn, intManaged, intRet1, int1);

        Console.WriteLine("Method Unicode.MarshalPointer_Int_InOut: ExactSpelling = true");
        int int2    = intManaged;
        int intRet2 = Unicode.MarshalPointer_Int_InOut(ref int2);

        Verify(intReturn, intNative, intRet2, int2);

        Console.WriteLine("Method Ansi.Marshal_Int_InOut: ExactSpelling = true");
        int int3    = intManaged;
        int intRet3 = Ansi.Marshal_Int_InOut(int3);

        Verify(intReturn, intManaged, intRet3, int3);

        Console.WriteLine("Method Ansi.MarshalPointer_Int_InOut: ExactSpelling = true");
        int int4    = intManaged;
        int intRet4 = Ansi.MarshalPointer_Int_InOut(ref int4);

        Verify(intReturn, intNative, intRet4, int4);
    }
Esempio n. 6
0
    public static int Main(string[] args)
    {
        int failures   = 0;
        int intManaged = 1000;
        int intNative  = 2000;
        int intReturn  = 3000;

        Console.WriteLine("Method Unicode.Marshal_Int_InOut: ExactSpelling = true");
        int int1    = intManaged;
        int intRet1 = Unicode.Marshal_Int_InOut(int1);

        failures += Verify(intReturn, intManaged, intRet1, int1);

        Console.WriteLine("Method Unicode.MarshalPointer_Int_InOut: ExactSpelling = true");
        int int2    = intManaged;
        int intRet2 = Unicode.MarshalPointer_Int_InOut(ref int2);

        failures += Verify(intReturn, intNative, intRet2, int2);

        Console.WriteLine("Method Ansi.Marshal_Int_InOut: ExactSpelling = true");
        int int3    = intManaged;
        int intRet3 = Ansi.Marshal_Int_InOut(int3);

        failures += Verify(intReturn, intManaged, intRet3, int3);

        Console.WriteLine("Method Ansi.MarshalPointer_Int_InOut: ExactSpelling = true");
        int int4    = intManaged;
        int intRet4 = Ansi.MarshalPointer_Int_InOut(ref int4);

        failures += Verify(intReturn, intNative, intRet4, int4);

        int intReturnAnsi    = 4000;
        int intReturnUnicode = 5000;

        Console.WriteLine("Method Unicode.Marshal_Int_InOut2: ExactSpelling = false");
        int int5    = intManaged;
        int intRet5 = Unicode.Marshal_Int_InOut2(int5);

        failures += Verify(intReturnUnicode, intManaged, intRet5, int5);

        Console.WriteLine("Method Unicode.MarshalPointer_Int_InOut2: ExactSpelling = false");
        int int6    = intManaged;
        int intRet6 = Unicode.MarshalPointer_Int_InOut2(ref int6);

        failures += Verify(intReturnUnicode, intNative, intRet6, int6);

        Console.WriteLine("Method Ansi.Marshal_Int_InOut2: ExactSpelling = false");
        int int7    = intManaged;
        int intRet7 = Ansi.Marshal_Int_InOut2(int7);

        failures += Verify(intReturnAnsi, intManaged, intRet7, int7);

        Console.WriteLine("Method Ansi.MarshalPointer_Int_InOut2: ExactSpelling = false");
        int int8    = intManaged;
        int intRet8 = Ansi.MarshalPointer_Int_InOut2(ref int8);

        failures += Verify(intReturnAnsi, intNative, intRet8, int8);

        return(100 + failures);
    }
Esempio n. 7
0
        public static string Expand(this string input, int length)
        {
            int inputLength = Ansi.Strip(input).Length;

            while (inputLength < length)
            {
                input += ' ';
                inputLength++;
            }

            return(input);
        }
        public void TestFormatterWithoutScope()
        {
            var logger     = new Logger();
            var output     = new SyntheticOutput();
            var dictionary = new Dictionary <string, string> {
                { "1", "first" }, { "2", "second" }
            };

            logger.Outputs.Clear();
            logger.Outputs.Add(output);

            logger.Log("info", dictionary);

            Assert.Equal($"{"[i]".Pastel(Color.Cyan)} { Ansi.Underline("Info").Pastel(Color.Cyan) + "      " } { "1 = first".Pastel(logger.Colors[1]) }", output.Lines[0]);
            Assert.Equal($"             { "  2 = second".Pastel(logger.Colors[1]) }", output.Lines[1]);
        }
Esempio n. 9
0
        private static void InitConsole()
        {
            Crt.SetTitle("GameSrv WFC Screen v" + GameSrv.Version);
            Crt.SetWindowSize(90, 40);
            Crt.HideCursor();
            Crt.ClrScr();

            // WFC Screen
            Ansi.Write(" Last: No callers yet...                                                 ³    RLogin: 0      On: No callers yet...                                                 ³    Telnet: 0    Type: No callers yet...                                                 ³ WebSocket: 0   ÚððStatusððÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³ÃÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÂÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ³ Time: Date: ³ °±²ÛGameSrv WFC Screen v" + GameSrv.Version + " ²±° ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ  Press [F1] For Help or [Q] To Quit");
            Crt.FastWrite(DateTime.Now.ToString(_TimeFormatFooter).ToLower(), 9, 38, Crt.LightGreen);
            Crt.FastWrite(DateTime.Now.ToString("dddd MMMM dd, yyyy"), 23, 38, Crt.LightGreen);

            // Setup scrolling region with a window
            Crt.Window(3, 5, 88, 36);
            Crt.GotoXY(1, 32);
        }
Esempio n. 10
0
        public void Test1()
        {
            var logger = new Logger("");
            var output = new SyntheticOutput();
            var list   = new List <string> {
                "first", "second"
            };

            logger.Outputs.Clear();
            logger.Outputs.Add(output);

            logger.Log("info", list);

            Assert.Equal($"{"[i]".Pastel(Color.Cyan)} { Ansi.Underline("Info").Pastel(Color.Cyan) + "      " } { "first".Pastel(logger.Colors[1]) }", output.Lines[0]);
            Assert.Equal($"             { "  second".Pastel(logger.Colors[1]) }", output.Lines[1]);
        }
Esempio n. 11
0
        string StyleToAnsi(TextStyle style, bool use256)
        {
            StringBuilder esb = new StringBuilder();

            esb.Append("\x1b[0m");

            if (style.IsHighIntensity)
            {
                esb.Append("\x1b[1m");
            }

            if (style.IsReverse)
            {
                esb.Append("\x1b[7m");
            }

            if (!style.Fg.IsEmpty)
            {
                if (use256)
                {
                    esb.Append(Ansi.ColorToAnsiString256(style.Fg, false, style.IsHighIntensity));
                }
                else
                {
                    esb.Append(Ansi.ColorToAnsiString8(style.Fg, false));
                }
            }

            if (!style.Bg.IsEmpty)
            {
                if (use256)
                {
                    esb.Append(Ansi.ColorToAnsiString256(style.Bg, true, false));
                }
                else
                {
                    esb.Append(Ansi.ColorToAnsiString8(style.Bg, true));
                }
            }

            return(esb.ToString());
        }
Esempio n. 12
0
            public MetaData(ColorMessage.MetaData cmMeta)
            {
                m_index   = cmMeta.m_index;
                m_fgColor = cmMeta.m_style.Fg.ToSystemColor();
                if (m_fgColor.IsEmpty)
                {
                    m_fgColor = System.Drawing.Color.FromArgb(160, 160, 160);
                }
                m_bgColor = cmMeta.m_style.Bg.ToSystemColor();
                if (m_bgColor.IsEmpty)
                {
                    m_bgColor = System.Drawing.Color.Black;
                }

                if ((cmMeta.m_style.Flags & TextStyleFlags.HighIntensity) != 0)
                {
                    bool bold;
                    int  c;

                    c = Ansi.ColorToAnsiColor8(Chiroptera.Base.Color.FromSystemColor(m_fgColor), out bold);
                    if (bold == false)
                    {
                        m_fgColor = Ansi.AnsiColor8ToColor(c, true).ToSystemColor();
                    }

                    if (!cmMeta.m_style.Bg.IsEmpty)
                    {
                        c = Ansi.ColorToAnsiColor8(Chiroptera.Base.Color.FromSystemColor(m_bgColor), out bold);
                        if (bold == false)
                        {
                            m_bgColor = Ansi.AnsiColor8ToColor(c, true).ToSystemColor();
                        }
                    }
                }

                if ((cmMeta.m_style.Flags & TextStyleFlags.Inverse) != 0)
                {
                    System.Drawing.Color tmp = m_fgColor;
                    m_fgColor = m_bgColor;
                    m_bgColor = tmp;
                }
            }
Esempio n. 13
0
        public static void Do()
        {
            Console.WriteLine("Generate ANSI table ...");
            var ascii = new Ansi();

            ascii.WriteToFile();
            Console.WriteLine("ANSI table generated.");
            Console.WriteLine("Start encoding " + _fileToCompress + " ...");
            var text    = File.ReadAllText(_fileToCompress);
            var encoder = new LZWEncoder();
            var b       = encoder.EncodeToByteList(text);

            File.WriteAllBytes(_encodedFile, b);
            Console.WriteLine("File " + _fileToCompress + " encoded to " + _encodedFile);
            Console.WriteLine("Start decoding " + _encodedFile);
            var decoder       = new LZWDecoder();
            var bo            = File.ReadAllBytes(_encodedFile);
            var decodedOutput = decoder.DecodeFromCodes(bo);

            File.WriteAllText(_decodedFile, decodedOutput, Encoding.Default);
            Console.WriteLine("File " + _encodedFile + " decoded to " + _decodedFile);
        }
Esempio n. 14
0
        private static void DrawMap()
        {
            // Draw the map
            int BG = 0;
            int FG = 7;

            Door.TextAttr(7);
            Door.ClrScr();
            for (int y = 0; y < 20; y++)
            {
                StringBuilder ToSend = new StringBuilder();

                for (int x = 0; x < 80; x++)
                {
                    MAP_INFO MI = Global.CurrentMap.W[y + (x * 20)];

                    if (BG != MI.BackgroundColour)
                    {
                        ToSend.Append(Ansi.TextBackground(MI.BackgroundColour));
                        Crt.TextBackground(MI.BackgroundColour); // Gotta do this to ensure calls to Ansi.* work right
                        BG = MI.BackgroundColour;
                    }
                    if (FG != MI.ForegroundColour)
                    {
                        ToSend.Append(Ansi.TextColor(MI.ForegroundColour));
                        Crt.TextColor(MI.ForegroundColour); // Gotta do this to ensure calls to Ansi.* work right
                        FG = MI.ForegroundColour;
                    }
                    ToSend.Append(MI.Character.ToString());
                }

                Door.Write(ToSend.ToString());
            }

            // Draw the Global.Player
            DrawPlayer(Global.Player.X, Global.Player.Y);

            // TODO Draw other players
        }
Esempio n. 15
0
    private static void ExactSpellingFalse_Windows()
    {
        int intManaged       = 1000;
        int intNative        = 2000;
        int intReturnAnsi    = 4000;
        int intReturnUnicode = 5000;

        Console.WriteLine("Method Unicode.Marshal_Int_InOut2: ExactSpelling = false");
        int int5    = intManaged;
        int intRet5 = Unicode.Marshal_Int_InOut2(int5);

        Verify(intReturnUnicode, intManaged, intRet5, int5);

        Console.WriteLine("Method Unicode.MarshalPointer_Int_InOut2: ExactSpelling = false");
        int int6    = intManaged;
        int intRet6 = Unicode.MarshalPointer_Int_InOut2(ref int6);

        Verify(intReturnUnicode, intNative, intRet6, int6);

        Console.WriteLine("Method Ansi.Marshal_Int_InOut2: ExactSpelling = false");
        int int7    = intManaged;
        int intRet7 = Ansi.Marshal_Int_InOut2(int7);

        Verify(intReturnAnsi, intManaged, intRet7, int7);

        Console.WriteLine("Method Ansi.MarshalPointer_Int_InOut2: ExactSpelling = false");
        int int8    = intManaged;
        int intRet8 = Ansi.MarshalPointer_Int_InOut2(ref int8);

        Verify(intReturnAnsi, intNative, intRet8, int8);

        Console.WriteLine("Method Auto.Marshal_Int_InOut: ExactSpelling = false. Verify CharSet.Auto behavior per-platform.");
        int int9    = intManaged;
        int intRet9 = Auto.Marshal_Int_InOut2(int9);

        Verify(intReturnUnicode, intManaged, intRet9, int9);
    }
Esempio n. 16
0
        private static void InitConsole()
        {
            if (_FancyOutput)
            {
                //TODO Can do this without System.Windows.Forms reference? Crt.SetIcon(new Icon(Assembly.GetExecutingAssembly().GetManifestResourceStream("GameSrv.GameSrv16+32.ico")).Handle);
                Crt.SetTitle("GameSrv WFC Screen v" + GameSrv.Version);
                Crt.SetWindowSize(90, 40);
                Crt.HideCursor();
                Crt.ClrScr();

                // WFC Screen
                Ansi.Write(" Last: No callers yet...                                                 ³    RLogin: 0      On: No callers yet...                                                 ³    Telnet: 0    Type: No callers yet...                                                 ³ WebSocket: 0   ÚððStatusððÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³³ÃÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÂÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ³ Time: Date: ³ °±²ÛGameSrv WFC Screen v" + GameSrv.Version + " ²±° ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ  Press [F1] For Help or [Q] To Quit");
                Crt.FastWrite(DateTime.Now.ToString(_TimeFormatFooter).ToLower(), 9, 38, Crt.LightGreen);
                Crt.FastWrite(DateTime.Now.ToString("dddd MMMM dd, yyyy"), 23, 38, Crt.LightGreen);

                // Setup scrolling region with a window
                Crt.Window(3, 5, 88, 36);
                Crt.GotoXY(1, 32);
            }
            else
            {
                Crt.ClrScr();
            }
        }
Esempio n. 17
0
 private static string GetVariableBacktickC(string input)
 {
     return(Regex.Replace(input, "`C", Ansi.ClrScr() + "\r\n\r\n", RegexOptions.IgnoreCase));
 }
Esempio n. 18
0
        public void Format(string loglevel, object input)
        {
            lock (_exceptionLock)
            {
                var exception = (Exception)input;
                var type      = exception.GetType();

                _logger.Log(loglevel, $"{type.Name.Pastel(Color.Gray)}: {exception.Message.Replace(Environment.NewLine, " ")}", _logger.Scope);

                if (exception.StackTrace != null)
                {
                    List <string> lines = new List <string>(exception.StackTrace.Contains(Environment.NewLine) ? exception.StackTrace.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.None) : new[] { exception.StackTrace });

                    for (int i = 0; i < lines.Count; i++)
                    {
                        if (lines[i].StartsWith("   at "))
                        {
                            var path = lines[i].Substring(6, lines[i].IndexOf('(') - 6).Split('.');

                            for (int j = 0; j < path.Length; j++)
                            {
                                path[j] = path[j].Pastel(Color.Gray);
                            }

                            int openingBracketIndex = lines[i].IndexOf('(');
                            int closingBracketIndex = lines[i].IndexOf(')');

                            if (openingBracketIndex < closingBracketIndex - 1)
                            {
                                var args = lines[i].Substring(openingBracketIndex + 1, lines[i].Length - (openingBracketIndex + 2)).Split(',');

                                for (int j = 0; j < args.Length; j++)
                                {
                                    var args2 = args[j].Trim().Split(' ');

                                    args[j] = $"{args2[0].Pastel(Color.Gray)} {Ansi.Bold(args2[1])}";
                                }

                                lines[i] = "at ".Pastel(Color.Gray) + String.Join(".", path) + $"({String.Join(", ", args)})";
                            }
                            else
                            {
                                lines[i] = "at ".Pastel(Color.Gray) + String.Join(".", path) + lines[i].Substring(openingBracketIndex, lines[i].Length - openingBracketIndex);
                            }

                            if (lines[i].Contains(" in "))
                            {
                                int index = lines[i].IndexOf(" in ");
                                lines.Insert(i + 1, "    in".Pastel(Color.Gray) + lines[i].Substring(index, lines[i].Length - (index)).Substring(3));

                                int lineIndex = lines[i + 1].IndexOf("line ");
                                lines.Insert(i + 2, "        at ".Pastel(Color.Gray) + lines[i + 1].Substring(lineIndex));
                                lines[i + 1] = lines[i + 1].Substring(0, lineIndex - 1);
                                lines[i]     = lines[i].Substring(0, index);

                                i += 2;
                            }
                        }
                    }

                    for (int i = 0; i < lines.Count; i++)
                    {
                        if (i > 0)
                        {
                            _logger.Log("", "  " + lines[i], _logger.Scope);
                        }
                        else
                        {
                            _logger.Log("stacktrace", lines[i], _logger.Scope);
                        }
                    }
                    ;
                }
            }
        }
Esempio n. 19
0
    public static int Main(string[] args)
    {
        int failures   = 0;
        int intManaged = 1000;
        int intNative  = 2000;
        int intReturn  = 3000;

        Console.WriteLine("Method Unicode.Marshal_Int_InOut: ExactSpelling = true");
        int int1    = intManaged;
        int intRet1 = Unicode.Marshal_Int_InOut(int1);

        failures += Verify(intReturn, intManaged, intRet1, int1);

        Console.WriteLine("Method Unicode.MarshalPointer_Int_InOut: ExactSpelling = true");
        int int2    = intManaged;
        int intRet2 = Unicode.MarshalPointer_Int_InOut(ref int2);

        failures += Verify(intReturn, intNative, intRet2, int2);

        Console.WriteLine("Method Ansi.Marshal_Int_InOut: ExactSpelling = true");
        int int3    = intManaged;
        int intRet3 = Ansi.Marshal_Int_InOut(int3);

        failures += Verify(intReturn, intManaged, intRet3, int3);

        Console.WriteLine("Method Ansi.MarshalPointer_Int_InOut: ExactSpelling = true");
        int int4    = intManaged;
        int intRet4 = Ansi.MarshalPointer_Int_InOut(ref int4);

        failures += Verify(intReturn, intNative, intRet4, int4);

        int intReturnAnsi    = 4000;
        int intReturnUnicode = 5000;

        Console.WriteLine("Method Unicode.Marshal_Int_InOut2: ExactSpelling = false");
        int int5    = intManaged;
        int intRet5 = Unicode.Marshal_Int_InOut2(int5);

        failures += Verify(intReturnUnicode, intManaged, intRet5, int5);

        Console.WriteLine("Method Unicode.MarshalPointer_Int_InOut2: ExactSpelling = false");
        int int6    = intManaged;
        int intRet6 = Unicode.MarshalPointer_Int_InOut2(ref int6);

        failures += Verify(intReturnUnicode, intNative, intRet6, int6);

        Console.WriteLine("Method Ansi.Marshal_Int_InOut2: ExactSpelling = false");
        int int7    = intManaged;
        int intRet7 = Ansi.Marshal_Int_InOut2(int7);

        failures += Verify(intReturnAnsi, intManaged, intRet7, int7);

        Console.WriteLine("Method Ansi.MarshalPointer_Int_InOut2: ExactSpelling = false");
        int int8    = intManaged;
        int intRet8 = Ansi.MarshalPointer_Int_InOut2(ref int8);

        failures += Verify(intReturnAnsi, intNative, intRet8, int8);

        Console.WriteLine("Method Auto.Marshal_Int_InOut: ExactSpelling = false. Verify CharSet.Auto behavior per-platform.");
        int int9    = intManaged;
        int intRet9 = Auto.Marshal_Int_InOut2(int9);

#if TARGET_WINDOWS
        failures += Verify(intReturnUnicode, intManaged, intRet9, int9);
#else
        failures += Verify(intReturnAnsi, intManaged, intRet9, int9);
#endif

        return(100 + failures);
    }
Esempio n. 20
0
        protected override void Execute()
        {
            try {
                // Handle non-proxy connections
                using (WebSocketConnection UserConnection = new WebSocketConnection(true, Config.Default.Certificate)) {
                    if (UserConnection.Open(_Socket))
                    {
                        _RemoteIP = UserConnection.GetRemoteIP();

                        RMLog.Debug("{" + _ConnectionId.ToString() + "} Opened connection from " + UserConnection.GetRemoteIP() + ":" + UserConnection.GetRemotePort());
                        if (UserConnection.Header["Path"] == "/ping")
                        {
                            // Handle ping requests (from proxy.ftelnet.ca most likely)
                            string Ping = UserConnection.ReadLn(1000);
                            if (UserConnection.ReadTimedOut)
                            {
                                RMLog.Debug("Answering a /ping (no time received) from " + UserConnection.GetRemoteIP() + ":" + UserConnection.GetRemotePort());
                            }
                            else
                            {
                                RMLog.Debug("Answering a /ping (" + Ping + ") from " + UserConnection.GetRemoteIP() + ":" + UserConnection.GetRemotePort());
                                UserConnection.Write(Ping);
                            }
                            return;
                        }
                    }
                    else
                    {
                        if (UserConnection.FlashPolicyFileRequest)
                        {
                            RMLog.Info("{" + _ConnectionId.ToString() + "} Answered flash policy file request from " + UserConnection.GetRemoteIP() + ":" + UserConnection.GetRemotePort().ToString());
                        }
                        else
                        {
                            RMLog.Debug("{" + _ConnectionId.ToString() + "} Invalid WebSocket connection from " + UserConnection.GetRemoteIP() + ":" + UserConnection.GetRemotePort().ToString());
                        }
                        return;
                    }

                    // If we get here it's a proxy connection, so handle it
                    RMLog.Info("{" + _ConnectionId.ToString() + "} Connection accepted from " + UserConnection.GetRemoteIP() + ":" + UserConnection.GetRemotePort());

                    string MessageText = string.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\r\n",
                                                       DateTime.Now.ToString(),
                                                       UserConnection.GetRemoteIP(),
                                                       UserConnection.GetRemotePort(),
                                                       UserConnection.Header["Path"],
                                                       UserConnection.Protocol,
                                                       UserConnection.SubProtocol);
                    FileUtils.FileAppendAllText(Path.Combine(ProcessUtils.StartupPath, "fTelnetProxy-Connections.log"), MessageText, Encoding.ASCII);

                    // Defaults for redirect location
                    _Hostname = Config.Default.TargetHostname;
                    _Port     = Config.Default.TargetPort;

                    // Check if user is requesting a custom target
                    if (UserConnection.Header["Path"] != "/")
                    {
                        bool CanRelay = false;

                        // Extract the requested host and port
                        string[] HostAndPort = UserConnection.Header["Path"].Split('/');
                        if ((HostAndPort.Length == 3) && (int.TryParse(HostAndPort[2], out _Port)))
                        {
                            _Hostname = HostAndPort[1];
                            if (Config.Default.TargetHostname.ToLower().Trim() == _Hostname.ToLower().Trim())
                            {
                                // User is requesting the target defined by the proxy admin, so check if it's to an allowed port
                                CanRelay = ((_Port > 0) && (_Port == Config.Default.TargetPort) || (_Port == Config.Default.RLoginPort));
                            }
                            else if (!string.IsNullOrEmpty(Config.Default.RelayFilename))
                            {
                                // proxy admin has relaying enabled, so check against the relay.cfg file
                                try {
                                    // Read relay file
                                    if (File.Exists(Config.Default.RelayFilename))
                                    {
                                        string[] AllowedHosts = File.ReadAllLines(Config.Default.RelayFilename);
                                        if (AllowedHosts.Length > 0)
                                        {
                                            // Check for a whitelisted port
                                            string[] AllowedPorts = AllowedHosts[0].Split(',');
                                            foreach (string AllowedPort in AllowedPorts)
                                            {
                                                if (AllowedPort == _Port.ToString())
                                                {
                                                    CanRelay = true;
                                                    break;
                                                }
                                            }

                                            // Not a whitelisted port, check for a whitelisted host
                                            if (!CanRelay)
                                            {
                                                string RequestedHostPort = _Hostname.ToLower() + ":" + _Port.ToString();
                                                foreach (string AllowedHost in AllowedHosts)
                                                {
                                                    if (AllowedHost.Trim().ToLower() == RequestedHostPort)
                                                    {
                                                        CanRelay = true;
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            RMLog.Error("{" + _ConnectionId.ToString() + "} Relay file is empty: '" + Config.Default.RelayFilename + "'");
                                        }
                                    }
                                    else
                                    {
                                        RMLog.Error("{" + _ConnectionId.ToString() + "} Relay file does not exist: '" + Config.Default.RelayFilename + "'");
                                    }
                                } catch (Exception ex) {
                                    RMLog.Exception(ex, "{" + _ConnectionId.ToString() + "} Error reading relay file: '" + Config.Default.RelayFilename + "'");
                                }
                            }
                        }

                        if (!CanRelay)
                        {
                            RMLog.Info("{" + _ConnectionId.ToString() + "} Rejecting request for " + _Hostname + ":" + _Port.ToString());
                            UserConnection.WriteLn("Sorry, for security reasons this proxy won't connect to " + _Hostname + ":" + _Port.ToString());
                            UserConnection.WriteLn("unless you contact me via the contact form on www.fTelnet.ca.  Just let me");
                            UserConnection.WriteLn("know the hostname and port you're trying to connect to, and I'll add it to");
                            UserConnection.WriteLn("the whitelist for you.");
                            Thread.Sleep(2500);
                            return;
                        }
                    }

                    // Try to connect to the desired Host and Port
                    UserConnection.Write(Ansi.ClrScr() + "Connecting to " + _Hostname + ":" + _Port.ToString() + "...");
                    using (TcpConnection ServerConnection = new TcpConnection()) {
                        if (ServerConnection.Connect(_Hostname, _Port))
                        {
                            RMLog.Info("{" + _ConnectionId.ToString() + "} Connected to " + _Hostname + ":" + _Port.ToString());
                            UserConnection.WriteLn("connected!");

                            // Repeatedly move data around until a connection is closed (or a stop is requested)
                            bool DoSleep = true;
                            while (!_Stop && UserConnection.Connected && ServerConnection.Connected)
                            {
                                DoSleep = true;

                                if (UserConnection.CanRead())
                                {
                                    ServerConnection.WriteBytes(UserConnection.ReadBytes());
                                    _DateLastTX = DateTime.Now;
                                    DoSleep     = false;
                                }

                                if (ServerConnection.CanRead())
                                {
                                    UserConnection.WriteBytes(ServerConnection.ReadBytes(1024)); // 1k at a time to allow non-stop screens to be aborted by user input
                                    _DateLastRX = DateTime.Now;
                                    DoSleep     = false;
                                }

                                if (DoSleep)
                                {
                                    Thread.Sleep(1);
                                }

                                // Check if we should abort due to idle times
                                // TODOX Allow to be customized
                                if (SecondsSinceLastRX > 600)
                                {
                                    // 10 minutes of no server activity
                                    RMLog.Info("{" + _ConnectionId.ToString() + "} Disconnecting after 10 minutes of no activity from server");
                                    UserConnection.Write(Ansi.GotoXY(1, 1) + Ansi.CursorDown(255) + "\r\nDisconnecting after 10 minutes of no activity from server...");
                                    Thread.Sleep(2500);
                                    break;
                                }
                                else if (SecondsSinceLastTX > 600)
                                {
                                    // 10 minutes of no user activity
                                    RMLog.Info("{" + _ConnectionId.ToString() + "} Disconnecting after 10 minutes of no activity from user");
                                    UserConnection.Write(Ansi.GotoXY(1, 1) + Ansi.CursorDown(255) + "\r\nDisconnecting after 10 minutes of no activity from user...");
                                    Thread.Sleep(2500);
                                    break;
                                }
                                else if (SecondsSinceConnecting > 21600)
                                {
                                    // 6 hours since connecting
                                    RMLog.Info("{" + _ConnectionId.ToString() + "} Disconnecting after 6 hours");
                                    UserConnection.Write(Ansi.GotoXY(1, 1) + Ansi.CursorDown(255) + "\r\nDisconnecting after 6 hours...");
                                    Thread.Sleep(2500);
                                    break;
                                }
                            }

                            // Check why we exited the loop
                            if (_Stop)
                            {
                                RMLog.Info("{" + _ConnectionId.ToString() + "} Stop requested");
                                UserConnection.Write(Ansi.GotoXY(1, 1) + Ansi.CursorDown(255) + "\r\nProxy server shutting down...");
                                Thread.Sleep(2500);
                            }
                            else if (!UserConnection.Connected)
                            {
                                RMLog.Info("{" + _ConnectionId.ToString() + "} Client closed connection");
                            }
                            else if (!ServerConnection.Connected)
                            {
                                RMLog.Info("{" + _ConnectionId.ToString() + "} Server closed connection");
                                UserConnection.Write(Ansi.GotoXY(1, 1) + Ansi.CursorDown(255) + "\r\nServer closed connection...");
                                Thread.Sleep(2500);
                            }
                        }
                        else
                        {
                            RMLog.Info("{" + _ConnectionId.ToString() + "} Unable to connect to " + _Hostname + ":" + _Port.ToString());
                            UserConnection.WriteLn("unable to connect!");
                            Thread.Sleep(2500);
                        }
                    }

                    // Display info about the connection we're closing
                    DisplayConnectionInformation();
                }
            } catch (Exception ex) {
                RMLog.Exception(ex, "{" + _ConnectionId.ToString() + "} Exception in client thread");
            }
        }
Esempio n. 21
0
        private void RunScript(string[] script)
        {
            while (_CurrentLineNumber < script.Length)
            {
                string Line        = script[_CurrentLineNumber];
                string LineTrimmed = Line.Trim();

                if (_InCLOSESCRIPT)
                {
                    return;
                }
                else if (_InIFFalse < 999)
                {
                    if (LineTrimmed.StartsWith("@"))
                    {
                        string[] Tokens = LineTrimmed.Split(' ');
                        switch (Tokens[0].ToUpper())
                        {
                        case "@BEGIN":
                            _InBEGINCount += 1;
                            break;

                        case "@END":
                            _InBEGINCount -= 1;
                            if (_InBEGINCount == _InIFFalse)
                            {
                                _InIFFalse = 999;
                            }
                            break;
                        }
                    }
                }
                else
                {
                    if (LineTrimmed.StartsWith("@"))
                    {
                        if (_InBUYMANAGER)
                        {
                            EndBUYMANAGER();
                        }
                        if (_InCHOICE)
                        {
                            EndCHOICE();
                        }
                        if (_InREADFILE != "")
                        {
                            EndREADFILE();
                        }
                        if (_InSELLMANAGER)
                        {
                            EndSELLMANAGER();
                        }
                        if (_InSHOWSCROLL)
                        {
                            EndSHOWSCROLL();
                        }
                        _InBUYMANAGER  = false;
                        _InCHOICE      = false;
                        _InREADFILE    = "";
                        _InSAY         = false;
                        _InSAYBAR      = false;
                        _InSELLMANAGER = false;
                        _InSHOW        = false;
                        _InSHOWLOCAL   = false;
                        _InSHOWSCROLL  = false;
                        _InWRITEFILE   = "";

                        string[] Tokens = LineTrimmed.Split(' ');
                        if (_Commands.ContainsKey(Tokens[0]))
                        {
                            _Commands[Tokens[0]](Tokens);
                        }
                        else
                        {
                            LogMissing(Tokens);
                        }
                    }
                    else
                    {
                        if (_InBUYMANAGER)
                        {
                            _InBUYMANAGEROptions.Add(Line);
                        }
                        else if (_InCHOICE)
                        {
                            _InCHOICEOptions.Add(new RTChoiceOption(Line));
                        }
                        else if (_InDO_ADDLOG)
                        {
                            FileUtils.FileAppendAllText(Global.GetSafeAbsolutePath("LOGNOW.TXT"), RTVariables.TranslateVariables(Line));
                            _InDO_ADDLOG = false;
                        }
                        else if (_InDO_WRITE)
                        {
                            Door.Write(RTVariables.TranslateVariables(Line));
                            _InDO_WRITE = false;
                        }
                        else if (_InFIGHT)
                        {
//                            if ((LineTrimmed <> '') AND NOT(AnsiStartsText(';', LineTrimmed))) then
//begin
//            FInFIGHTLines.Add(Line);
//                            if (FInFIGHTLines.Count = 16) then
//                            begin
//              EndFIGHT;
//                            FInFIGHT:= false;
//                            end;
//                            end;
                        }
                        else if (_InREADFILE != "")
                        {
                            _InREADFILELines.Add(Line);
                        }
                        else if (_InSAY)
                        {
                            // TODO SHould be in TEXT window (but since LORD2 doesn't use @SAY, not a high priority)
                            Door.Write(RTVariables.TranslateVariables(Line));
                        }
                        else if (_InSAYBAR)
                        {
                            EndSAYBAR(Line);
                            _InSAYBAR = false;
                        }
                        else if (_InSELLMANAGER)
                        {
                            _InSELLMANAGEROptions.Add(Line);
                        }
                        else if (_InSHOW)
                        {
                            Door.WriteLn(RTVariables.TranslateVariables(Line));
                        }
                        else if (_InSHOWLOCAL)
                        {
                            Ansi.Write(RTVariables.TranslateVariables(Line) + "\r\n");
                        }
                        else if (_InSHOWSCROLL)
                        {
                            _InSHOWSCROLLLines.Add(RTVariables.TranslateVariables(Line));
                        }
                        else if (_InWRITEFILE != "")
                        {
                            FileUtils.FileAppendAllText(_InWRITEFILE, RTVariables.TranslateVariables(Line) + Environment.NewLine, RMEncoding.Ansi);
                        }
                    }
                }

                _CurrentLineNumber += 1;
            }
        }
Esempio n. 22
0
        protected override void Execute()
        {
            try {
                // Handle non-proxy connections
                using (WebSocketConnection NewConnection = new WebSocketConnection(true, Config.Default.Certificate)) {
                    if (NewConnection.Open(_Socket))
                    {
                        RMLog.Debug("{" + _ConnectionId.ToString() + "} Opened connection from " + NewConnection.GetRemoteIP() + ":" + NewConnection.GetRemotePort());
                        if (NewConnection.Header["Path"] == "/ping")
                        {
                            // Handle ping requests (from proxy.ftelnet.ca most likely)
                            string Ping = NewConnection.ReadLn(1000);
                            if (NewConnection.ReadTimedOut)
                            {
                                RMLog.Debug("Answering a /ping (no time received) from " + NewConnection.GetRemoteIP() + ":" + NewConnection.GetRemotePort());
                            }
                            else
                            {
                                RMLog.Debug("Answering a /ping (" + Ping + ") from " + NewConnection.GetRemoteIP() + ":" + NewConnection.GetRemotePort());
                                NewConnection.Write(Ping);
                            }
                            return;
                        }
                    }
                    else
                    {
                        if (NewConnection.FlashPolicyFileRequest)
                        {
                            RMLog.Info("{" + _ConnectionId.ToString() + "} Answered flash policy file request from " + NewConnection.GetRemoteIP() + ":" + NewConnection.GetRemotePort().ToString());
                        }
                        else
                        {
                            RMLog.Debug("{" + _ConnectionId.ToString() + "} Invalid WebSocket connection from " + NewConnection.GetRemoteIP() + ":" + NewConnection.GetRemotePort().ToString());
                        }
                        return;
                    }

                    // If we get here it's a proxy connection, so handle it
                    RMLog.Info("{" + _ConnectionId.ToString() + "} Connection accepted from " + NewConnection.GetRemoteIP() + ":" + NewConnection.GetRemotePort());

                    string MessageText = string.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\r\n",
                                                       DateTime.Now.ToString(),
                                                       NewConnection.GetRemoteIP(),
                                                       NewConnection.GetRemotePort(),
                                                       NewConnection.Header["Path"],
                                                       NewConnection.Protocol,
                                                       NewConnection.SubProtocol);
                    FileUtils.FileAppendAllText(Path.Combine(ProcessUtils.StartupPath, "fTelnetProxy-Connections.log"), MessageText, Encoding.ASCII);

                    // Defaults for redirect location
                    string Hostname = Config.Default.TargetHostname;
                    int    Port     = Config.Default.TargetPort;

                    // Check if user is requesting a custom target
                    if (NewConnection.Header["Path"] != "/")
                    {
                        bool CanRelay = false;

                        // Extract the requested host and port
                        string[] HostAndPort = NewConnection.Header["Path"].Split('/');
                        if ((HostAndPort.Length == 3) && (int.TryParse(HostAndPort[2], out Port)))
                        {
                            Hostname = HostAndPort[1];
                            if (Config.Default.TargetHostname.ToLower().Trim() == Hostname.ToLower().Trim())
                            {
                                // User is requesting the target defined by the proxy admin, so check if it's to an allowed port
                                CanRelay = ((Port > 0) && (Port == Config.Default.TargetPort) || (Port == Config.Default.RLoginPort));
                            }
                            else if (!string.IsNullOrEmpty(Config.Default.RelayFilename))
                            {
                                // proxy admin has relaying enabled, so check against the relay.cfg file
                                try {
                                    // Read relay file
                                    if (File.Exists(Config.Default.RelayFilename))
                                    {
                                        string[] AllowedHosts = File.ReadAllLines(Config.Default.RelayFilename);
                                        if (AllowedHosts.Length > 0)
                                        {
                                            // Check for a whitelisted port
                                            string[] AllowedPorts = AllowedHosts[0].Split(',');
                                            foreach (string AllowedPort in AllowedPorts)
                                            {
                                                if (AllowedPort == Port.ToString())
                                                {
                                                    CanRelay = true;
                                                    break;
                                                }
                                            }

                                            // Not a whitelisted port, check for a whitelisted host
                                            if (!CanRelay)
                                            {
                                                string RequestedHostPort = Hostname.ToLower() + ":" + Port.ToString();
                                                foreach (string AllowedHost in AllowedHosts)
                                                {
                                                    if (AllowedHost.Trim().ToLower() == RequestedHostPort)
                                                    {
                                                        CanRelay = true;
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            RMLog.Error("{" + _ConnectionId.ToString() + "} Relay file is empty: '" + Config.Default.RelayFilename + "'");
                                        }
                                    }
                                    else
                                    {
                                        RMLog.Error("{" + _ConnectionId.ToString() + "} Relay file does not exist: '" + Config.Default.RelayFilename + "'");
                                    }
                                } catch (Exception ex) {
                                    RMLog.Exception(ex, "{" + _ConnectionId.ToString() + "} Error reading relay file: '" + Config.Default.RelayFilename + "'");
                                }
                            }
                        }

                        if (!CanRelay)
                        {
                            RMLog.Info("{" + _ConnectionId.ToString() + "} Rejecting request for " + Hostname + ":" + Port.ToString());
                            NewConnection.WriteLn("Sorry, for security reasons this proxy won't connect to " + Hostname + ":" + Port.ToString());
                            Thread.Sleep(2500);
                            return;
                        }
                    }

                    // Try to connect to the desired Host and Port
                    NewConnection.Write(Ansi.ClrScr() + "Connecting to " + Hostname + ":" + Port.ToString() + "...");
                    using (TcpConnection _TcpConnection = new TcpConnection()) {
                        if (_TcpConnection.Connect(Hostname, Port))
                        {
                            RMLog.Info("{" + _ConnectionId.ToString() + "} Connected to " + Hostname + ":" + Port.ToString());
                            NewConnection.WriteLn("connected!");

                            // Repeatedly move data around until a connection is closed (or a stop is requested)
                            bool DoSleep = true;
                            while (!_Stop && NewConnection.Connected && _TcpConnection.Connected)
                            {
                                DoSleep = true;

                                if (NewConnection.CanRead())
                                {
                                    _TcpConnection.WriteBytes(NewConnection.ReadBytes());
                                    DoSleep = false;
                                }

                                if (_TcpConnection.CanRead())
                                {
                                    NewConnection.WriteBytes(_TcpConnection.ReadBytes());
                                    DoSleep = false;
                                }

                                if (DoSleep)
                                {
                                    Thread.Sleep(1);
                                }
                            }

                            // Check why we exited the loop
                            if (_Stop)
                            {
                                RMLog.Info("{" + _ConnectionId.ToString() + "} Stop requested");
                                NewConnection.Write(Ansi.GotoXY(1, 1) + Ansi.CursorDown(255) + "\r\nProxy server shutting down...");
                                Thread.Sleep(2500);
                            }
                            else if (!NewConnection.Connected)
                            {
                                RMLog.Info("{" + _ConnectionId.ToString() + "} Client closed connection");
                            }
                            else if (!_TcpConnection.Connected)
                            {
                                RMLog.Info("{" + _ConnectionId.ToString() + "} Server closed connection");
                                NewConnection.Write(Ansi.GotoXY(1, 1) + Ansi.CursorDown(255) + "\r\nServer closed connection...");
                                Thread.Sleep(2500);
                            }
                        }
                        else
                        {
                            RMLog.Info("{" + _ConnectionId.ToString() + "} Unable to connect to " + Hostname + ":" + Port.ToString());
                            NewConnection.WriteLn("unable to connect!");
                            Thread.Sleep(2500);
                        }
                    }
                }
            } catch (Exception ex) {
                RMLog.Exception(ex, "{" + _ConnectionId.ToString() + "} Exception in client thread");
            }
        }