Beispiel #1
0
        /// <summary>
        /// Write the text representation of the specified array of objects to
        /// server log agent using the specified format information.
        /// </summary>
        /// <param name="display">Shall the representation be displayed in the console window.</param>
        /// <param name="format">A composite format string.</param>
        /// <param name="arg">An array of objects to write using format.</param>
        public void WriteLine(bool display, string format, params object[] arg)
        {
            string str;
            string timestamp;

            if (FirstTime)
            {
                timestamp = string.Format("{0}+0", BeginTime.ToString("HH:mm:ss.fff")); FirstTime = false;
            }
            else
            {
                timestamp = GetTime(BeginTime);
            }

            if (timestamp.Length < 20)            //15:55:58.283+7600010 = 20 character long
            {
                str = string.Format("{0}+0\t\t{1}", BeginTime.ToString("HH:mm:ss.fff"), string.Format(format, arg));
                LogAgent.WriteLine(str, display, false);
                str = string.Format("{0}+0\t{1}", BeginTime.ToString("HH:mm:ss.fff"), string.Format(format, arg));
                LogAgent.WriteLine(str, false, true);
            }
            else
            {
                str = string.Format("{0}\t{1}", GetTime(BeginTime), string.Format(format, arg));
                LogAgent.WriteLine(str, display);
            }
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            Console.Title = "WebOne";
            Console.WriteLine("WebOne HTTP Proxy Server {0}\n(C) https://github.com/atauenis/webone\n\n", Assembly.GetExecutingAssembly().GetName().Version);

            //process command line arguments
            ProcessCommandLine(args);
            ConfigFileName = GetConfigurationFileName();

            //load configuration file and set port number
            if (Port < 1)
            {
                Port = ConfigFile.Port;
            }
            else
            {
                ConfigFile.Port = Port;
            }

            //process remaining command line arguments and override configuration file options
            ProcessCommandLineOptions();

            //enable log
            if (!ConfigFile.HaveLogFile)
            {
                LogAgent.OpenLogFile(null);
            }

            ServicePointManager.DefaultConnectionLimit = int.MaxValue;
            //https://qna.habr.com/q/696033
            //https://github.com/atauenis/webone/issues/2

            Console.Title = "WebOne @ " + ConfigFile.DefaultHostName + ":" + ConfigFile.Port;

            try
            {
                new HTTPServer(ConfigFile.Port);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Cannot start server: {0}!", ex.Message);
                                #if DEBUG
                throw;
                                #endif
            }

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
Beispiel #3
0
        /// <summary>
        /// Write the text representation of the specified array of objects to
        /// server log agent using the specified format information.
        /// </summary>
        /// <param name="display">Shall the representation be displayed in the console window.</param>
        /// <param name="format">A composite format string.</param>
        /// <param name="arg">An array of objects to write using format.</param>
        public void WriteLine(bool display, bool displayTimestamp, string format, params object[] arg)
        {
            string str;
            string timestamp;
            string message = string.Format(format, arg);

            if (FirstTime)
            {
                timestamp = string.Format("{0}+0", BeginTime.ToString("dd.MM.yyyy HH:mm:ss.fff")); FirstTime = false;
            }
            else
            {
                timestamp = GetTime(BeginTime);
            }

            if (displayTimestamp)            //e.g. ">GET http://example.com/ (127.0.0.1)"
            {
                if (timestamp.Length < 20)   //23.02.2021 15:55:58.283+7600010 = 31 character long
                {
                    str = string.Format("{0}+0\t\t{1}", BeginTime.ToString("dd.MM.yyyy HH:mm:ss.fff"), message);
                    LogAgent.WriteLine(str, display, false);
                    str = string.Format("{0}+0\t{1}", BeginTime.ToString("dd.MM.yyyy HH:mm:ss.fff"), message);
                    LogAgent.WriteLine(str, false, true);
                }
                else
                {
                    str = string.Format("{0}\t{1}", GetTime(BeginTime), message);
                    LogAgent.WriteLine(str, true, display);
                }
            }

            else             //e.g. "Starting server..."
            {
                str = string.Format("{0}+0\t{1}", BeginTime.ToString("dd.MM.yyyy HH:mm:ss.fff"), message);

                LogAgent.WriteLine(str, display, true, message);
                return;
            }
        }
Beispiel #4
0
        static ConfigFile()
        {
            //ConfigFileName = "webone.conf";
            Console.WriteLine("Using configuration file {0}.", ConfigFileName);
            int i = 0;

            try
            {
                if (!File.Exists(ConfigFileName))
                {
                    Console.WriteLine("{0}: no such config file. Using defaults.", ConfigFileName); return;
                }
                ;

                string[] CfgFile = System.IO.File.ReadAllLines(ConfigFileName);
                string   Section = "";
                for (i = 0; i < CfgFile.Count(); i++)
                {
                    try
                    {
                        if (CfgFile[i] == "")
                        {
                            continue;                                           //empty lines
                        }
                        if (CfgFile[i].StartsWith(";"))
                        {
                            continue;                                           //comments
                        }
                        if (CfgFile[i].StartsWith("["))                         //section
                        {
                            Section = CfgFile[i].Substring(1, CfgFile[i].Length - 2);
                            StringListConstructor.Clear();

                            if (Section.StartsWith("FixableURL:"))
                            {
                                FixableURLs.Add(Section.Substring(11));
                                FixableUrlActions.Add(Section.Substring(11), new Dictionary <string, string>());
                            }

                            if (Section.StartsWith("FixableType:"))
                            {
                                FixableTypes.Add(Section.Substring(12));
                                FixableTypesActions.Add(Section.Substring(12), new Dictionary <string, string>());
                            }

                            if (Section.StartsWith("ContentPatch:"))
                            {
                                ContentPatches.Add(Section.Substring(13));
                                ContentPatchActions.Add(Section.Substring(13), new Dictionary <string, string>());
                            }

                            if (Section.StartsWith("ContentPatchFind:"))
                            {
                                Console.WriteLine("Warning: ContentPatchFind sections are no longer supported. See wiki.");
                            }

                            if (Section.StartsWith("Edit:"))
                            {
                                LastRawEditSet++;
                                RawEditSets.Add(new List <string>());
                                RawEditSets[LastRawEditSet].Add("OnUrl=" + Section.Substring("Edit:".Length));
                            }

                            if (Section == "Edit")
                            {
                                LastRawEditSet++;
                                RawEditSets.Add(new List <string>());
                            }

                            continue;
                        }


                        //Console.WriteLine(Section);
                        if (Program.CheckString(Section, SpecialSections))                         //special sections (patterns, lists, etc)
                        {
                            //Console.WriteLine("{0}+={1}", Section, CfgFile[i]);
                            switch (Section)
                            {
                            case "ForceHttps":
                                StringListConstructor.Add(CfgFile[i]);
                                ForceHttps = StringListConstructor.ToArray();
                                continue;

                            case "TextTypes":
                                StringListConstructor.Add(CfgFile[i]);
                                TextTypes = StringListConstructor.ToArray();
                                continue;

                            case "ForceUtf8":
                                StringListConstructor.Add(CfgFile[i]);
                                ForceUtf8 = StringListConstructor.ToArray();
                                continue;

                            case "InternalRedirectOn":
                                StringListConstructor.Add(CfgFile[i]);
                                InternalRedirectOn = StringListConstructor.ToArray();
                                continue;

                            case "Converters":
                                Converters.Add(new Converter(CfgFile[i]));
                                continue;

                            default:
                                Console.WriteLine("Warning: The special section {0} is not implemented in this build.", Section);
                                continue;
                            }
                            //continue; //statement cannot be reached
                        }

                        int BeginValue = CfgFile[i].IndexOf("=");                        //regular sections
                        if (BeginValue < 1)
                        {
                            continue;                                         //bad line
                        }
                        string ParamName  = CfgFile[i].Substring(0, BeginValue);
                        string ParamValue = CfgFile[i].Substring(BeginValue + 1);
                        //Console.WriteLine("{0}.{1}={2}", Section, ParamName, ParamValue);

                        //Console.WriteLine(Section);
                        if (Section.StartsWith("FixableURL"))
                        {
                            //Console.WriteLine("URL Fix rule: {0}/{1} = {2}",Section.Substring(11),ParamName,ParamValue);
                            FixableUrlActions[Section.Substring(11)].Add(ParamName, ParamValue);
                            continue;
                        }

                        if (Section.StartsWith("FixableType"))
                        {
                            FixableTypesActions[Section.Substring(12)].Add(ParamName, ParamValue);
                            continue;
                        }

                        if (Section.StartsWith("ContentPatch:"))
                        {
                            if (!ContentPatches.Contains(Section.Substring(13)))
                            {
                                ContentPatches.Add(Section.Substring(13));
                            }
                            ContentPatchActions[Section.Substring(13)].Add(ParamName, ParamValue);
                            continue;
                        }

                        if (Section.StartsWith("Edit:"))
                        {
                            if (RawEditSets.Count > 0)
                            {
                                RawEditSets[LastRawEditSet].Add(CfgFile[i]);
                            }
                            continue;
                        }

                        switch (Section)
                        {
                        case "Server":
                            switch (ParamName)
                            {
                            case "Port":
                                Port = Convert.ToInt32(ParamValue);
                                break;

                            case "OutputEncoding":
                                if (ParamValue == "Windows" || ParamValue == "Win" || ParamValue == "ANSI")
                                {
                                    //OutputEncoding = Encoding.Default; //.NET 4.0
                                    OutputEncoding = CodePagesEncodingProvider.Instance.GetEncoding(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ANSICodePage);
                                    continue;
                                }
                                else if (ParamValue == "DOS" || ParamValue == "OEM")
                                {
                                    OutputEncoding = CodePagesEncodingProvider.Instance.GetEncoding(System.Globalization.CultureInfo.CurrentCulture.TextInfo.OEMCodePage);
                                    continue;
                                }
                                else if (ParamValue == "Mac" || ParamValue == "Apple")
                                {
                                    OutputEncoding = CodePagesEncodingProvider.Instance.GetEncoding(System.Globalization.CultureInfo.CurrentCulture.TextInfo.MacCodePage);
                                    continue;
                                }
                                else if (ParamValue == "EBCDIC" || ParamValue == "IBM")
                                {
                                    OutputEncoding = CodePagesEncodingProvider.Instance.GetEncoding(System.Globalization.CultureInfo.CurrentCulture.TextInfo.EBCDICCodePage);
                                    continue;
                                }
                                else if (ParamValue == "0" || ParamValue == "AsIs")
                                {
                                    OutputEncoding = null;
                                    continue;
                                }
                                else
                                {
                                    try
                                    {
                                        //OutputEncoding = Encoding.GetEncoding(ParamValue);
                                        OutputEncoding = CodePagesEncodingProvider.Instance.GetEncoding(ParamValue);
                                        if (OutputEncoding == null)
                                        {
                                            try { OutputEncoding = CodePagesEncodingProvider.Instance.GetEncoding(int.Parse(ParamValue)); } catch { }
                                        }

                                        if (OutputEncoding == null && ParamValue.ToLower().StartsWith("utf"))
                                        {
                                            switch (ParamValue.ToLower())
                                            {
                                            case "utf-7":
                                                OutputEncoding = Encoding.UTF7;
                                                break;

                                            case "utf-8":
                                                OutputEncoding = Encoding.UTF8;
                                                break;

                                            case "utf-16":
                                            case "utf-16le":
                                                OutputEncoding = Encoding.Unicode;
                                                break;

                                            case "utf-16be":
                                                OutputEncoding = Encoding.BigEndianUnicode;
                                                break;

                                            case "utf-32":
                                            case "utf-32le":
                                                OutputEncoding = Encoding.UTF32;
                                                break;
                                            }
                                        }

                                        if (OutputEncoding == null)
                                        {
                                            Console.WriteLine("Warning: Unknown codepage {0}, using AsIs. See MSDN 'Encoding.GetEncodings Method' article for list of valid encodings.", ParamValue);
                                        }
                                        ;
                                    }
                                    catch (ArgumentException) { Console.WriteLine("Warning: Bad codepage {0}, using {1}. Get list of available encodings at http://{2}:{3}/!codepages/.", ParamValue, OutputEncoding.EncodingName, ConfigFile.DefaultHostName, Port); }
                                }
                                continue;

                            case "Authenticate":
                                Authenticate = ParamValue;
                                continue;

                            case "HideClientErrors":
                                HideClientErrors = ToBoolean(ParamValue);
                                continue;

                            case "SearchInArchive":
                                SearchInArchive = ToBoolean(ParamValue);
                                continue;

                            case "ShortenArchiveErrors":
                                ShortenArchiveErrors = ToBoolean(ParamValue);
                                continue;

                            case "SecurityProtocols":
                                try { System.Net.ServicePointManager.SecurityProtocol = (System.Net.SecurityProtocolType)(int.Parse(ParamValue)); }
                                catch (NotSupportedException) { Console.WriteLine("Warning: Bad TLS version {1} ({0}), using {2} ({2:D}).", ParamValue, (System.Net.SecurityProtocolType)(int.Parse(ParamValue)), System.Net.ServicePointManager.SecurityProtocol); };
                                continue;

                            case "UserAgent":
                                UserAgent = ParamValue;
                                continue;

                            case "DefaultHostName":
                                DefaultHostName = ParamValue.Replace("%HostName%", Environment.MachineName);
                                bool ValidHostName = (Environment.MachineName.ToLower() == DefaultHostName.ToLower());
                                if (!ValidHostName)
                                {
                                    foreach (System.Net.IPAddress LocIP in Program.GetLocalIPAddresses())
                                    {
                                        if (LocIP.ToString() == DefaultHostName)
                                        {
                                            ValidHostName = true;
                                        }
                                    }
                                }
                                if (!ValidHostName)
                                {
                                    try { if (System.Net.Dns.GetHostEntry(DefaultHostName).AddressList.Count() > 0)
                                          {
                                              ValidHostName = true;
                                          }
                                    } catch { }
                                }
                                if (!ValidHostName)
                                {
                                    Console.WriteLine("Warning: DefaultHostName setting is not applicable to this computer!");
                                }
                                continue;

                            case "ValidateCertificates":
                                ValidateCertificates = ToBoolean(ParamValue);
                                continue;

                            case "TemporaryDirectory":
                                if (ParamValue.ToUpper() == "%TEMP%" || ParamValue == "$TEMP" || ParamValue == "$TMPDIR")
                                {
                                    TemporaryDirectory = Path.GetTempPath();
                                }
                                else
                                {
                                    TemporaryDirectory = ParamValue;
                                }
                                continue;

                            case "LogFile":
                                LogAgent.OpenLogFile(GetLogFilePath(ParamValue), false);
                                HaveLogFile = true;
                                continue;

                            case "AppendLogFile":
                                LogAgent.OpenLogFile(GetLogFilePath(ParamValue), true);
                                HaveLogFile = true;
                                continue;

                            default:
                                Console.WriteLine("Warning: Unknown server option: " + ParamName);
                                break;
                            }
                            break;

                        case "Edit":
                            if (RawEditSets.Count > 0)
                            {
                                RawEditSets[LastRawEditSet].Add(CfgFile[i]);
                            }
                            break;

                        case "Translit":
                            TranslitTable.Add(new KeyValuePair <string, string>(ParamName, ParamValue));
                            break;

                        default:
                            Console.WriteLine("Warning: Unknown section: " + Section);
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error on line {1}: {0}", ex.Message, i);
#if DEBUG
                        Console.WriteLine("All next lines will be ignored. Invoking debugging.");
                        throw;
#endif
                    }
                }

                i++;
                foreach (List <string> RawEdit in RawEditSets)
                {
                    EditRules.Add(new EditSet(RawEdit));
                }

                AddLegacyFixableURLs();
                AddLegacyFixableTypes();
                AddLegacyContentPatches();
            }
            catch (Exception ex) {
                                #if DEBUG
                Console.WriteLine("Error in configuration file: {0}. Line {1}. Go to debugger.", ex.ToString(), i);
                throw;
                                #else
                Console.WriteLine("Error in configuration file: {0}.\nAll next lines after {1} are ignored.", ex.Message, i);
                                #endif
            }

            if (i < 1)
            {
                Console.WriteLine("Warning: curiously short file. Probably line endings are not valid for this OS.");
            }
            Console.WriteLine("{0} load complete.", ConfigFileName);
        }
Beispiel #5
0
        static void Main(string[] args)
        {
            Console.Title = "WebOne";
            Console.WriteLine("WebOne HTTP Proxy Server {0}\n(C) https://github.com/atauenis/webone\n\n", Assembly.GetExecutingAssembly().GetName().Version);

            //process command line arguments
            ProcessCommandLine(args);
            ConfigFileName = GetConfigurationFileName();

            //load configuration file and set port number
            try
            {
                ConfigFileLoader.LoadFile(GetConfigurationFileName());
                ConfigFileLoader.ProcessConfiguration();
                if (Port < 1)
                {
                    Port = ConfigFile.Port;
                }
                else
                {
                    ConfigFile.Port = Port;
                }
            }
            catch (Exception ConfigLoadException)
            {
                Console.WriteLine("Error while loading configuration: {0}", ConfigLoadException.Message);
                if (!DaemonMode)
                {
                    Console.WriteLine("\nPress any key to exit.");
                    Console.ReadKey();
                }
                Log.WriteLine(false, false, "WebOne has been exited due to lack of configuration.");
                return;
            }

            //process remaining command line arguments and override configuration file options
            ProcessCommandLineOptions();

            //if log is not declared, say "Not using log file"
            if (OverrideLogFile == null)
            {
                LogAgent.OpenLogFile(null);
            }

            //check for --daemon mode
            if (DaemonMode)
            {
                if (!LogAgent.IsLoggingEnabled)
                {
                    Console.WriteLine("Error: log file is not available, please fix the problem. Exiting.");
                    return;
                }
                Console.Title = "WebOne (silent) @ " + ConfigFile.DefaultHostName + ":" + ConfigFile.Port;
                Console.WriteLine("The proxy runs in daemon mode. See all messages in the log file.");
            }

            ServicePointManager.DefaultConnectionLimit = int.MaxValue;
            //https://qna.habr.com/q/696033
            //https://github.com/atauenis/webone/issues/2

            //set console window title
            if (!DaemonMode)
            {
                Console.Title = "WebOne @ " + ConfigFile.DefaultHostName + ":" + ConfigFile.Port;
            }

            Log.WriteLine(false, false, "Configured to http://{1}:{2}/, HTTP 1.0", ConfigFileName, ConfigFile.DefaultHostName, ConfigFile.Port);
            HTTPS = new HTTPServer(ConfigFile.Port);

            //start the server from 1 or 2 attempts
            for (int StartAttempts = 0; StartAttempts < 2; StartAttempts++)
            {
                try
                {
                    HTTPS.Start();
                    break;
                }
                catch (HttpListenerException ex)
                {
                    Log.WriteLine(true, false, "Cannot start server: {0}", ex.Message);

                    if (!DaemonMode && ex.NativeErrorCode == 5)
                    {
                        //access (for listen TCP port) denied, show troubleshooting help
                        if (ex.NativeErrorCode == 5 && Environment.OSVersion.Platform == PlatformID.Unix)                         //access denied @ *nix
                        {
                            Console.WriteLine();
                            Console.WriteLine(@"You need to use ""sudo WebOne"" or use Port greater than 1024.");
                            Shutdown(ex.NativeErrorCode);
                            break;
                        }
                        if (ex.NativeErrorCode == 5 && Environment.OSVersion.Platform == PlatformID.Win32NT && StartAttempts == 0)                         //access denied @ Win32
                        {
                            Console.WriteLine();
                            Console.WriteLine("Seems that Windows has been blocked running WebOne with non-admin rights.");
                            Console.WriteLine("Read more in project's wiki:");
                            Console.WriteLine("https://github.com/atauenis/webone/wiki/Windows-installation#how-to-run-without-admin-privileges");
                            Console.Write("Do you want to add a Windows Network Shell rule to run WebOne with user rights? (Y/N)");
                            if (Console.ReadKey().Key == ConsoleKey.Y)
                            {
                                ConfigureWindowsNetShell(Port);
                                continue;
                            }
                            else
                            {
                                Shutdown(ex.NativeErrorCode);
                                break;
                            }
                        }
                    }
                    Shutdown(ex.NativeErrorCode);
                    break;
                }
                catch (Exception ex)
                {
                    Log.WriteLine(true, false, "Server start failed: {0}", ex.Message);
                    Shutdown(ex.HResult);
                    break;
                }
            }

            //register Ctrl+C/kill handler
            System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += (ctx) => { Shutdown(); };
            Console.CancelKeyPress += (s, e) => { Shutdown(); };

            //wait while server is in work
            while (HTTPS.Working)
            {
                Thread.Sleep(250);
            }

            //the end
            Shutdown();
        }
Beispiel #6
0
        /// <summary>
        /// Process command line arguments
        /// </summary>
        /// <param name="args">Array of WebOne.exe startup arguments</param>
        private static void ProcessCommandLine(string[] args)
        {
            string ArgName  = CmdLineArgUnnamed;
            string ArgValue = "";
            List <KeyValuePair <string, string> > Args = new List <KeyValuePair <string, string> >();

            KeyValuePair <string, string> LastArg = new KeyValuePair <string, string>();
            bool LastWasValue = false;

            foreach (string arg in args)
            {
                if (arg.StartsWith("-") || arg.StartsWith("/"))
                {
                    LastWasValue = false;
                    LastArg      = new KeyValuePair <string, string>(ArgName, ArgValue);
                    Args.Add(LastArg);

                    ArgName  = arg;
                    ArgValue = "";
                    continue;
                }
                else
                {
                    if (LastWasValue)
                    {
                        LastArg = new KeyValuePair <string, string>(ArgName, ArgValue);
                        Args.Add(LastArg);
                    }
                    ArgValue     = arg;
                    LastWasValue = true;
                    continue;
                }
            }
            LastArg = new KeyValuePair <string, string>(ArgName, ArgValue);
            Args.Add(LastArg);

            foreach (KeyValuePair <string, string> kvp in Args)
            {
                CmdLineOptions.Add(kvp);
                //Console.WriteLine("Arg: '{0}' = '{1}'", kvp.Key, kvp.Value);
                switch (kvp.Key)
                {
                case "/l":
                case "-l":
                case "--log":
                    if (kvp.Value == "" || kvp.Value == "no")
                    {
                        OverrideLogFile = null; break;
                    }
                    OverrideLogFile = kvp.Value;
                    LogAgent.OpenLogFile(OverrideLogFile);
                    break;

                case "/t":
                case "-t":
                case "--tmp":
                case "--temp":
                case "/p":
                case "-p":
                case "--port":
                case "--http-port":
                case "/h":
                case "-h":
                case "--host":
                case "--hostname":
                case "/a":
                case "-a":
                case "--proxy-authenticate":
                case "--dump-headers":
                case "--dump-requests":
                    //will be processed in ProcessCommandLineOptions()
                    break;

                case "--daemon":
                    DaemonMode = true;
                    break;

                case "--help":
                case "-?":
                case "/?":
                    Console.WriteLine("All command line arguments can be found in WebOne Wiki:");
                    Console.WriteLine("https://github.com/atauenis/webone/wiki");
                    Console.WriteLine();
                    Console.WriteLine("Initially made by Alexander Tauenis. Moscow, Russian Federation.");
                    Environment.Exit(0);
                    break;

                case CmdLineArgUnnamed:
                    if (kvp.Value == string.Empty)
                    {
                        break;
                    }
                    try { Port = Convert.ToInt32(kvp.Value); Console.WriteLine("Using custom port {0}.", Port); }
                    catch { ConfigFileName = kvp.Value; }
                    break;

                default:
                    Console.WriteLine("Unknown command line argument: {0}.", kvp.Key);
                    break;
                }
            }
        }
Beispiel #7
0
        /// <summary>
        /// Parse loaded configuration files (RawEntries) and load them to ConfigFile properties
        /// </summary>
        public static void ProcessConfiguration()
        {
            foreach (KeyValuePair <string, string> entry in RawEntries)
            {
                if (entry.Value.StartsWith('['))
                {
                    //section title
                    RawSections.Add(new ConfigFileSection(entry.Value, entry.Key));
                }
                else
                {
                    //section value
                    if (RawSections.Count > 0)
                    {
                        RawSections[RawSections.Count - 1].Options.Add(new ConfigFileOption(entry.Value, entry.Key));
                    }
                    else
                    {
                        throw new Exception("Found option outside section.");
                    }
                }
            }

            foreach (var Section in RawSections)
            {
                switch (Section.Kind)
                {
                case "Server":
                    foreach (ConfigFileOption Option in Section.Options)
                    {
                        switch (Option.Key)
                        {
                        case "Port":
                            ConfigFile.Port = Convert.ToInt32(Option.Value);
                            break;

                        case "OutputEncoding":
                            ConfigFile.OutputEncoding = GetCodePage(Option.Value);
                            break;

                        case "Authenticate":
                            ConfigFile.Authenticate.Add(Option.Value);
                            break;

                        case "AuthenticateMessage":
                            ConfigFile.AuthenticateMessage = Option.Value;
                            break;

                        case "AuthenticateRealm":
                            ConfigFile.AuthenticateRealm = Option.Value;
                            break;

                        case "HideClientErrors":
                            ConfigFile.HideClientErrors = ToBoolean(Option.Value);
                            break;

                        case "SearchInArchive":
                            ConfigFile.SearchInArchive = ToBoolean(Option.Value);
                            break;

                        case "ShortenArchiveErrors":
                            ConfigFile.ShortenArchiveErrors = ToBoolean(Option.Value);
                            break;

                        case "SecurityProtocols":
                            try { System.Net.ServicePointManager.SecurityProtocol = (System.Net.SecurityProtocolType)(int.Parse(Option.Value)); }
                            catch (NotSupportedException) { Log.WriteLine(true, false, "Warning: Bad TLS version {1} ({0}), using {2} ({2:D}).", Option.Value, (System.Net.SecurityProtocolType)(int.Parse(Option.Value)), System.Net.ServicePointManager.SecurityProtocol); };
                            break;

                        case "UserAgent":
                            ConfigFile.UserAgent = Option.Value;
                            break;

                        case "DefaultHostName":
                            ConfigFile.DefaultHostName = Option.Value.Replace("%HostName%", Environment.MachineName);
                            bool ValidHostName = (Environment.MachineName.ToLower() == ConfigFile.DefaultHostName.ToLower());
                            if (!ValidHostName)
                            {
                                foreach (System.Net.IPAddress LocIP in Program.GetLocalIPAddresses())
                                {
                                    if (LocIP.ToString() == ConfigFile.DefaultHostName)
                                    {
                                        ValidHostName = true;
                                    }
                                }
                            }
                            if (!ValidHostName)
                            {
                                try { if (System.Net.Dns.GetHostEntry(ConfigFile.DefaultHostName).AddressList.Count() > 0)
                                      {
                                          ValidHostName = true;
                                      }
                                } catch { }
                            }
                            if (!ValidHostName)
                            {
                                Log.WriteLine(true, false, "Warning: DefaultHostName setting is not applicable to this computer!");
                            }
                            break;

                        case "ValidateCertificates":
                            ConfigFile.ValidateCertificates = ToBoolean(Option.Value);
                            break;

                        case "TemporaryDirectory":
                            if (Option.Value.ToUpper() == "%TEMP%" || Option.Value == "$TEMP" || Option.Value == "$TMPDIR")
                            {
                                ConfigFile.TemporaryDirectory = Path.GetTempPath();
                            }
                            else
                            {
                                ConfigFile.TemporaryDirectory = Option.Value;
                            }
                            break;

                        case "LogFile":
                            if (Program.OverrideLogFile != null && Program.OverrideLogFile == "")
                            {
                                LogAgent.OpenLogFile(Program.GetLogFilePath(Option.Value), false);
                            }
                            break;

                        case "AppendLogFile":
                            if (Program.OverrideLogFile != null && Program.OverrideLogFile == "")
                            {
                                LogAgent.OpenLogFile(Program.GetLogFilePath(Option.Value), true);
                            }
                            break;

                        case "DisplayStatusPage":
                            ConfigFile.DisplayStatusPage = Option.Value;
                            break;

                        default:
                            Log.WriteLine(true, false, "Warning: Unknown server option {0} in {1}.", Option.Key, Option.Location);
                            break;
                        }
                    }
                    break;

                case "ForceHttps":
                    foreach (ConfigFileOption Line in Section.Options)
                    {
                        ConfigFile.ForceHttps.Add(Line.RawString);
                    }
                    break;

                case "TextTypes":
                    foreach (ConfigFileOption Line in Section.Options)
                    {
                        ConfigFile.TextTypes.Add(Line.RawString);
                    }
                    break;

                case "ForceUtf8":
                    foreach (ConfigFileOption Line in Section.Options)
                    {
                        ConfigFile.ForceUtf8.Add(Line.RawString);
                    }
                    break;

                case "InternalRedirectOn":
                    foreach (ConfigFileOption Line in Section.Options)
                    {
                        ConfigFile.InternalRedirectOn.Add(Line.RawString);
                    }
                    break;

                case "Converters":
                    foreach (ConfigFileOption Line in Section.Options)
                    {
                        ConfigFile.Converters.Add(new Converter(Line.RawString));
                    }
                    break;

                case "Edit":
                    ConfigFile.EditRules.Add(new EditSet(Section));
                    break;

                case "Translit":
                    foreach (ConfigFileOption Line in Section.Options)
                    {
                        if (Line.HaveKeyValue)
                        {
                            ConfigFile.TranslitTable.Add(new KeyValuePair <string, string>(Line.Key, Line.Value));
                        }
                    }
                    break;

                case "Authenticate":
                    foreach (ConfigFileOption Line in Section.Options)
                    {
                        if (Line.RawString.Split(":").Length == 2 && !Line.RawString.Contains(" "))
                        {
                            //login:password pair
                            ConfigFile.Authenticate.Add(Line.RawString);
                        }
                        else
                        {
                            //option name/value pair
                            if (Line.HaveKeyValue)
                            {
                                switch (Line.Key)
                                {
                                case "AuthenticateMessage":
                                    ConfigFile.AuthenticateMessage = Line.Value;
                                    break;

                                case "AuthenticateRealm":
                                    ConfigFile.AuthenticateRealm = Line.Value;
                                    break;

                                default:
                                    Log.WriteLine(true, false, "Warning: Invalid authentication option at {0}.", Line.Location);
                                    break;
                                }
                            }
                            else
                            {
                                Log.WriteLine(true, false, "Warning: Invalid authentication credentials at {0}.", Line.Location);
                            }
                        }
                    }
                    break;

                case "FixableURL":
                case "FixableType":
                case "ContentPatch":
                    Log.WriteLine(true, false, "Warning: {0} section at {1} is no longer supported.", Section.Kind, Section.Location);
                    Log.WriteLine(true, false, "See https://github.com/atauenis/webone/wiki/Configuration-file about [{0}].", Section.Kind, Section.Location);
                    break;

                default:
                    Log.WriteLine(true, false, "Warning: Unknown section {0} in {1}.", Section.Kind, Section.Location);
                    break;
                }
            }

            Console.WriteLine("Configuration load complete.");
            foreach (string f in LoadedFiles)
            {
                Log.WriteLine(false, false, "Configuration file {0} load complete.", f);
            }
        }
Beispiel #8
0
        /// <summary>
        /// Process command line options that overrides webone.conf
        /// </summary>
        private static void ProcessCommandLineOptions()
        {
            foreach (KeyValuePair <string, string> kvp in CmdLineOptions)
            {
                try
                {
                    //Console.WriteLine("Opt: '{0}' = '{1}'", kvp.Key, kvp.Value);
                    switch (kvp.Key)
                    {
                    case "/l":
                    case "-l":
                    case "--log":
                        if (kvp.Value == "" || kvp.Value == "no")
                        {
                            ConfigFile.HaveLogFile = false; break;
                        }
                        LogAgent.OpenLogFile(GetLogFilePath(kvp.Value), false);
                        ConfigFile.HaveLogFile = true;
                        break;

                    case "/t":
                    case "-t":
                    case "--tmp":
                    case "--temp":
                        if (kvp.Value.ToUpper() == "%TEMP%" || kvp.Value == "$TEMP" || kvp.Value == "$TMPDIR")
                        {
                            ConfigFile.TemporaryDirectory = Path.GetTempPath();
                        }
                        else
                        {
                            ConfigFile.TemporaryDirectory = kvp.Value;
                        }
                        break;

                    case "/p":
                    case "-p":
                    case "--port":
                    case "--http-port":
                        Port            = Convert.ToInt32(kvp.Value);
                        ConfigFile.Port = Convert.ToInt32(kvp.Value);
                        break;

                    case "/h":
                    case "-h":
                    case "--host":
                    case "--hostname":
                        ConfigFile.DefaultHostName = kvp.Value;
                        break;

                    case "/a":
                    case "-a":
                    case "--proxy-authenticate":
                        ConfigFile.Authenticate = kvp.Value;
                        break;

                    case "--dump-headers":
                        string HdrDmpPath = "dump-hd-%Url%.log";
                        if (kvp.Value != "")
                        {
                            HdrDmpPath = kvp.Value;
                        }

                        Console.WriteLine("Will dump headers to: {0}.", HdrDmpPath);
                        List <string> HdrDumpRule = new List <string>();
                        HdrDumpRule.Add("AddHeaderDumping=" + HdrDmpPath);
                        ConfigFile.EditRules.Add(new EditSet(HdrDumpRule));
                        break;

                    case "--dump-requests":
                        string RqDmpPath = "dump-rq-%Url%.log";
                        if (kvp.Value != "")
                        {
                            RqDmpPath = kvp.Value;
                        }

                        Console.WriteLine("Will dump headers & uploads's bodies to: {0}.", RqDmpPath);
                        List <string> RqDumpRule = new List <string>();
                        RqDumpRule.Add("AddRequestDumping=" + RqDmpPath);
                        ConfigFile.EditRules.Add(new EditSet(RqDumpRule));
                        break;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Warning: Wrong argument '{1} {2}': {0}.", ex.Message, kvp.Key, kvp.Value);
                }
            }
        }