public void Handle(HttpListenerRequest req, HttpListenerResponse res) { var authorizeRequestIntent = RequestReader.ReadBody <AuthorizeUserCommand>(req); if (!authorizeRequestIntent.Found) { ResponseWriter.Write(res, HttpStatusCode.Unauthorized, ""); return; } var authorizeRequest = authorizeRequestIntent.Get(); if (!authorizeRequest.IsValid()) { ResponseWriter.Write(res, HttpStatusCode.Unauthorized, ""); return; } var authorized = _bll.Authorize(authorizeRequest); if (!authorized) { ResponseWriter.Write(res, HttpStatusCode.Unauthorized, ""); return; } var response = new AuthorizeUserResponse(authorized); var body = JsonSerializer.Serialize(response); ResponseWriter.Write(res, body); }
public async Task ReadGet() { var mockHttpRequest = new MockHttpRequest { Query = new QueryCollection( new Dictionary <string, StringValues> { { "query", new StringValues("theQuery") }, { "operation", new StringValues("theOperation") }, { "variables", new StringValues(JsonConvert.SerializeObject( new Inputs(new Dictionary <string, object> { { "key", "value" } }))) } }) }; var result = RequestReader.ReadGet(mockHttpRequest); await Verifier.Verify(new { result.inputs, result.operation, result.query }); }
public async Task OnClientStream(string p_title, RequestReader p_reader) { while (await p_reader.MoveNext()) { Log.Information("服务端读取:" + p_reader.Val <string>()); } }
public void Handle(HttpListenerRequest req, HttpListenerResponse res) { var credentialsIntent = RequestReader.ReadBody <AuthenticateUserCommand>(req); if (!credentialsIntent.Found) { ResponseWriter.Write(res, HttpStatusCode.Unauthorized, ""); return; } var credentials = credentialsIntent.Get(); if (!credentials.IsValid()) { ResponseWriter.Write(res, HttpStatusCode.Unauthorized, ""); return; } var sessionTokenIntent = _bll.Authenticate(credentials); if (!sessionTokenIntent.Found) { ResponseWriter.Write(res, HttpStatusCode.Unauthorized, ""); return; } var response = new AuthenticateUserResponse(sessionTokenIntent.Get()); var body = JsonSerializer.Serialize(response); ResponseWriter.Write(res, body); }
private void ProcessRequest(ref ArraySegment <byte> data) { var requestBuffer = data.Array !; var requestBody = (ReadOnlySpan <byte>)data; var ret = RequestReader.Parse(ref requestBody, BaseUri) !; HttpRequest = ret.Item1; ContentHeaders = ret.Item2; Options.RequestProcessor !.Process(this, HttpRequest); var pooledBuffer = Tunnel.ArrayPool.Rent(data.Count + 8096); // write request back int requestLength; using (var memoryStream = new MemoryStream(pooledBuffer)) { using (var streamWriter = new StreamWriter(memoryStream, leaveOpen: true)) { RequestWriter.WriteRequest(streamWriter, HttpRequest, requestBody.Length, ContentHeaders); } requestLength = (int)memoryStream.Position; } requestBody.CopyTo(pooledBuffer.AsSpan(requestLength)); data = new(pooledBuffer, 0, requestLength + requestBody.Length); // return current buffer Tunnel.ArrayPool.Return(requestBuffer); }
public bool Connect(DnsInfo dns) { try { Client = new TcpClient(); Client.Connect(dns.IPAddress, dns.Port); IsConnected = true; if (dns.SSL) { Stream = new SslStream(Client.GetStream(), true); } else { Stream = Client.GetStream(); } byte[] request = CreateRequest(dns); Stream.Write(request, 0, request.Length); byte[] buffer = new byte[8192]; int len = Stream.Read(buffer, 0, buffer.Length); string response = Encoding.UTF8.GetString(buffer, 0, len); string first = response.Substring(0, 50); if (!first.Contains(" 101 ")) { Disconnect(); throw new NotSupportedException("Server doesn't support web socket protocol"); } RequestReader reader = new RequestReader(); HttpRequest requestResponse = reader.Read(response); if (!requestResponse.Headers.ContainsKey("Sec-WebSocket-Accept")) { throw new InvalidOperationException("Handshaking error, server didn't response Sec-WebSocket-Accept"); } string rkey = requestResponse.Headers["Sec-WebSocket-Accept"]; using (SHA1 sha1 = SHA1.Create()) { byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(WebSocketKey + HttpServer.WEBSOCKET_GUID)); string fkey = Convert.ToBase64String(hash); if (rkey != fkey) { throw new InvalidOperationException("Handshaking error, Invalid Key"); } } OnConnected(); Task.Factory.StartNew(Read); return(true); } catch { Disconnect(); return(false); } }
public void ReadRequest_NoCampsites_ReturnsFalse() { string FilePath = "..\\..\\..\\RequestFiles\\no-campsites.json"; string FileContents = File.ReadAllText(FilePath); var test = new RequestReader(); var e = test.ReadRequest(FileContents); Assert.AreEqual(e, false); }
async Task <Task> ProcessClientRequest(Socket socket, ClientManager clientManager) { var pipe = new Pipe(new PipeOptions(null, null, null, PauseWriterThreshold, ResumeWriterThreshold)); RequestReader requestReader = new RequestReader(clientManager, _cmdManager); Task writing = FillPipeAsync(socket, pipe.Writer, clientManager); Task reading = ReadPipeAsync(pipe.Reader, clientManager, requestReader); return(Task.WhenAll(reading, writing)); }
public void ReadRequest_ValidRequest_ReturnsTrue() { string FilePath = "..\\..\\..\\RequestFiles\\valid-request.json"; string FileContents = File.ReadAllText(FilePath); var test = new RequestReader(); var e = test.ReadRequest(FileContents); Assert.AreEqual(e, true); }
public void ReadRequest_NoSearchProperty_ReturnsFalse() { string FilePath = "..\\..\\..\\RequestFiles\\no-search-property.json"; string FileContents = File.ReadAllText(FilePath); var test = new RequestReader(); var e = test.ReadRequest(FileContents); Assert.AreEqual(e, false); }
public async Task Post(CancellationToken cancellation) { var result = await RequestReader.ReadPost(Request, cancellation); await Execute( result.query, result.operation, result.attachments, result.inputs, cancellation); }
public async Task ReadPost() { var attachment1Bytes = Encoding.UTF8.GetBytes("Attachment1 Text"); var attachment2Bytes = Encoding.UTF8.GetBytes("Attachment2 Text"); var mockHttpRequest = new MockHttpRequest { Form = new FormCollection( new Dictionary <string, StringValues> { { "query", new StringValues("theQuery") }, { "operation", new StringValues("theOperation") }, { "variables", new StringValues(JsonConvert.SerializeObject( new Inputs(new Dictionary <string, object> { { "key", "value" } }))) } }, new FormFileCollection { new FormFile(new MemoryStream(attachment1Bytes), 0, attachment1Bytes.Length, "attachment1", "attachment1.txt") { Headers = new HeaderDictionary { { "file1Header", "file1HeaderValue" } } }, new FormFile(new MemoryStream(attachment2Bytes), 0, attachment2Bytes.Length, "attachment2", "attachment2.txt") { Headers = new HeaderDictionary { { "file2Header", "file2HeaderValue" } } }, }), }; var result = await RequestReader.ReadPost(mockHttpRequest); await Verifier.Verify(new { result.attachments, result.inputs, result.operation, result.query }); }
public async Task OnDuplexStream(string p_title, RequestReader p_reader, ResponseWriter p_writer) { while (await p_reader.MoveNext()) { Log.Information("服务端读取:" + p_reader.Val <string>()); var msg = "++" + p_reader.Val <string>(); await p_writer.Write(msg); Log.Information("服务端写入:" + msg); } }
public void CONNECT_Should_be_FALSE_Different_Request_Type() { //Given const string request = "GET www.dacos.com.ro/favicon.ico HTTP/1.1"; var reader = new RequestReader(request); //When reader.CheckRequestType(); //Then Assert.False(reader.IsConnect); }
public void GET_Should_be_TRUE_for_SIMPLE_Request() { //Given const string request = "GET www.dacos.com.ro/favicon.ico HTTP/1.1"; var reader = new RequestReader(request); //When reader.CheckRequestType(); //Then Assert.True(reader.IsGet); }
public void GET_Should_be_FALSE_Different_Request() { //Given const string request = " CONNECT www.google-analytics.com:443 HTTP/1.1 "; var reader = new RequestReader(request); //When reader.CheckRequestType(); //Then Assert.False(reader.IsGet); }
public void CONNECT_Should_be_TRUE_Request_Has_EmptySpaces() { //Given const string request = " CONNECT www.google-analytics.com:443 HTTP/1.1 "; var reader = new RequestReader(request); //When reader.CheckRequestType(); //Then Assert.True(reader.IsConnect); }
public void Test_Port_Should_Return_Zero_NO_Port_was_Found() { //Given const string request = "CONNECT www.google-analytics.com: 221 HTTP/1.1 "; var reader = new RequestReader(request); //When int port = reader.Port; //Then Assert.Equal(0, port); }
public void Test_Port_Should_correctly_Extract_443_PORT_From_HostHeader() { //Given const string request = "Header1\r\nHeader2\r\nHost: Andrei:443\r\nHeader3\r\n"; var reader = new RequestReader(request); //When int port = reader.Port; //Then Assert.Equal(443, port); }
public void Test_HOST_When_HOSTHEADER_appears_Later_duirng_Request() { //Given const string request = "Header1\r\nHeader2\r\nHost: Andrei\r\nHeader3\r\n"; var reader = new RequestReader(request); //When string host = reader.Host; //Then Assert.Equal("Andrei", host); }
async Task Parse(string chars) { await using var stream = new MemoryStream(Encoding.UTF8.GetBytes(chars)) { Position = 0 }; var(query, inputs, operation) = await RequestReader.ReadBody(stream, CancellationToken.None); await Verify(new { query, inputs, operation }); }
public void Test_HOST_Should_Return_NULL_When_NO_Host_was_FOUND() { //Given const string request = "Header1\r\nHeader2\r\nHos: Andrei\r\nHeader3\r\n"; var reader = new RequestReader(request); //When string host = reader.Host; //Then Assert.Null(host); }
public void Should_Correctly_Extract_HOST_Simple_Case_GET_Request() { //Given const string request = "GET something\r\nHeader\r\nHost: Andrei\r\n"; var reader = new RequestReader(request); //When string host = reader.Host; //Then Assert.Equal("Andrei", host); }
public void Test_HOST_Should_Eliminate_Port_From_HostHeader_ConnectRequest() { //Given const string request = "Header1\r\nHost: Andrei:443\r\nHeader3\r\n"; var reader = new RequestReader(request); //When string host = reader.Host; //Then Assert.Equal("Andrei", host); }
public void ShouldProcessTestsObjectNoThrow(string jsonString) { var moqMemoryStream = new Mock <MemoryStream>(); moqMemoryStream.Setup(x => x.CanRead).Returns(true); var moqReader = new Mock <Reader>(moqMemoryStream.Object); var objFactory = new ProtocolObjectFactory(new ProtocolObjectManager()); var requestReader = new RequestReader(moqReader.Object, objFactory); requestReader.CurrentObjectData = jsonString; var createdObject = requestReader.CreateObjectFromData(); }
/// <summary> /// Create a request model by first deserializing the message body and then parsing properties from /// values (such as route data) /// </summary> /// <typeparam name="TRequest"> /// The type of the request model that we want to create. /// </typeparam> /// <returns>An instance of Type requestType</returns> public async Task <TRequest> CreateRequestModelAsync <TRequest>() { // Try to deserialize the message body to the appropriate request model or create a default instance var requestReader = new RequestReader(_httpContext, _inputFormatter); var model = await requestReader.DeserializeRequestAsync <TRequest>(); // Merge in any values from the value parsers foreach (var parser in _valueParsers) { parser.ParseValues(model); } // Return the result return((TRequest)model); }
public void RequestReadWithPayloadTest() { var requestMessage = new NetMQMessage(); var requester = Guid.NewGuid(); requestMessage.Append(requester.ToByteArray()); requestMessage.AppendEmptyFrame(); requestMessage.Append((int)MessageType.Error); requestMessage.Append(JsonConvert.SerializeObject(ErrorCode.InvocationError)); var request = RequestReader.Read <ErrorCode>(new NoEncryption(), requestMessage); Assert.AreEqual(requester, new Guid(request.From)); Assert.AreEqual(MessageType.Error, request.Type); Assert.AreEqual(ErrorCode.InvocationError, request.Payload); }
public void RequestReadWithoutPayloadTest() { var requestMessage = new NetMQMessage(); var requester = Guid.NewGuid(); requestMessage.Append(requester.ToByteArray()); requestMessage.AppendEmptyFrame(); requestMessage.Append((int)MessageType.Acknowledge); requestMessage.AppendEmptyFrame(); var request = RequestReader.Read(new NoEncryption(), requestMessage); Assert.AreEqual(requester, new Guid(request.From)); Assert.AreEqual(MessageType.Acknowledge, request.Type); Assert.IsNull(request.Payload); }
public async Task ProcessAsync() { RawHttpRequest httpRequest; try { httpRequest = await RequestReader.ReadAsync(_clientSession.CancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { _clientSession.Close(); return; } catch (Exception exception) { HttpNetTrace.Error(nameof(HttpSessionHandler), exception, "Unhandled exceptio while processing HTTP request."); _clientSession.Close(); return; } var httpResponse = new RawHttpResponse { Version = httpRequest.Version, Headers = new Dictionary <string, string>(), StatusCode = (int)HttpStatusCode.OK }; var httpContext = new HttpContext(httpRequest, httpResponse, _clientSession, this); await _clientSession.HandleHttpRequestAsync(httpContext); if (httpContext.Response != null) { await ResponseWriter.WriteAsync(httpContext.Response, _clientSession.CancellationToken); HttpNetTrace.Verbose(nameof(HttpSessionHandler), "Response '{0}' sent to '{1}'.", httpContext.Response.StatusCode, _clientSession.Client.Identifier); } if (httpContext.CloseConnection) { _clientSession.Close(); } }
public void AddClient(Socket socket, ClientManager clientManager) { var key = GetKey(socket); Pipe pipe = new Pipe(new PipeOptions(null, null, null, PauseWriterThreshold, ResumeWriterThreshold)); RequestReader requestReader = new RequestReader(clientManager, _cmdManager); lock (_clients) { _clients.Add(socket); _pipes.Add(key, pipe); if (_clients.Count == 1) { Monitor.Pulse(_clients); } } ReadPipeAsync(pipe.Reader, clientManager, requestReader); }
void InnerRun () { requestId = -1; broker = null; var rr = new RequestReader (client); if (rr.ShuttingDown) { Close (); server.Stop (); return; } string vhost = rr.Request.GetRequestHeader ("Host"); int port = -1; if (vhost != null) { int lead = vhost.IndexOf('['); int follow = lead >= 0 ? vhost.IndexOf(']') : -1; if (follow > lead) { //ipv6 address int colon = vhost.IndexOf("]:", StringComparison.Ordinal); if (colon != -1) { Int32.TryParse (vhost.Substring (colon + 2), out port); vhost = vhost.Substring(0, colon + 1); } } else { //ipv4 or hostname int colon = vhost.IndexOf (':'); if (colon != -1) { Int32.TryParse (vhost.Substring (colon + 1), out port); vhost = vhost.Substring (0, colon); } } if (port <= 0 || port > 65535) { //No port specified, Int32.TryParse failed or invalid port number port = 80; } } string vServerName = rr.Request.GetVirtualServerName () ?? vhost; VPathToHost vapp; string vpath = rr.GetUriPath (); string path = rr.GetPhysicalPath (); if (path == null) { vapp = server.GetApplicationForPath (vServerName, port, vpath, false); } else { vapp = GetOrCreateApplication (vServerName, port, path, vpath); } if (vapp == null) { rr.NotFound (); Stream.Close (); Stream = null; return; } var host = (ModMonoApplicationHost) vapp.AppHost; if (host == null) { rr.NotFound (); Stream.Close (); Stream = null; return; } modRequest = rr.Request; if (!server.SingleApplication) { broker = (ModMonoRequestBroker) vapp.RequestBroker; broker.UnregisterRequestEvent += OnUnregisterRequest; requestId = broker.RegisterRequest (this); } host.ProcessRequest (requestId, modRequest.GetHttpVerbName(), modRequest.GetQueryString(), modRequest.GetUri(), modRequest.GetProtocol(), modRequest.GetLocalAddress(), modRequest.GetServerPort(), modRequest.GetRemoteAddress(), modRequest.GetRemotePort(), modRequest.GetRemoteName(), modRequest.GetAllHeaders(), modRequest.GetAllHeaderValues(), (requestId == -1) ? this : null); }