public async Task OnDisconnectAsync(ISocketConnection connection) { if (_pipelines.TryRemove(connection, out MessagePipeline? pipeline)) { await pipeline.DisposeAsync().ConfigureAwait(false); } }
public override ValueTask <ConnectionStatus> OnConnectAsync( ISocketConnection connection, InitializeConnectionMessage message, CancellationToken cancellationToken) { return(new ValueTask <ConnectionStatus>(_connectionStatus)); }
public SubscriptionSession( CancellationTokenSource session, ISocketSessionInterceptor sessionInterceptor, ISocketConnection connection, IResponseStream responseStream, ISubscription subscription, IExecutionDiagnosticEvents diagnosticEvents, string clientSubscriptionId) { _session = session ?? throw new ArgumentNullException(nameof(session)); _sessionInterceptor = sessionInterceptor ?? throw new ArgumentNullException(nameof(sessionInterceptor)); _connection = connection ?? throw new ArgumentNullException(nameof(connection)); _responseStream = responseStream ?? throw new ArgumentNullException(nameof(responseStream)); _diagnosticEvents = diagnosticEvents ?? throw new ArgumentNullException(nameof(diagnosticEvents)); Subscription = subscription ?? throw new ArgumentNullException(nameof(subscription)); Id = clientSubscriptionId ?? throw new ArgumentNullException(nameof(clientSubscriptionId)); _sessionToken = _session.Token; Task.Factory.StartNew( SendResultsAsync, _sessionToken, TaskCreationOptions.LongRunning, TaskScheduler.Default); }
private async Task RegisterInternalAsync( ISubscription subscription, ISocketConnection connection) { if (_subs.TryAdd(subscription.Id, new Sub(subscription, connection))) { connection.Disposed += (sender, args) => RemoveSubscription(subscription.Id); if (connection.IsClosed) { _subs.TryRemove(subscription.Id, out _); return; } subscription.OnRegister(() => UnregisterAsync(subscription.Id)); var writer = new SocketMessageWriter(); writer.WriteStartObject(); writer.WriteType(MessageTypes.Subscription.Start); writer.WriteId(subscription.Id); writer.WriteStartPayload(); subscription.OperationFormatter.Serialize(subscription.Operation, writer); writer.WriteEndObject(); await connection.SendAsync(writer.Body).ConfigureAwait(false); } }
public DataService(DataBase eDataBase, string strConnect, ISocketConnection pSocketConnection, TaskService eService) { this._strConnect = strConnect; this._eDataBase = eDataBase; this._pSocketConnection = pSocketConnection; this._eService = eService; }
private void FailureRaised ( ISocketConnection sender, Exception ex ) { // here we should log the exception Console.WriteLine(ex.ToString()); // we disconnect the faulty client sender.BeginDisconnect(); }
private void ClientDisconnected (ISocketConnection sender) { if (clients.Contains(sender)) { clients.Remove(sender); } }
private void FailureRaised (ISocketConnection sender, Exception ex) { // here we should log the exception // we disconnect the faulty client sender.BeginDisconnect(); }
protected override async Task HandleAsync( ISocketConnection connection, InitializeConnectionMessage message, CancellationToken cancellationToken) { ConnectionStatus connectionStatus = await _socketSessionInterceptor.OnConnectAsync( connection, message, cancellationToken); if (connectionStatus.Accepted) { await connection.SendAsync(AcceptConnectionMessage.Default, cancellationToken); await connection.SendAsync(KeepConnectionAliveMessage.Default, cancellationToken); } else { var rejectMessage = connectionStatus.Extensions == null ? new RejectConnectionMessage(connectionStatus.Message) : new RejectConnectionMessage( connectionStatus.Message, connectionStatus.Extensions); await connection.SendAsync( rejectMessage.Serialize(), cancellationToken); await connection.CloseAsync( connectionStatus.Message, SocketCloseStatus.PolicyViolation, cancellationToken); } }
internal void DoDisconnect() { bool fireEvent = false; lock (FConnectedSync) { if (FConnected) { //----- Disconnect! FConnected = false; FSocketConnection = null; if (FSocketClient != null) { FSocketClient.Stop(); FSocketClient.Dispose(); FSocketClient = null; } fireEvent = true; } } if ((FOnDisconnectedEvent != null) && fireEvent) { FOnDisconnectedEvent(); } }
public MessageReceiver( ISocketConnection connection, PipeWriter writer) { _connection = connection; _writer = writer; }
/// <summary> /// 构造函数 -- 断线 /// </summary> /// <param name="SocketConnection">连接接口</param> public SocketEventArgs(ISocketConnection SocketConnection, bool bConnection) { this._bLink = bConnection; this._SocketConnection = SocketConnection; this._SocketException = new Exception(); }
/// <summary> /// 构造函数 -- 断线 /// </summary> /// <param name="SocketConnection">连接接口</param> /// <param name="SocketException">异常类</param> public SocketEventArgs(ISocketConnection SocketConnection, Exception SocketException) { this._bLink = false; this._SocketConnection = SocketConnection; this._SocketException = SocketException; }
protected override async Task HandleAsync( ISocketConnection connection, DataStartMessage message, CancellationToken cancellationToken) { IQueryRequestBuilder requestBuilder = QueryRequestBuilder.From(message.Payload) .SetServices(connection.RequestServices); await _socketSessionInterceptor.OnRequestAsync( connection, requestBuilder, cancellationToken); IExecutionResult result = await _requestExecutor.ExecuteAsync( requestBuilder.Create(), cancellationToken); switch (result) { case IResponseStream responseStream: var subscription = new Subscription(connection, responseStream, message.Id); connection.Subscriptions.Register(subscription); break; case IQueryResult queryResult: using (queryResult) await HandleQueryResultAsync( connection, message, queryResult, cancellationToken); break; default: throw DataStartMessageHandler_RequestTypeNotSupported(); } }
public async ValueTask OnRequestAsync(ISocketConnection connection, IQueryRequestBuilder requestBuilder, CancellationToken cancellationToken) { requestBuilder.TrySetServices(connection.RequestServices); requestBuilder.TryAddProperty(nameof(HttpContext), connection.HttpContext); requestBuilder.TryAddProperty(nameof(ClaimsPrincipal), connection.HttpContext.User); }
static void client_OnSymmetricAuthenticate(ISocketConnection connection, out System.Security.Cryptography.RSACryptoServiceProvider serverKey, out byte[] signMessage) { //----- Sign Message! signMessage = new byte[] { 0x51, 0xBE, 0xA2, 0xC5, 0x31, 0x19, 0xAE, 0x21, 0x3D, 0x9A, 0xF2, 0x78, 0x90, 0x19, 0xCF, 0x97, 0xA5, 0x75, 0x99, 0xB3, 0xFD, 0x31, 0xE6, 0xB5, 0x7F, 0xFD, 0xD0, 0x37, 0x26, 0xC2, 0x7B, 0x27, 0x18, 0x43, 0xED, 0xD9, 0xC8, 0x5A, 0xF5, 0xE0, 0xDA, 0x33, 0x41, 0x3A, 0xC8, 0xE7, 0x4A, 0x5C, 0x9D, 0x48, 0x95, 0x22, 0x56, 0x2F, 0x62, 0x20, 0xD8, 0xEC, 0x46, 0x52, 0x49, 0x76, 0xFB, 0x7B, 0x1E, 0xF0, 0x5F, 0x4D, 0x2B, 0x33, 0xCE, 0xB0, 0x12, 0x29, 0x31, 0xCA, 0xEF, 0xAB, 0xEC, 0x97, 0xB3, 0x73, 0x2E, 0xDD, 0x2D, 0x58, 0xAC, 0xE9, 0xE0, 0xCC, 0x14, 0xDC, 0x14, 0xEF, 0x97, 0x64, 0x38, 0xC6, 0x1C, 0xD8, 0x87, 0xFC, 0x30, 0xD5, 0x79, 0xE4, 0x10, 0x2C, 0xFE, 0x98, 0x30, 0x2C, 0xFF, 0xAE, 0x51, 0xD5, 0x47, 0x1D, 0x4D, 0xC5, 0x43, 0x75, 0x6C, 0x5E, 0x32, 0xF2, 0x9C, 0x22 }; //----- Using CspParameters! CspParameters param = new CspParameters(); param.KeyContainerName = "ALAZ_ECHO_SERVICE"; serverKey = new RSACryptoServiceProvider(param); }
public KeepConnectionAliveJob( ISocketConnection connection, TimeSpan timeout) { _connection = connection; _timeout = timeout; }
private static void client_OnSymmetricAuthenticate(ISocketConnection connection, out System.Security.Cryptography.RSACryptoServiceProvider serverKey) { //----- Using string! //----- You must get the public key xml from the ALAZ certificate in you server machine. //----- Uncomment the following lines to get the public key from certificate. //---- Get certificate! // X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); // store.Open(OpenFlags.ReadOnly); // X509Certificate2 certificate = store.Certificates.Find(X509FindType.FindBySubjectName, "ALAZ Library", true)[0]; //---- Get public key string! // string publicKey = certificate.PrivateKey.ToXmlString(false); serverKey = new RSACryptoServiceProvider(); //----- Using string! if (connection.Context.Host.Context.HostType == HostType.htClient) { serverKey.FromXmlString("<RSAKeyValue><Modulus>z2ksxSTLHSBjY4+IEz7TZU5EclOql5pphA9+xyNQ6c1rYW6VPAmXmiXZKmsza8N++YVLAGnzR95iYyr4oL+mBz8lbhjDH2iqyQL7utbW1s87WaDC2o+82dLnLvwEqBhWpnz4tC0v0kCKayH6Jj+30l3xLdgDwReWF7YEvp6yq6nGxHOeSiioPpTtJzNhWjKGnK6oSZqthfWHewlRl2hVIrewD+JbP5JYTp/7iYptOiCwNAUZEBxODR2743D56J1AeHNc8VpZNvE3ZozIoRFhnxZw0ZpvMbgPliKPyjPeOvOFeqZUJ2zkQ7sH+gnqt67QzkOzznfuFPmTpBo0tMheyw==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"); } else { serverKey.FromXmlString("<RSAKeyValue><Modulus>z2ksxSTLHSBjY4+IEz7TZU5EclOql5pphA9+xyNQ6c1rYW6VPAmXmiXZKmsza8N++YVLAGnzR95iYyr4oL+mBz8lbhjDH2iqyQL7utbW1s87WaDC2o+82dLnLvwEqBhWpnz4tC0v0kCKayH6Jj+30l3xLdgDwReWF7YEvp6yq6nGxHOeSiioPpTtJzNhWjKGnK6oSZqthfWHewlRl2hVIrewD+JbP5JYTp/7iYptOiCwNAUZEBxODR2743D56J1AeHNc8VpZNvE3ZozIoRFhnxZw0ZpvMbgPliKPyjPeOvOFeqZUJ2zkQ7sH+gnqt67QzkOzznfuFPmTpBo0tMheyw==</Modulus><Exponent>AQAB</Exponent><P>7IhXSag5zlV+Ary/KDsMinK2Jah/WdTov6Z2XAAPHB4zOGEbhCXdgTEkIrOJNpyobF6L7mR9sTnuV5pr+vWklKkYMbxUEK+KRYo4knUvxx5ED4lFE3KUGeVz6jJ1LY5FqmQT4RTtfwZa6dxRPSgn19/k6sOqyPnnalPz30CYFAk=</P><Q>4Hs/u3UIH+CB3yf2gpupXw5yxl82YX/GuB+ZIAYopM65UlukzFl8eW1iEu42gG/UOpjfmDje+wEvIZ5gcKGjGdDgRmEbAYKNt7X6LqkhIMQqUHt0vAsNrYDXgRFVHdd8YisZ62DzAyMM9nu6v0jPTmhlJSDJwpH3s9XbVy0rmTM=</Q><DP>IF7UW087ggJvOV6tZosWP0hNpz+1Fg0uQTQ91H9pkfaMGfYoNuCbvNeF033wlFnCLvqNefWkwgFknfaTOogtmu69UektNA9iA/xTm6+P91csB1hI7M1seVLOl0mKgc6LuDL0CYS8r/qlrIWrVIxPT5rjkEFw+QpCYmnU4UPMzEk=</DP><DQ>jy7OBfmuBvcin35UBBbZv6Htn45Xl3TzAbpV51FGV2jsWBXQVe+2L5WPeteqt92clwuvgt6zi5LDx0PH68+NwweyJfIGUb4+OrG+NEj4snetLcyxNsguHz8RNmghzHkIA23OiI48MwIGYKmnAh+k6zQ3X6k8R/jm8DQ2RbKwHnU=</DQ><InverseQ>Jrbm5MzTpYI9f0jQKBFzdEdI4DeUFou4BrFpJaheh/+jhzogia+0VsK1CfuXbXgFLPV2aXpQeZYZTX/ANJEymJsp9kAELknq8O+qz6QFyfY0F4Q5H6SVuI/U40XlstYZ2ZEvjGMhXpSAnQUIZ8HJQf8nFOSoAK+HyDwPdvn5RlE=</InverseQ><D>L5hkBK1nyrxG8m7afAgbvJCUVmPqrrVpZzujDRGGnNBdxtL4ffl5h48N4ZUODLmk5p920ZZ+lExs6XLP8Rtpfxo3fadDB28eWdhMadipHkwZw3yHml4HqTijgn2kl+pV4Ainjbkc0zOqT+FRJPvUM/sIwEtkuSevcqt7NT73ozp9roswv0QHBrclCVIN0uiCqPEsfTaLeVEpg48dOh8as6l1XDlgnDGTFjkj2AgFfD27POPE3n4pJSaYJc5zNijbwrjyz8qa1nr+xBQ+yvteNDOg/1LAczP1xrypDgsl/bRHmkljYhPj40SXwK2jwyicgfgCbE3wi6O9t52D8koacQ==</D></RSAKeyValue>"); } }
public async Task ConnectAsync(string hostName) { Close(); _socket = _socketFactory.Create(); _socket.OnMessage += OnMessage; _socket.Connect($"ws://{hostName}:3000"); if (!_socket.IsAlive) { throw new ConnectionException($"Unable to conenct to television at {hostName}."); } _hostName = hostName; var key = await _keyStore.GetKeyAsync(hostName); var handshakeCommand = new HandshakeCommand(key); var handshakeResponse = await SendCommandAsync <HandshakeResponse>(handshakeCommand); await _keyStore.StoreKeyAsync(hostName, handshakeResponse.Key); var mouseCommand = new MouseGetCommand(); var mouseGetResponse = await SendCommandAsync <MouseGetResponse>(mouseCommand); _mouseSocket = _socketFactory.Create(); _mouseSocket.Connect(mouseGetResponse.SocketPath); if (!_mouseSocket.IsAlive) { throw new ConnectionException($"Unable to conenct to television mouse service at {hostName}."); } }
public virtual void OnSymmetricAuthenticate(ISocketConnection connection, out RSACryptoServiceProvider serverKey, out byte[] signMessage) { serverKey = new RSACryptoServiceProvider(); serverKey.Clear(); signMessage = new byte[0]; }
public async Task Return_One_Of_Many_Connections() { using (IWebHost host = TestServerHelper.CreateServer(out int port)) { // arrange var serviceCollection = new ServiceCollection(); serviceCollection.AddWebSocketClient( "Foo", c => c.Uri = new Uri("ws://localhost:" + port)); serviceCollection.AddWebSocketConnectionPool(); IServiceProvider services = serviceCollection.BuildServiceProvider(); ISocketConnectionPool connectionPool = services.GetRequiredService <ISocketConnectionPool>(); await connectionPool.RentAsync("Foo"); ISocketConnection connection = await connectionPool.RentAsync("Foo"); // act await connectionPool.ReturnAsync(connection); // assert Assert.False(connection.IsClosed); } }
public HttpStreamRouteObject(ISocketConnection socketConnection, HttpStreamRouter httpStreamRouter) { _socketConnection = socketConnection; _httpStreamRouter = httpStreamRouter; _socketConnection.DataReceived += SocketConnectionOnDataReceived; _httpRequestStream = new HttpRequestStream(); }
public SubscriptionSession( ISocketConnection connection, IResponseStream responseStream, ISubscription subscription, IDiagnosticEvents diagnosticEvents, string clientSubscriptionId) { _connection = connection ?? throw new ArgumentNullException(nameof(connection)); _responseStream = responseStream ?? throw new ArgumentNullException(nameof(responseStream)); _diagnosticEvents = diagnosticEvents ?? throw new ArgumentNullException(nameof(diagnosticEvents)); Subscription = subscription ?? throw new ArgumentNullException(nameof(subscription)); Id = clientSubscriptionId ?? throw new ArgumentNullException(nameof(clientSubscriptionId)); _cts = CancellationTokenSource.CreateLinkedTokenSource(_connection.RequestAborted); Task.Factory.StartNew( SendResultsAsync, _cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); }
private async Task HandleMessageAsync( ISocketConnection connection, OperationMessage message, CancellationToken cancellationToken) { for (int i = 0; i < _messageHandlers.Length; i++) { IMessageHandler handler = _messageHandlers[i]; if (handler.CanHandle(message)) { await handler.HandleAsync( connection, message, cancellationToken) .ConfigureAwait(false); // the message is handled and we are done. return; } } // TODO : resources throw new NotSupportedException( "The specified message type is not supported."); }
public async Task Rent_Two_Connections() { using (IWebHost host = TestServerHelper.CreateServer(out int port)) { // arrange var serviceCollection = new ServiceCollection(); serviceCollection.AddWebSocketClient( "Foo", c => c.Uri = new Uri("ws://localhost:" + port)); serviceCollection.AddWebSocketConnectionPool(); IServiceProvider services = serviceCollection.BuildServiceProvider(); ISocketConnectionPool connectionPool = services.GetRequiredService <ISocketConnectionPool>(); ISocketConnection firstConnection = await connectionPool.RentAsync("Foo"); // act ISocketConnection secondConnection = await connectionPool.RentAsync("Foo"); // assert Assert.Equal(firstConnection, secondConnection); } }
/// <summary> /// Begins listening for requests. /// </summary> /// <param name="cancellationToken">A token to observe for cancellation.</param> /// <returns>A <see cref="Task"/> representing the asynchronous listening operation.</returns> public Task StartAsync(CancellationToken cancellationToken) { Task.Run(async() => { try { this.tcpListener.Start(); // Stop() makes AcceptSocketAsync() throw an ObjectDisposedException. // This means that when the token is cancelled, the callback action here will be to Stop() the listener, // which in turn throws the exception and it gets caught below, exiting gracefully. cancellationToken.Register(() => this.tcpListener.Stop()); while (!cancellationToken.IsCancellationRequested) { try { var socket = await this.tcpListener.AcceptSocketAsync().ConfigureAwait(false); ISocketConnection socketConnection = this.socketConnectionFactory.Create(socket); if (this.dosDefender?.IsBlocked(socketConnection.SocketIp) ?? false) { // TODO: evaluate if it is worth just leaving the connection open but ignore it, so that they think they are successfully DoSing... // But we would need to think if it is a connection drain attack then... socketConnection.Close(); continue; } this.NewConnection?.Invoke(socketConnection); socketConnection.Closed += this.OnConnectionClose; socketConnection.PacketProcessed += this.AfterConnectionMessageProcessed; this.dosDefender?.LogConnectionAttempt(socketConnection.SocketIp); socketConnection.Read(); } catch (ObjectDisposedException) { // This is normal when the listerner is stopped because of token cancellation. break; } catch (Exception socEx) { this.Logger.Error(socEx.ToString()); } } } catch (SocketException socEx) { this.Logger.Error(socEx.ToString()); } }); // return this to allow other IHostedService-s to start. return(Task.CompletedTask); }
protected override Task HandleAsync( ISocketConnection connection, DataStopMessage message, CancellationToken cancellationToken) { connection.Subscriptions.Unregister(message.Id); return(Task.CompletedTask); }
public void Close() { _socket?.Close(); _socket = null; _mouseSocket?.Close(); _mouseSocket = null; }
public static IApplicationBuilder MapWebSocket( this IApplicationBuilder app, PathString path, ISocketConnection handler, ISocketConnectionManager manager) { return(app.Map(path, _app => _app.UseMiddleware <WebSocketManagerMiddleware>(handler, manager))); }
private void MessageSent ( ISocketConnection sender ) { // In case the last message sent to the client was to warn it an error occured // we should have its handle in there and just close the connection if (clientsToDisconnect.Contains(sender.SocketHandle)) { clientsToDisconnect.Remove(sender.SocketHandle); sender.BeginDisconnect(); } }
protected override async Task HandleAsync( ISocketConnection connection, DataStartMessage message, CancellationToken cancellationToken) { IQueryRequestBuilder requestBuilder = QueryRequestBuilder.New() .SetQuery(message.Payload.Query) .SetQueryName(message.Payload.QueryName) .SetOperation(message.Payload.OperationName) .SetVariableValues(message.Payload.Variables) .SetProperties(message.Payload.Extensions) .SetServices(connection.RequestServices); if (_requestInterceptors != null) { for (var i = 0; i < _requestInterceptors.Length; i++) { await _requestInterceptors[i].OnCreateAsync( connection, requestBuilder, cancellationToken) .ConfigureAwait(false); } } IExecutionResult result = await _queryExecutor.ExecuteAsync( requestBuilder.Create(), cancellationToken) .ConfigureAwait(false); switch (result) { case IResponseStream responseStream: connection.Subscriptions.Register( new Subscription( connection, responseStream, message.Id)); break; case IReadOnlyQueryResult queryResult: using (queryResult) { await HandleQueryResultAsync( connection, message, queryResult, cancellationToken) .ConfigureAwait(false); } break; default: throw new NotSupportedException(); } }
public SocketListener(ISocketConnection connection /*, IDataConverter dataConverter*/) { //_dataConverter = dataConverter; _connection = connection; _listener = new Socket( _connection.AddressFamily, _connection.SocketType, _connection.ProtocolType); }
internal void DoOnSSLClientAuthenticate(ISocketConnection connection, out string serverName, ref X509Certificate2Collection certs, ref bool checkRevocation) { serverName = String.Empty; if (FOnSSLClientAuthenticateEvent != null) { FOnSSLClientAuthenticateEvent(connection, out serverName, ref certs, ref checkRevocation); } }
public WebSocketManagerMiddleware( RequestDelegate next, ISocketConnection handler, ISocketConnectionManager manager) { _next = next; _handler = handler; _manager = manager; }
public MessageProcessor( ISocketConnection connection, IMessagePipeline pipeline, PipeReader reader) { _connection = connection; _pipeline = pipeline; _reader = reader; }
public override void OnConnected(ConnectionEventArgs e) { connection = e.Connection; connection.BeginReceive(); if (Connected != null) { Connected(e.Connection); } ConnectEvent.Set(); }
private Mock <IFactory <ISocketConnection> > CreateFactory(ISocketConnection main, ISocketConnection mouse) { var mock = new Mock <IFactory <ISocketConnection> >(); mock.SetupSequence(x => x.Create()) .Returns(main) .Returns(mouse); return(mock); }
public void Route(ISocketConnection socketConnection) { var httpSocketConnection = socketConnection as SocketConnection; if (httpSocketConnection == null) { throw new StreamRouterException("HttpStreamRouter can only accept SocketConnection"); } var streamRouteObject = new HttpStreamRouteObject(httpSocketConnection, this); objects.Add(streamRouteObject); httpSocketConnection.Disconnected += () => objects.Remove(streamRouteObject); }
private static void client_OnSSLClientAuthenticate(ISocketConnection connection, out string serverName, ref X509Certificate2Collection certs, ref bool checkRevocation) { serverName = "ALAZ Library"; X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); certs = store.Certificates.Find(X509FindType.FindBySubjectName, serverName, true); checkRevocation = false; store.Close(); }
public ConnectingViewModel(IForegroundUpdateService foregroundUpdateService, ISocketConnection socketConnection) { _connection = socketConnection; foregroundUpdateService.OnRegistrationStatusUpdated += OnRegistrationStatusUpdated; ConnectCommand = new DelegateCommand(OnConnectCommandExecute, OnConnectCommandCanExecute); ShowSettings = new DelegateCommand(() => OnShowSettings?.Invoke()); UpdateStatus(); }
private void FailureRaised ( ISocketConnection sender, Exception ex ) { // since the client generated an exceptipon we will disconnect it // as soon as the error message below is sent clientsToDisconnect.Add(sender.SocketHandle); // we warn the client something happened Nuxleus.Bucker.Message m = new Nuxleus.Bucker.Message(); m.Type = "error"; m.Op = null; m.Error = new Nuxleus.Bucker.Error(); m.Error.Type = "internal-server-error"; m.Error.Code = 500; sender.BeginSend(Nuxleus.Bucker.Message.Serialize(m)); }
public override void OnSymmetricAuthenticate(ISocketConnection connection, out RSACryptoServiceProvider serverKey, out byte[] signMessage) { /* * A RSACryptoServiceProvider is needed to encrypt and send session key. * In server side you need public and private key to decrypt session key. * In client side tou need only public key to encrypt session key. * * You can create a RSACryptoServiceProvider from a string (file, registry), a CspParameters or a certificate. * The following certificate and instructions is in MakeCert folder. * */ //----- Sign Message! signMessage = new byte[] { 0x1E, 0xF0, 0x5F, 0x4D, 0x2B, 0x33, 0xCE, 0xB0, 0x12, 0x29, 0x31, 0xCA, 0xEF, 0xAB, 0xEC, 0x97, 0xB3, 0x73, 0x2E, 0xDD, 0x2D, 0x58, 0xAC, 0xE9, 0xE0, 0xCC, 0x14, 0xDC, 0x14, 0xEF, 0x97, 0x64, 0x38, 0xC6, 0x1C, 0xD8, 0x87, 0xFC, 0x30, 0xD5, 0x79, 0xE4, 0x10, 0x2C, 0xFE, 0x98, 0x30, 0x2C, 0xFF, 0xAE, 0x51, 0xD5, 0x47, 0x1D, 0x4D, 0xC5, 0x43, 0x75, 0x6C, 0x5E, 0x32, 0xF2, 0x9C, 0x22, 0x51, 0xBE, 0xA2, 0xC5, 0x31, 0x19, 0xAE, 0x21, 0x3D, 0x9A, 0xF2, 0x78, 0x90, 0x19, 0xCF, 0x97, 0xA5, 0x75, 0x99, 0xB3, 0xFD, 0x31, 0xE6, 0xB5, 0x7F, 0xFD, 0xD0, 0x37, 0x26, 0xC2, 0x7B, 0x27, 0x18, 0x43, 0xED, 0xD9, 0xC8, 0x5A, 0xF5, 0xE0, 0xDA, 0x33, 0x41, 0x3A, 0xC8, 0xE7, 0x4A, 0x5C, 0x9D, 0x48, 0x95, 0x22, 0x56, 0x2F, 0x62, 0x20, 0xD8, 0xEC, 0x46, 0x52, 0x49, 0x76, 0xFB, 0x7B }; //----- Using Certificate Store! X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); X509Certificate2 certificate = store.Certificates.Find(X509FindType.FindBySubjectName, "ALAZ Library", true)[0]; serverKey = new RSACryptoServiceProvider(); serverKey.FromXmlString(certificate.PrivateKey.ToXmlString(true)); store.Close(); }
public override void OnSSLClientAuthenticate(ISocketConnection connection, out string serverName, ref X509Certificate2Collection certs, ref bool checkRevocation) { /* //----- Using client certificate! //----- The following certificate and instructions is in CertificateCreation folder. X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); certs = store.Certificates.Find(X509FindType.FindBySubjectName, serverName, false); store.Close(); */ //----- Check server certificate! serverName = "TESTCERT"; checkRevocation = false; }
private void BlipReceived ( ISocketConnection sender, IMessage message ) { Notification n = Notification.Parse(message.InnerMessage); if ((n.Id != null) && (n.Id != String.Empty)) { // Just ensure that we don't run into some kind of race condition lock (processedLock) { if (!processed.Contains(n.Id)) { processed.Add(n.Id); } else { // The blip has already been processed return; } } if (Received != null) { Received(n); } else { notifications.Enqueue(n); } } }
public override void OnSSLServerAuthenticate(ISocketConnection connection, out X509Certificate2 certificate, out bool clientAuthenticate, ref bool checkRevocation) { //----- Set server certificate, client authentication and certificate revocation! //----- Look at the CertificateCreation folder for instructions /* //----- Using Certificate Store! X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); certificate = store.Certificates.Find(X509FindType.FindBySubjectName, "TESTCERT", false)[0]; store.Close(); */ //----- Using pfx/p12 file! certificate = new X509Certificate2(@"..\..\..\..\CertificateCreation\cert.p12", "12345"); clientAuthenticate = false; checkRevocation = false; }
private void QueueMessageReceived ( ISocketConnection sender, IMessage message ) { Nuxleus.Bucker.Message m = Nuxleus.Bucker.Message.Parse(message.InnerMessage); switch (m.Op.Type) { case OperationType.ListMessages: HandleListOfNewMessages(m); break; case OperationType.GetMessage: HandleMessageReceived(m); break; default: // we are not interested in processing any other message type break; } }
public override void OnSSLClientAuthenticate(ISocketConnection connection, out string serverName, ref X509Certificate2Collection certs, ref bool checkRevocation) { serverName = "ALAZ Library"; //----- Using client certificate! //----- The following certificate and instructions is in MakeCert folder. //X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); //store.Open(OpenFlags.ReadOnly); //certs = store.Certificates.Find(X509FindType.FindBySubjectName, serverName, false); checkRevocation = false; //store.Close(); }
public override void OnSSLServerAuthenticate(ISocketConnection connection, out X509Certificate2 certificate, out bool clientAuthenticate, ref bool checkRevocation) { //----- Set server sertificate, client authentication and certificate revocation! //----- The following certificate and instructions is in MakeCert folder. X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName, "ALAZ Library", false); certificate = certs[0]; clientAuthenticate = false; checkRevocation = false; store.Close(); }
public ConnectionEventArgs(ISocketConnection connection) { FConnection = connection; }
public ExceptionEventArgs(ISocketConnection connection, Exception exception) : base(connection) { FException = exception; }
public virtual void OnSymmetricAuthenticate(ISocketConnection connection, out RSACryptoServiceProvider serverKey) { serverKey = new RSACryptoServiceProvider(); serverKey.Clear(); }
private void MessageReceived(ISocketConnection sender, IMessage message) { if (clientsToDisconnect.Contains(sender.SocketHandle)) { // if the client has been scheduled to be closed we don't process any of its // incoming data return; } Nuxleus.Bucker.Message m = Nuxleus.Bucker.Message.Parse(message.InnerMessage); Nuxleus.Bucker.Message responseToSend = null; switch (m.Op.Type) { case OperationType.GetMessage: responseToSend = HandleGetMessageRequest(m); break; case OperationType.ListMessages: responseToSend = HandleListMessagesRequest(m); break; case OperationType.PushMessage: Console.WriteLine(m.ToString()); responseToSend = HandlePushMessageRequest(m); break; case OperationType.DeleteMessage: responseToSend = HandleDeleteMessageRequest(m); break; case OperationType.NewQueue: responseToSend = HandleNewQueueRequest(m); break; case OperationType.DeleteQueue: responseToSend = HandleDeleteQueueRequest(m); break; case OperationType.ListQueues: responseToSend = HandleListQueuesRequest(m); break; default: responseToSend = new Nuxleus.Bucker.Message(); responseToSend.Type = "error"; responseToSend.Op = null; responseToSend.Error = new Nuxleus.Bucker.Error(); responseToSend.Error.Type = "operation-not-allowed"; responseToSend.Error.Code = 405; break; } if (responseToSend != null) { sender.BeginSend(Nuxleus.Bucker.Message.Serialize(responseToSend)); responseToSend = null; } }
public void BeginSendTo(ISocketConnection connection, byte[] buffer) { Host.BeginSendTo((BaseSocketConnection)connection, buffer); }
private void ClientConnected ( ISocketConnection sender ) { clients.Add(sender); }
public virtual void OnSSLServerAuthenticate(ISocketConnection connection, out X509Certificate2 certificate, out bool clientAuthenticate, ref bool checkRevocation) { certificate = new X509Certificate2(); clientAuthenticate = true; }
private void ClientConnected ( ISocketConnection sender ) { // we are now connected to the queue server // let's ensure the queues we monitor are created too Nuxleus.Bucker.Message nq = new Nuxleus.Bucker.Message(); nq.Op.Type = OperationType.NewQueue; foreach (string queueId in monitoredQueues) { nq.QueueId = queueId; sender.BeginSend(Nuxleus.Bucker.Message.Serialize(nq)); } StartMonitoring(); }
static void client_OnSymmetricAuthenticate(ISocketConnection connection, out System.Security.Cryptography.RSACryptoServiceProvider serverKey, out byte[] signMessage) { //----- Sign Message! signMessage = new byte[] { 0x1E, 0xF0, 0x5F, 0x4D, 0x2B, 0x33, 0xCE, 0xB0, 0x12, 0x29, 0x31, 0xCA, 0xEF, 0xAB, 0xEC, 0x97, 0xB3, 0x73, 0x2E, 0xDD, 0x2D, 0x58, 0xAC, 0xE9, 0xE0, 0xCC, 0x14, 0xDC, 0x14, 0xEF, 0x97, 0x64, 0x38, 0xC6, 0x1C, 0xD8, 0x87, 0xFC, 0x30, 0xD5, 0x79, 0xE4, 0x10, 0x2C, 0xFE, 0x98, 0x30, 0x2C, 0xFF, 0xAE, 0x51, 0xD5, 0x47, 0x1D, 0x4D, 0xC5, 0x43, 0x75, 0x6C, 0x5E, 0x32, 0xF2, 0x9C, 0x22, 0x51, 0xBE, 0xA2, 0xC5, 0x31, 0x19, 0xAE, 0x21, 0x3D, 0x9A, 0xF2, 0x78, 0x90, 0x19, 0xCF, 0x97, 0xA5, 0x75, 0x99, 0xB3, 0xFD, 0x31, 0xE6, 0xB5, 0x7F, 0xFD, 0xD0, 0x37, 0x26, 0xC2, 0x7B, 0x27, 0x18, 0x43, 0xED, 0xD9, 0xC8, 0x5A, 0xF5, 0xE0, 0xDA, 0x33, 0x41, 0x3A, 0xC8, 0xE7, 0x4A, 0x5C, 0x9D, 0x48, 0x95, 0x22, 0x56, 0x2F, 0x62, 0x20, 0xD8, 0xEC, 0x46, 0x52, 0x49, 0x76, 0xFB, 0x7B }; //----- Using string! //----- You must get the public key xml from the ALAZ certificate in you server machine. //----- Uncomment the following lines to get the public key from certificate. //---- Get certificate! // X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); // store.Open(OpenFlags.ReadOnly); // X509Certificate2 certificate = store.Certificates.Find(X509FindType.FindBySubjectName, "ALAZ Library", true)[0]; //---- Get public key string! // string publicKey = certificate.PrivateKey.ToXmlString(false); serverKey = new RSACryptoServiceProvider(); serverKey.FromXmlString("<RSAKeyValue><Modulus>x66+m1J+bNfaDmUCDl/XEi5tZUSPvtJ1AxsZAR2awHI+xKtB8320oBZiKDuEY0MticpMtfvEkBGDSYXtMCxtpQ+4B6DydwwoQhUc+XDHNnCJ3agCDLQ30Tt/lDLMvEVzyXCgaC7J6KM9PT533b6Khlz96gNIht7e0sSDAVP76Hc=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"); }
private void BlipReceived ( ISocketConnection sender, IMessage message ) { Notification n = Notification.Parse(message.InnerMessage); postOffice.Post(n); }
public virtual void OnSSLClientAuthenticate(ISocketConnection connection, out string serverName, ref X509Certificate2Collection certs, ref bool checkRevocation) { serverName = String.Empty; }