Exemplo n.º 1
0
 static void ServerLoop(ServerFactory factory, ServerParameters parameters)
 {
     while (true)
     {
         RunServer(factory, parameters).Wait();
     }
 }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            var         process  = new Process();
            TcpListener listener = null;

            try
            {
                listener = new TcpListener(IPAddress.Parse(ServerParameters.GetIPAdr()), ServerParameters.GetPort());
                listener.Start();
                Console.WriteLine("Ожидание подключений...");

                while (true)
                {
                    TcpClient client      = listener.AcceptTcpClient();
                    var       userConnect = new UserConnect(client, new TXTTest());

                    //process.AddConnect


                    Thread clientThread = new Thread(new ThreadStart(userConnect.Process));
                    clientThread.Start();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (listener != null)
                {
                    listener.Stop();
                }
            }
        }
Exemplo n.º 3
0
 static async Task RunServer(ServerFactory factory, ServerParameters parameters)
 {
     using (var server = await factory.Start(parameters)) {
         var handler = ConnectionHandlerFactory.Echo.Create(server);
         await handler.Run();
     }
 }
Exemplo n.º 4
0
 public ClientLink(TcpClient tcpC, ServerParameters serverParameters, TopicManager topicManager, PrivateMessageManager privateMessageManager)
 {
     Comm                  = tcpC;
     ServerParameter       = serverParameters;
     TopicManager          = topicManager;
     PrivateMessageManager = privateMessageManager;
 }
Exemplo n.º 5
0
 public WindowDatabaseGenerator(UserControl control, string demoString)
 {
     InitializeComponent();
     DemoString = demoString;
     if (control != null)
     {
         Owner = Window.GetWindow(control);
         WindowStartupLocation = WindowStartupLocation.CenterOwner;
     }
     else
     {
         WindowStartupLocation = WindowStartupLocation.CenterScreen;
     }
     ShowInTaskbar = false;
     btnGenerateDatabase.Content = (string)btnGenerateDatabase.Content + DemoString;
     pbPassword.Password         = ServerParameters.Password;
     pbPassword.PasswordChanged += (s, e) => { ServerParameters.Password = pbPassword.Password; };
     Closed += (s, e) => {
         windowWasClosed = true;
         if (DatabaseHelper.IsGenerating)
         {
             DatabaseHelper.CancelDatabaseGenerationAsync();
         }
         ServerParameters.SaveParameters();
         Mouse.OverrideCursor = null;
     };
 }
Exemplo n.º 6
0
 private static void LogHostInfo(ServerParameters arg, HostConfig config)
 {
     Console.WriteLine("BinRoot: " + config.DllFolder);
     foreach (var assembly in config.AutoconfigureAssemblies)
     {
         arg.Log.Trace("Lib: " + assembly);
     }
     foreach (var hostBinding in config.Bindings)
     {
         arg.Log.Info("Binding: " + hostBinding);
     }
     arg.Log.Trace("RootFolder: " + config.RootFolder);
     foreach (var contentFolder in config.ContentFolders)
     {
         arg.Log.Trace("ContentFolder: " + contentFolder);
     }
     foreach (var map in config.StaticContentMap)
     {
         arg.Log.Trace("Map: " + map.Key + " : " + map.Value);
     }
     foreach (var map in config.Proxize)
     {
         arg.Log.Trace("Proxize: " + map.Key + " : " + map.Value);
     }
     foreach (var e in config.StaticContentCacheMap)
     {
         arg.Log.Trace(e.Value.ToString());
     }
 }
Exemplo n.º 7
0
        public static void Configure(IUnityContainer container, string connectionString)
        {
            var sqlConnection = new SqlConnection(connectionString);

            sqlConnection.Open();

            var parameters = new ServerParameters
            {
                SqlConnection = connectionString
            };

            container.RegisterInstance <ServerParameters>(parameters);
            container.RegisterInstance <IClientManager>(new ClientManager());
            container.RegisterInstance <IClientChecker>(new ClientChecker(sqlConnection));

            container.RegisterType <IClient, Client>();

            container.RegisterType <IPacketParser, PacketParser>();
            container.RegisterType <IStreamParser, StreamParser>();

            container.RegisterInstance <ICacher <LevelData> >(new LevelCacher(parameters));
            container.RegisterInstance <ICacher <PingData> >(new PingCacher(parameters));

            container.RegisterType <ILocalParser, PingParser>("ping", new HierarchicalLifetimeManager());
            container.RegisterType <ILocalParser, LevelParser>("level", new HierarchicalLifetimeManager());
        }
Exemplo n.º 8
0
        private static void EnsureRequiredApplications(ServerParameters serverParameters, HostConfig config)
        {
            var requires = config.Definition.Elements("require");

            foreach (var require in requires)
            {
                if (!string.IsNullOrWhiteSpace(require.Attr("server")))
                {
                    continue;                                                   //external service
                }
                var name      = require.IdCodeOrValue() + require.Attr("suffix");
                var shadow    = EnvironmentInfo.GetShadowDirectory(name);
                var processes = Process.GetProcessesByName("qh");
                Console.WriteLine(string.Join("; ", processes.Select(_ => _.ProcessName)));
                var required =
                    processes.FirstOrDefault(_ => _.MainModule.FileName.NormalizePath().StartsWith(shadow.NormalizePath()));
                if (null != required)
                {
                    config.Log.Info("Required '" + name + "' found, PID: " + required.Id);
                }
                else
                {
                    var args = name;
                    if (serverParameters.Get("hidden", false))
                    {
                        args += " --hidden";
                    }
                    required = Process.Start(EnvironmentInfo.ResolvePath("@repos@/.build/bin/all/qh.exe"), args);
                    config.Log.Info("Required '" + name + "' started, PID: " + required.Id);
                }
            }
        }
 public ServerManager(ServerParameters parameters)
 {
     _taskScheduler = GetTaskScheduler(parameters.SchedulerType);
     _tasksFilePath = parameters.TasksFilePath;
     _timer         = GetTimer();
     _queueManager  = GetQueueManager();
 }
Exemplo n.º 10
0
 public BaseSqlCacher(ServerParameters parameters, int length)
 {
     _lock       = new object();
     _items      = new Queue <TItem>();
     _parameters = parameters;
     _length     = length;
 }
Exemplo n.º 11
0
        static void Server(string[] args)
        {
            var           newArgs = new ArraySegment <string> (args, 1, args.Length - 1);
            ServerFactory factory = Factory.MonoServer;
            int           repeat  = 0;

            var parameters = new ServerParameters();

            var p = new OptionSet {
                { "server=", v => factory = ConnectionFactoryProvider.GetServerFactory(v) },
                { "verbose", v => parameters.EnableDebugging = true },
                { "repeat", (int v) => repeat = v }
            };
            var extra = p.Parse(newArgs);

            if (extra.Count != 0)
            {
                throw new InvalidOperationException();
            }

            if (repeat < 0)
            {
                repeat = int.MaxValue;
            }
            else if (repeat == 0)
            {
                repeat = 1;
            }

            for (int i = 0; i < repeat; i++)
            {
                RunServer(factory, parameters).Wait();
            }
        }
Exemplo n.º 12
0
	    private static int Execute(ServerParameters arg) {
	        var config = arg.BuildServerConfig();
	        EnsureRequiredApplications(arg,config);
	        config.DllFolder = EnvironmentInfo.ResolvePath("@repos@/.build/bin/all");
            var command = arg.Get("command", "");
	        if (string.IsNullOrWhiteSpace(command)) {
	            Console.WriteLine("LOGLEVEL " + config.LogLevel);
	        }
	        var hostServer = new HostServer(config);
            hostServer.Initialize();
            var consoleContext = new ConsoleContext
            {
                Container = hostServer.Container,
                Parameters = arg
            };
            var listener = new ConsoleListener(consoleContext);
            
	        if (!string.IsNullOrWhiteSpace(command)) {
	            var task = listener.Call(command);
	            task.Wait();
	        }
	        else {

	            LogHostInfo(arg, config);
	            hostServer.Start();
	            Console.WriteLine("LOGLEVEL " + config.LogLevel);

	            listener.Log = hostServer.Container.Get<ILoggyManager>().Get("console");
	            listener.Run();
	            hostServer.Stop();
	        }
	        return 0;
	    }
Exemplo n.º 13
0
        public ServerService()
        {
            InitializeComponent();

            ServerConfiguration _serverConfiguration = new ServerConfiguration();

            _serverParameters = _serverConfiguration.ReadConfigurationFile();
        }
Exemplo n.º 14
0
		internal static RemoteCertificateValidationCallback GetValidationCallback (ServerParameters parameters)
		{
			var validator = parameters.ServerCertificateValidator;
			if (validator == null)
				return null;

			return ((CertificateValidator)validator).ValidationCallback;
		}
Exemplo n.º 15
0
        public void CanReadConfigFromWebFarmRoot()
        {
            var dir = Path.Combine(Path.GetTempPath(), "ServerParametersTest");

            Directory.CreateDirectory(dir);
            File.WriteAllText(Path.Combine(dir, "a.hostconf"), @"
class x
    y=23
");
            var parameters = new ServerParameters().Initialize("x", "-fr", dir);

            Assert.AreEqual("23", parameters.Definition.Attr("y"));
        }
Exemplo n.º 16
0
        public Server()
        {
            Log.LogInfo("Setting up...", LogType.Application_Work);

            //create server parameter file if it doesn't exist
            if (!File.Exists(Globals.BASE_DIRECTORY + Globals.PARAMETERS_PATH))
            {
                JSONManagement.WriteToJsonFile <ServerParameters>(
                    Globals.BASE_DIRECTORY + Globals.PARAMETERS_PATH,
                    new ServerParameters(8407, "127.0.0.1"));
            }

            ServerParameter               = JSONManagement.ReadFromJsonFile <ServerParameters>(AppDomain.CurrentDomain.BaseDirectory + Globals.PARAMETERS_PATH);
            InternalTopicManager          = new TopicManager();
            InternalPrivateMessageManager = new PrivateMessageManager();
            ClientLinks = new List <ClientLink>();
            //Disconnect gracefully every link when server closes
            AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
        }
        public StartServerResponse StartServer([FromQuery] ServerParameters parameters)
        {
            try
            {
                if (parameters.ApiKey != _config.GetValue <string>("ApiKey"))
                {
                    return(new StartServerResponse("Invalid ApiKey."));
                }

                Stopwatch sw = Stopwatch.StartNew();
                while (_isBusy)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                    if (sw.Elapsed.TotalSeconds > 5)
                    {
                        throw new Exception("Request timeout: the previous request hasn't finished yet.");
                    }
                }

                _isBusy = true;

                var serverProcess = _privateServerService.SpawnNewPrivateServer(parameters.Players, parameters.ModName);
                _logger.LogInformation("Server started waiting for {0} players on port {1}.",
                                       parameters.Players, serverProcess.Port);

                string commandLine = CommandLineUtils.GetClientLaunchCommand(HttpContext.Request.Host.Host,
                                                                             serverProcess.Port,
                                                                             serverProcess.Mod.CommandLine);

                Thread.Sleep(TimeSpan.FromSeconds(2));
                return(new StartServerResponse(serverProcess.Port, commandLine));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
                return(new StartServerResponse(generalErrorMessage));
            }
            finally
            {
                _isBusy = false;
            }
        }
        public OutboundEventNotificationService(Session session, ICicStatusService statusService, IDeviceManager deviceManager, ITraceContext traceContext)
        {
            _deviceManager = deviceManager;
            _session = session;
            _traceContext = traceContext;
            _statusService = statusService;
            _statusService.UserStatusChanged += OnUserStatusChanged;

            _session.ConnectionStateChanged += OnConnectionStateChanged;

            _deviceManager.HeadsetConnected += OnDeviceEvent;
            _deviceManager.HeadsetDisconnected += OnDeviceEvent;
            _deviceManager.MuteChanged += OnDeviceEvent;
            _deviceManager.PlantronicsDeviceAttached += OnDeviceEvent;
            _deviceManager.PlantronicsDeviceDetached += OnDeviceEvent;

            _serverParams = new ServerParameters(_session);
            _serverParams.StartWatching(new []{ShouldSendHandlerNotificationParam, WebServerUrlParam});

            PostToWebService();
        }
Exemplo n.º 19
0
        private static int Execute(ServerParameters arg)
        {
            var config = arg.BuildServerConfig();

            EnsureRequiredApplications(arg, config);
            config.DllFolder = EnvironmentInfo.ResolvePath("@repos@/.build/bin/all");
            var command = arg.Get("command", "");

            if (string.IsNullOrWhiteSpace(command))
            {
                Console.WriteLine("LOGLEVEL " + config.LogLevel);
            }
            var hostServer = new HostServer(config);

            hostServer.Initialize();
            var consoleContext = new ConsoleContext
            {
                Container  = hostServer.Container,
                Parameters = arg
            };
            var listener = new ConsoleListener(consoleContext);

            if (!string.IsNullOrWhiteSpace(command))
            {
                var task = listener.Call(command);
                task.Wait();
            }
            else
            {
                LogHostInfo(arg, config);
                hostServer.Start();
                Console.WriteLine("LOGLEVEL " + config.LogLevel);

                listener.Log = hostServer.Container.Get <ILoggyManager>().Get("console");
                listener.Run();
                hostServer.Stop();
            }
            return(0);
        }
Exemplo n.º 20
0
	    private static void EnsureRequiredApplications(ServerParameters serverParameters, HostConfig config) {
	        var requires = config.Definition.Elements("require");
	        foreach (var require in requires) {
                if(!string.IsNullOrWhiteSpace(require.Attr("server")))continue; //external service
	            var name = require.IdCodeOrValue()+require.Attr("suffix");
	            var shadow = EnvironmentInfo.GetShadowDirectory(name);
	            var processes = Process.GetProcessesByName("qh");
                Console.WriteLine(string.Join("; ",processes.Select(_=>_.ProcessName)));
	            var required =
	                processes.FirstOrDefault(_ => _.MainModule.FileName.NormalizePath().StartsWith(shadow.NormalizePath()));
	            if (null != required) {
	                config.Log.Info("Required '" + name + "' found, PID: " + required.Id);
	            }
	            else {
	                var args = name;
	                if (serverParameters.Get("hidden", false)) {
	                    args += " --hidden";
	                }
	                required = Process.Start(EnvironmentInfo.ResolvePath("@repos@/.build/bin/all/qh.exe"), args);
                    config.Log.Info("Required '" + name + "' started, PID: " + required.Id);
	            }
	        }
	    }
Exemplo n.º 21
0
	    private static void LogHostInfo(ServerParameters arg, HostConfig config) {
            Console.WriteLine("BinRoot: "+config.DllFolder);
	        foreach (var assembly in config.AutoconfigureAssemblies) {
                arg.Log.Trace("Lib: " + assembly);
	        }
	        foreach (var hostBinding in config.Bindings) {
                arg.Log.Info("Binding: " + hostBinding);
	        }
	        arg.Log.Trace("RootFolder: " + config.RootFolder);
	        foreach (var contentFolder in config.ContentFolders) {
	            arg.Log.Trace("ContentFolder: " + contentFolder);
	        }
	        foreach (var map in config.StaticContentMap) {
	            arg.Log.Trace("Map: "+map.Key+" : "+map.Value);
	        }
            foreach (var map in config.Proxize)
            {
                arg.Log.Trace("Proxize: " + map.Key + " : " + map.Value);
            }
	        foreach (var e in config.StaticContentCacheMap) {
	            arg.Log.Trace(e.Value.ToString());
	        }
	    }
		public override IServer CreateServer (ServerParameters parameters)
		{
			return CreateMonoServer (parameters);
		}
Exemplo n.º 23
0
 void PivotGridDemoModule_Loaded(object sender, RoutedEventArgs e)
 {
     ServerParameters.LoadParameters();
     radioOlapCube.IsChecked = true;
 }
		public Task<MonoSslStream> CreateServerStreamAsync (Stream stream, ServerParameters parameters, CancellationToken cancellationToken)
		{
			return CreateServerStreamAsync (stream, parameters, null, cancellationToken);
		}
		public MonoSslStream CreateServerStream (Stream stream, ServerParameters parameters)
		{
			var certificate = CertificateProvider.GetCertificate (parameters.ServerCertificate);

			var protocol = GetProtocol (parameters, true);
			var validator = CallbackHelpers.GetCertificateValidator (parameters.ServerCertificateValidator);

			var askForCert = (parameters.Flags & (ServerFlags.AskForClientCertificate|ServerFlags.RequireClientCertificate)) != 0;

			var sslStream = tlsProvider.CreateSslStream (stream, false, validator);
			sslStream.AuthenticateAsServer (certificate, askForCert, protocol, false);

			return new MonoSslStream (sslStream);
		}
		public override IServer CreateServer (ServerParameters parameters)
		{
			if (SupportsMonoExtensions)
				return new MonoServer (this, parameters);
			else
				return new DotNetServer (this, parameters, this);
		}
Exemplo n.º 27
0
        /*/// <value>Counts the numbers of Connections that share
         * /// this Connector. Used in Release() to decide wether this
         * /// connector is to be moved to the PooledConnectors list.</value>
         * // internal int mShareCount;*/

        /// <summary>
        /// Opens the physical connection to the server.
        /// </summary>
        /// <remarks>Usually called by the RequestConnector
        /// Method of the connection pool manager.</remarks>
        internal void Open()
        {
            ServerVersion = null;
            // If Connection.ConnectionString specifies a protocol version, we will
            // not try to fall back to version 2 on failure.

            _backendProtocolVersion = (settings.Protocol == ProtocolVersion.Unknown)
                                          ? ProtocolVersion.Version3
                                          : settings.Protocol;

            // Reset state to initialize new connector in pool.
            CurrentState = NpgsqlClosedState.Instance;

            // Keep track of time remaining; Even though there may be multiple timeout-able calls,
            // this allows us to still respect the caller's timeout expectation.
            int      connectTimeRemaining = this.ConnectionTimeout * 1000;
            DateTime attemptStart         = DateTime.Now;

            // Get a raw connection, possibly SSL...
            CurrentState.Open(this, connectTimeRemaining);
            try
            {
                // Establish protocol communication and handle authentication...
                CurrentState.Startup(this);
            }
            catch (NpgsqlException ne)
            {
                connectTimeRemaining -= Convert.ToInt32((DateTime.Now - attemptStart).TotalMilliseconds);

                // Check for protocol not supported.  If we have been told what protocol to use,
                // we will not try this step.
                if (settings.Protocol != ProtocolVersion.Unknown)
                {
                    throw;
                }
                // If we attempted protocol version 3, it may be possible to drop back to version 2.
                if (BackendProtocolVersion != ProtocolVersion.Version3)
                {
                    throw;
                }
                NpgsqlError Error0 = (NpgsqlError)ne.Errors[0];

                // If NpgsqlError..ctor() encounters a version 2 error,
                // it will set its own protocol version to version 2.  That way, we can tell
                // easily if the error was a FATAL: protocol error.
                if (Error0.BackendProtocolVersion != ProtocolVersion.Version2)
                {
                    throw;
                }
                // Try using the 2.0 protocol.
                _mediator.ResetResponses();
                BackendProtocolVersion = ProtocolVersion.Version2;
                CurrentState           = NpgsqlClosedState.Instance;

                // Get a raw connection, possibly SSL...
                CurrentState.Open(this, connectTimeRemaining);
                // Establish protocol communication and handle authentication...
                CurrentState.Startup(this);
            }

            // Change the state of connection to open and ready.
            _connection_state = ConnectionState.Open;
            CurrentState      = NpgsqlReadyState.Instance;

            // Fall back to the old way, SELECT VERSION().
            // This should not happen for protocol version 3+.
            if (ServerVersion == null)
            {
                //NpgsqlCommand command = new NpgsqlCommand("set DATESTYLE TO ISO;select version();", this);
                //ServerVersion = new Version(PGUtil.ExtractServerVersion((string) command.ExecuteScalar()));
                using (NpgsqlCommand command = new NpgsqlCommand("set DATESTYLE TO ISO;select version();", this))
                {
                    ServerVersion = new Version(PGUtil.ExtractServerVersion((string)command.ExecuteScalar()));
                }
            }

            // Adjust client encoding.

            NpgsqlParameterStatus clientEncodingParam = null;

            if (
                !ServerParameters.TryGetValue("client_encoding", out clientEncodingParam) ||
                (!string.Equals(clientEncodingParam.ParameterValue, "UTF8", StringComparison.OrdinalIgnoreCase) && !string.Equals(clientEncodingParam.ParameterValue, "UNICODE", StringComparison.OrdinalIgnoreCase))
                )
            {
                new NpgsqlCommand("SET CLIENT_ENCODING TO UTF8", this).ExecuteBlind();
            }

            if (!string.IsNullOrEmpty(settings.SearchPath))
            {
                /*NpgsqlParameter p = new NpgsqlParameter("p", DbType.String);
                 * p.Value = settings.SearchPath;
                 * NpgsqlCommand commandSearchPath = new NpgsqlCommand("SET SEARCH_PATH TO :p,public", this);
                 * commandSearchPath.Parameters.Add(p);
                 * commandSearchPath.ExecuteNonQuery();*/

                /*NpgsqlParameter p = new NpgsqlParameter("p", DbType.String);
                 * p.Value = settings.SearchPath;
                 * NpgsqlCommand commandSearchPath = new NpgsqlCommand("SET SEARCH_PATH TO :p,public", this);
                 * commandSearchPath.Parameters.Add(p);
                 * commandSearchPath.ExecuteNonQuery();*/

                // TODO: Add proper message when finding a semicolon in search_path.
                // This semicolon could lead to a sql injection security hole as someone could write in connection string:
                // searchpath=public;delete from table; and it would be executed.

                if (settings.SearchPath.Contains(";"))
                {
                    throw new InvalidOperationException();
                }

                // This is using string concatenation because set search_path doesn't allow type casting. ::text
                NpgsqlCommand commandSearchPath = new NpgsqlCommand("SET SEARCH_PATH=" + settings.SearchPath, this);
                commandSearchPath.ExecuteBlind();
            }

            if (!string.IsNullOrEmpty(settings.ApplicationName))
            {
                if (!SupportsApplicationName)
                {
                    //TODO
                    //throw new InvalidOperationException(resman.GetString("Exception_ApplicationNameNotSupported"));
                    throw new InvalidOperationException("ApplicationName not supported.");
                }

                if (settings.ApplicationName.Contains(";"))
                {
                    throw new InvalidOperationException();
                }

                NpgsqlCommand commandApplicationName = new NpgsqlCommand("SET APPLICATION_NAME='" + settings.ApplicationName + "'", this);
                commandApplicationName.ExecuteBlind();
            }

            /*
             * Try to set SSL negotiation to 0. As of 2010-03-29, recent problems in SSL library implementations made
             * postgresql to add a parameter to set a value when to do this renegotiation or 0 to disable it.
             * Currently, Npgsql has a problem with renegotiation so, we are trying to disable it here.
             * This only works on postgresql servers where the ssl renegotiation settings is supported of course.
             * See http://lists.pgfoundry.org/pipermail/npgsql-devel/2010-February/001065.html for more information.
             */

            try
            {
                NpgsqlCommand commandSslrenegotiation = new NpgsqlCommand("SET ssl_renegotiation_limit=0", this);
                commandSslrenegotiation.ExecuteBlind();
            }
            catch {}



            /*
             * Set precision digits to maximum value possible. For postgresql before 9 it was 2, after that, it is 3.
             * This way, we set first to 2 and then to 3. If there is an error because of 3, it will have been set to 2 at least.
             * Check bug report #1010992 for more information.
             */


            try
            {
                NpgsqlCommand commandSingleDoublePrecision = new NpgsqlCommand("SET extra_float_digits=2;SET extra_float_digits=3;", this);
                commandSingleDoublePrecision.ExecuteBlind();
            }
            catch {}


            /*
             * Set lc_monetary format to 'C' ir order to get a culture agnostic representation of money.
             * I noticed that on Windows, even when the lc_monetary is English_United States.UTF-8, negative
             * money is formatted as ($value) with parentheses to indicate negative value.
             * By going with a culture agnostic format, we get a consistent behavior.
             */

            try
            {
                NpgsqlCommand commandMonetaryFormatC = new NpgsqlCommand("SET lc_monetary='C';", this);
                commandMonetaryFormatC.ExecuteBlind();
            }
            catch
            {
            }


            // Make a shallow copy of the type mapping that the connector will own.
            // It is possible that the connector may add types to its private
            // mapping that will not be valid to another connector, even
            // if connected to the same backend version.
            _oidToNameMapping = NpgsqlTypesHelper.CreateAndLoadInitialTypesMapping(this).Clone();

            ProcessServerVersion();

            // The connector is now fully initialized. Beyond this point, it is
            // safe to release it back to the pool rather than closing it.
            IsInitialized = true;
        }
Exemplo n.º 28
0
 public LevelCacher(ServerParameters parameters)
     : base(parameters, 100)
 {
 }
		public override IMonoServer CreateMonoServer (ServerParameters parameters)
		{
			if (!SupportsMonoExtensions)
				throw new InvalidOperationException ();
			return new MonoServer (this, parameters);
		}
Exemplo n.º 30
0
        /// <summary>
        /// Creates a new request object.
        /// </summary>
        /// <param name="fcgiRequest"></param>
        public HttpRequest(FastCGI.Request fcgiRequest)
        {
            FcgiRequest = fcgiRequest;
            string httpMethod = fcgiRequest.GetParameterASCII("REQUEST_METHOD");

            switch (httpMethod)
            {
            case "GET":
                Method = HttpMethod.GET;
                break;

            case "POST":
                Method = HttpMethod.POST;
                break;

            case "PUT":
                Method = HttpMethod.PUT;
                break;

            case "DELETE":
                Method = HttpMethod.DELETE;
                break;

            default:
                Method = HttpMethod.UNKNOWN;
                break;
            }

            GET = new Dictionary <string, string>();
            // Todo: perform correct parsing and decoding according to HTTP standard
            var getParams = Encoding.ASCII.GetString(ServerParameters["QUERY_STRING"]).Split('&');

            foreach (var param in getParams)
            {
                if (param.Length > 0)
                {
                    var keyValue = param.Split(new char[] { '=' }, 2);
                    if (keyValue.Length >= 1)
                    {
                        var key   = keyValue[0];
                        var value = "";
                        if (keyValue.Length >= 2)
                        {
                            value = keyValue[1];
                        }
                        GET[key] = System.Uri.UnescapeDataString(value.Replace('+', ' '));
                    }
                }
            }

            POST = new Dictionary <string, string>();
            // Todo: perform correct parsing and decoding according to HTTP standard
            var postParams = Body.Split('&');

            foreach (var param in postParams)
            {
                if (param.Length > 0)
                {
                    var keyValue = param.Split(new char[] { '=' }, 2);
                    if (keyValue.Length >= 1)
                    {
                        var key   = keyValue[0];
                        var value = "";
                        if (keyValue.Length >= 2)
                        {
                            value = keyValue[1];
                        }
                        POST[key] = System.Uri.UnescapeDataString(value.Replace('+', ' '));
                    }
                }
            }

            if (ServerParameters.ContainsKey("HTTP_COOKIE"))
            {
                var cookieHeader = GetParameterASCII("HTTP_COOKIE");
                var cookies      = cookieHeader.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var cookie in cookies)
                {
                    var cookieNameValue = cookie.Split('=');
                    Cookies[cookieNameValue[0].Trim()] = System.Uri.UnescapeDataString(cookieNameValue[1].Trim().Replace('+', ' '));
                }
            }
        }
		public CipherInstrumentParameters (InstrumentationCategory category, CipherInstrumentType type, ClientParameters clientParameters, ServerParameters serverParameters)
			: base (category, clientParameters, serverParameters)
		{
			Type = type;
		}
Exemplo n.º 32
0
        /*/// <value>Counts the numbers of Connections that share
         * /// this Connector. Used in Release() to decide wether this
         * /// connector is to be moved to the PooledConnectors list.</value>
         * // internal int mShareCount;*/

        /// <summary>
        /// Opens the physical connection to the server.
        /// </summary>
        /// <remarks>Usually called by the RequestConnector
        /// Method of the connection pool manager.</remarks>
        internal void Open()
        {
            ServerVersion = null;
            // If Connection.ConnectionString specifies a protocol version, we will
            // not try to fall back to version 2 on failure.

            _backendProtocolVersion = (settings.Protocol == ProtocolVersion.Unknown)
                                          ? ProtocolVersion.Version3
                                          : settings.Protocol;

            // Reset state to initialize new connector in pool.
            CurrentState = NpgsqlClosedState.Instance;

            // Get a raw connection, possibly SSL...
            CurrentState.Open(this);
            try
            {
                // Establish protocol communication and handle authentication...
                CurrentState.Startup(this);
            }
            catch (NpgsqlException ne)
            {
                // Check for protocol not supported.  If we have been told what protocol to use,
                // we will not try this step.
                if (settings.Protocol != ProtocolVersion.Unknown)
                {
                    throw;
                }
                // If we attempted protocol version 3, it may be possible to drop back to version 2.
                if (BackendProtocolVersion != ProtocolVersion.Version3)
                {
                    throw;
                }
                NpgsqlError Error0 = (NpgsqlError)ne.Errors[0];

                // If NpgsqlError..ctor() encounters a version 2 error,
                // it will set its own protocol version to version 2.  That way, we can tell
                // easily if the error was a FATAL: protocol error.
                if (Error0.BackendProtocolVersion != ProtocolVersion.Version2)
                {
                    throw;
                }
                // Try using the 2.0 protocol.
                _mediator.ResetResponses();
                BackendProtocolVersion = ProtocolVersion.Version2;
                CurrentState           = NpgsqlClosedState.Instance;

                // Get a raw connection, possibly SSL...
                CurrentState.Open(this);
                // Establish protocol communication and handle authentication...
                CurrentState.Startup(this);
            }

            // Change the state of connection to open and ready.
            _connection_state = ConnectionState.Open;
            CurrentState      = NpgsqlReadyState.Instance;

            // Fall back to the old way, SELECT VERSION().
            // This should not happen for protocol version 3+.
            if (ServerVersion == null)
            {
                NpgsqlCommand command = new NpgsqlCommand("set DATESTYLE TO ISO;select version();", this);
                ServerVersion = new Version(PGUtil.ExtractServerVersion((string)command.ExecuteScalar()));
            }

            // Adjust client encoding.

            NpgsqlParameterStatus clientEncodingParam = null;

            if (
                !ServerParameters.TryGetValue("client_encoding", out clientEncodingParam) ||
                (!string.Equals(clientEncodingParam.ParameterValue, "UTF8", StringComparison.OrdinalIgnoreCase) && !string.Equals(clientEncodingParam.ParameterValue, "UNICODE", StringComparison.OrdinalIgnoreCase))
                )
            {
                new NpgsqlCommand("SET CLIENT_ENCODING TO UTF8", this).ExecuteBlind();
            }

            if (!string.IsNullOrEmpty(settings.SearchPath))
            {
                /*NpgsqlParameter p = new NpgsqlParameter("p", DbType.String);
                 * p.Value = settings.SearchPath;
                 * NpgsqlCommand commandSearchPath = new NpgsqlCommand("SET SEARCH_PATH TO :p,public", this);
                 * commandSearchPath.Parameters.Add(p);
                 * commandSearchPath.ExecuteNonQuery();*/

                /*NpgsqlParameter p = new NpgsqlParameter("p", DbType.String);
                 * p.Value = settings.SearchPath;
                 * NpgsqlCommand commandSearchPath = new NpgsqlCommand("SET SEARCH_PATH TO :p,public", this);
                 * commandSearchPath.Parameters.Add(p);
                 * commandSearchPath.ExecuteNonQuery();*/

                // TODO: Add proper message when finding a semicolon in search_path.
                // This semicolon could lead to a sql injection security hole as someone could write in connection string:
                // searchpath=public;delete from table; and it would be executed.

                if (settings.SearchPath.Contains(";"))
                {
                    throw new InvalidOperationException();
                }

                // This is using string concatenation because set search_path doesn't allow type casting. ::text
                NpgsqlCommand commandSearchPath = new NpgsqlCommand("SET SEARCH_PATH=" + settings.SearchPath, this);
                commandSearchPath.ExecuteBlind();
            }



            /*
             * Try to set SSL negotiation to 0. As of 2010-03-29, recent problems in SSL library implementations made
             * postgresql to add a parameter to set a value when to do this renegotiation or 0 to disable it.
             * Currently, Npgsql has a problem with renegotiation so, we are trying to disable it here.
             * This only works on postgresql servers where the ssl renegotiation settings is supported of course.
             * See http://lists.pgfoundry.org/pipermail/npgsql-devel/2010-February/001065.html for more information.
             */



            try

            {
                NpgsqlCommand commandSslrenegotiation = new NpgsqlCommand("SET ssl_renegotiation_limit=0", this);

                commandSslrenegotiation.ExecuteBlind();
            }

            catch {}



            // Make a shallow copy of the type mapping that the connector will own.
            // It is possible that the connector may add types to its private
            // mapping that will not be valid to another connector, even
            // if connected to the same backend version.
            _oidToNameMapping = NpgsqlTypesHelper.CreateAndLoadInitialTypesMapping(this).Clone();

            ProcessServerVersion();

            // The connector is now fully initialized. Beyond this point, it is
            // safe to release it back to the pool rather than closing it.
            IsInitialized = true;
        }
		public override IMonoServer CreateMonoServer (ServerParameters parameters)
		{
			return new OpenSslServer (this, parameters);
		}
Exemplo n.º 34
0
		public OpenSslServer (OpenSslConnectionProvider provider, ServerParameters parameters)
			: base (provider, parameters)
		{
		}
Exemplo n.º 35
0
        /// <summary>
        /// Opens the physical connection to the server.
        /// </summary>
        /// <remarks>Usually called by the RequestConnector
        /// Method of the connection pool manager.</remarks>
        internal void Open()
        {
            ServerVersion = null;
            // If Connection.ConnectionString specifies a protocol version, we will
            // not try to fall back to version 2 on failure.

            _backendProtocolVersion = (settings.Protocol == ProtocolVersion.Unknown)
                                                                                  ? ProtocolVersion.Version3
                                                                                  : settings.Protocol;

            // Reset state to initialize new connector in pool.
            CurrentState = NpgsqlClosedState.Instance;

            // Get a raw connection, possibly SSL...
            CurrentState.Open(this);
            try
            {
                // Establish protocol communication and handle authentication...
                CurrentState.Startup(this);
            }
            catch (NpgsqlException ne)
            {
                // Check for protocol not supported.  If we have been told what protocol to use,
                // we will not try this step.
                if (settings.Protocol != ProtocolVersion.Unknown)
                {
                    throw;
                }
                // If we attempted protocol version 3, it may be possible to drop back to version 2.
                if (BackendProtocolVersion != ProtocolVersion.Version3)
                {
                    throw;
                }
                NpgsqlError Error0 = (NpgsqlError)ne.Errors[0];

                // If NpgsqlError..ctor() encounters a version 2 error,
                // it will set its own protocol version to version 2.  That way, we can tell
                // easily if the error was a FATAL: protocol error.
                if (Error0.BackendProtocolVersion != ProtocolVersion.Version2)
                {
                    throw;
                }
                // Try using the 2.0 protocol.
                _mediator.ResetResponses();
                BackendProtocolVersion = ProtocolVersion.Version2;
                CurrentState           = NpgsqlClosedState.Instance;

                // Get a raw connection, possibly SSL...
                CurrentState.Open(this);
                // Establish protocol communication and handle authentication...
                CurrentState.Startup(this);
            }

            // Change the state of connection to open and ready.
            State        = ConnectionState.Open;
            CurrentState = NpgsqlReadyState.Instance;

            // Fall back to the old way, SELECT VERSION().
            // This should not happen for protocol version 3+.
            if (ServerVersion == null)
            {
                using (NpgsqlCommand command = new NpgsqlCommand("set DATESTYLE TO ISO;select version();", this))
                {
                    ServerVersion = new Version(PGUtil.ExtractServerVersion((string)command.ExecuteScalar()));
                }
            }

            StringBuilder sbInit = new StringBuilder();

            // Adjust client encoding.
            NpgsqlParameterStatus clientEncodingParam = null;

            if (!ServerParameters.TryGetValue("client_encoding", out clientEncodingParam) ||
                !string.Equals(clientEncodingParam.ParameterValue, "UTF8", StringComparison.OrdinalIgnoreCase) && !string.Equals(clientEncodingParam.ParameterValue, "UNICODE", StringComparison.OrdinalIgnoreCase))
            {
                sbInit.AppendLine("SET CLIENT_ENCODING TO UTF8;");
            }

            if (!string.IsNullOrEmpty(settings.SearchPath))
            {
                // TODO: Add proper message when finding a semicolon in search_path.
                // This semicolon could lead to a sql injection security hole as someone could write in connection string:
                // searchpath=public;delete from table; and it would be executed.

                if (settings.SearchPath.Contains(";"))
                {
                    throw new InvalidOperationException();
                }

                sbInit.AppendLine("SET SEARCH_PATH=" + settings.SearchPath + ";");
            }

            if (!string.IsNullOrEmpty(settings.ApplicationName))
            {
                if (!SupportsApplicationName)
                {
                    //TODO
                    //throw new InvalidOperationException(resman.GetString("Exception_ApplicationNameNotSupported"));
                    throw new InvalidOperationException("ApplicationName not supported.");
                }

                if (settings.ApplicationName.Contains(";"))
                {
                    throw new InvalidOperationException();
                }

                sbInit.AppendLine("SET APPLICATION_NAME='" + settings.ApplicationName.Replace('\'', '-') + "';");
            }

            /*
             * Try to set SSL negotiation to 0. As of 2010-03-29, recent problems in SSL library implementations made
             * postgresql to add a parameter to set a value when to do this renegotiation or 0 to disable it.
             * Currently, Npgsql has a problem with renegotiation so, we are trying to disable it here.
             * This only works on postgresql servers where the ssl renegotiation settings is supported of course.
             * See http://lists.pgfoundry.org/pipermail/npgsql-devel/2010-February/001065.html for more information.
             */
            sbInit.AppendLine("SET ssl_renegotiation_limit=0;");

            /*
             * Set precision digits to maximum value possible. For postgresql before 9 it was 2, after that, it is 3.
             * This way, we set first to 2 and then to 3. If there is an error because of 3, it will have been set to 2 at least.
             * Check bug report #1010992 for more information.
             */
            sbInit.AppendLine("SET extra_float_digits=3;");
            try
            {
                new NpgsqlCommand(sbInit.ToString(), this).ExecuteBlind();
            }
            catch
            {
                foreach (var line in sbInit.ToString().Split(Environment.NewLine.ToCharArray()))
                {
                    try
                    {
                        if (line.Length > 0)
                        {
                            new NpgsqlCommand(line, this).ExecuteBlind();
                        }
                    }
                    catch { }
                }
            }

            // Make a shallow copy of the type mapping that the connector will own.
            // It is possible that the connector may add types to its private
            // mapping that will not be valid to another connector, even
            // if connected to the same backend version.
            _oidToNameMapping = NpgsqlTypesHelper.CreateAndLoadInitialTypesMapping(this).Clone();

            ProcessServerVersion();

            // The connector is now fully initialized. Beyond this point, it is
            // safe to release it back to the pool rather than closing it.
            IsInitialized = true;
        }
Exemplo n.º 36
0
 public PingCacher(ServerParameters parameters)
     : base(parameters, 10)
 {
 }
		public InstrumentationParameters (InstrumentationCategory category, ClientParameters clientParameters, ServerParameters serverParameters)
			: base (clientParameters, serverParameters)
		{
			Category = category;
		}
Exemplo n.º 38
0
		public MonoServer (MonoConnectionProviderImpl provider, ServerParameters parameters)
			: base (provider, parameters)
		{
		}
		ISslStream ISslStreamProvider.CreateServerStream (Stream stream, ServerParameters parameters)
		{
			return CreateServerStream (stream, parameters);
		}
Exemplo n.º 40
0
		public HttpServer CreateServer (IPortableEndPoint endpoint, ListenerFlags flags, ServerParameters parameters = null)
		{
			return new HttpServer (this, endpoint, flags, parameters);
		}
		async Task<ISslStream> ISslStreamProvider.CreateServerStreamAsync (Stream stream, ServerParameters parameters, CancellationToken cancellationToken)
		{
			return await CreateServerStreamAsync (stream, parameters, cancellationToken).ConfigureAwait (false);
		}
		public MonoClientAndServerParameters (ClientParameters clientParameters, ServerParameters serverParameters)
			: base (clientParameters, serverParameters)
		{
		}
		public async Task<MonoSslStream> CreateServerStreamAsync (Stream stream, ServerParameters parameters, MSI.MonoTlsSettings settings, CancellationToken cancellationToken)
		{
			var certificate = CertificateProvider.GetCertificate (parameters.ServerCertificate);
			var protocol = GetProtocol (parameters, true);

			MSI.ICertificateValidator validator = null;
			if (settings != null)
				CallbackHelpers.AddCertificateValidator (settings, parameters.ServerCertificateValidator);
			else
				validator = CallbackHelpers.GetCertificateValidator (parameters.ServerCertificateValidator);

			var askForCert = (parameters.Flags & (ServerFlags.AskForClientCertificate|ServerFlags.RequireClientCertificate)) != 0;

			var sslStream = tlsProvider.CreateSslStream (stream, false, validator, settings);
			var monoSslStream = new MonoSslStream (sslStream);

			try {
				await sslStream.AuthenticateAsServerAsync (certificate, askForCert, protocol, false).ConfigureAwait (false);
			} catch (Exception ex) {
				var lastError = monoSslStream.LastError;
				if (lastError != null)
					throw new AggregateException (ex, lastError);
				throw;
			}

			return monoSslStream;
		}
Exemplo n.º 44
0
		public abstract IMonoServer CreateMonoServer (ServerParameters parameters);
		public SignatureInstrumentParameters (InstrumentationCategory category, SignatureInstrumentType type, ClientParameters clientParameters, ServerParameters serverParameters)
			: base (category, clientParameters, serverParameters)
		{
			Type = type;
		}
		public SimpleConnectionParameters (InstrumentationCategory category, SimpleConnectionType type, ClientParameters clientParameters, ServerParameters serverParameters)
			: base (category, clientParameters, serverParameters)
		{
			Type = type;
		}