public async Task <int> ReadBytesAsync(byte[] bytes) { int otherIndex = 0; if (currentIndex < buffer.Length) { for ( ; currentIndex < buffer.Length && otherIndex < bytes.Length; currentIndex++, otherIndex++) { bytes[otherIndex] = buffer.GetByte(currentIndex); } } while (!headersRead || (buffer.Length == buffer.Capacity && otherIndex < bytes.Length)) { await inputStream.ReadAsync(buffer, buffer.Capacity, DefaultStreamOptions); headersRead = true; for (currentIndex = 0; currentIndex < buffer.Length && otherIndex < bytes.Length; currentIndex++, otherIndex++) { bytes[otherIndex] = buffer.GetByte(currentIndex); } } return(otherIndex); }
private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { socket = args.Socket; var dr = new DataReader(socket.InputStream); /// GET ヘッダを取り出し StringBuilder request = new StringBuilder(); uint BufferSize = 1024; using (IInputStream input = socket.InputStream) { byte[] data = new byte[BufferSize]; IBuffer buffer = data.AsBuffer(); uint dataRead = BufferSize; while (dataRead == BufferSize) { await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial); request.Append(Encoding.UTF8.GetString(data, 0, data.Length)); dataRead = buffer.Length; } } // GET method を取り出し string requestMethod = request.ToString().Split('\n')[0]; string[] requestParts = requestMethod.Split(' '); var text = requestParts[1]; /// GETコマンドの受信イベント if (this.OnReceived != null) { OnReceived(text); } }
public Windows.Foundation.IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return(AsyncInfo.Run <IBuffer, uint>(async(cancellationToken, progress) => { progress.Report(0); try { if (inputStream == null) { await SendRequesAsync().ConfigureAwait(false); } } catch (Exception ex) { Debug.WriteLine(ex); throw; } IBuffer result = await inputStream.ReadAsync(buffer, count, options).AsTask(cancellationToken, progress).ConfigureAwait(false); // Move position forward. requestedPosition += result.Length; Debug.WriteLine("requestedPosition = {0:N0}", requestedPosition); return result; })); }
public static async Task <StreamReaderAsync> Create(IInputStream inputStream) { var stream = new StreamReaderAsync(inputStream); await inputStream.ReadAsync(stream.buffer, stream.buffer.Capacity, DefaultStreamOptions); return(stream); }
private void ReadMore() { IBuffer buffer = new Windows.Storage.Streams.Buffer(1024); readOperation = inputStream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.Partial); readOperation.Completed = OnReadCompleted; }
/// <summary> /// Nimmt den Request entgegen und gibt diesen als StringBuilder Objekt zurück /// </summary> /// <param name="inputStream"></param> /// <returns></returns> private static async Task <StringBuilder> HandleHttpRequest(IInputStream inputStream) { try { StringBuilder requestString = new StringBuilder(); using (IInputStream input = inputStream) { byte[] data = new byte[BufferSize]; IBuffer buffer = data.AsBuffer(); uint dataRead = BufferSize; while (dataRead == BufferSize) { await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial); requestString.Append(Encoding.UTF8.GetString(data, 0, data.Length)); dataRead = buffer.Length; } } return(requestString); } catch (Exception exception) { Log.Log.WriteException(exception); return(new StringBuilder()); } }
/// <summary> /// Bitmap画像を取得する(Zipファイル用) /// </summary> /// <param name="entry"></param> /// <param name="decodePixelWidth"></param> /// <returns></returns> public static async Task <BitmapImage> CreateBitmap(ZipArchiveEntry entry, int decodePixelWidth) { BitmapImage bitmap = null; using (await m_asyncLock.LockAsync()) { using (Stream entryStream = entry.Open()) { using (IInputStream inputStream = entryStream.AsInputStream()) { byte[] buffBytes = new byte[entry.Length]; await inputStream.ReadAsync(buffBytes.AsBuffer(), (uint)buffBytes.Length, InputStreamOptions.None); using (MemoryStream memStream = new MemoryStream(buffBytes)) { bitmap = new BitmapImage(); if (decodePixelWidth > 0) { bitmap.DecodePixelType = DecodePixelType.Logical; bitmap.DecodePixelWidth = decodePixelWidth; } await bitmap.SetSourceAsync(memStream.AsRandomAccessStream()); } } } } return(bitmap); }
private async void ProcessRequestAsync(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { StringBuilder requestStringBuilder = new StringBuilder(); using (IInputStream input = args.Socket.InputStream) { byte[] data = new byte[BufferSize]; IBuffer buffer = data.AsBuffer(); uint dataRead = BufferSize; while (dataRead == BufferSize) { await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial); requestStringBuilder.Append(Encoding.UTF8.GetString(data, 0, data.Length)); dataRead = buffer.Length; } } HttpRequest request = ConvertInputStringToHttpRequest(requestStringBuilder.ToString(), args.Socket.Information.RemoteAddress.CanonicalName); HttpResponse response = await this._middlewareManager.Execute(request); using (IOutputStream output = args.Socket.OutputStream) { await this.WriteResponseAsync(response, output); } }
public IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return(AsyncInfo.Run((Func <System.Threading.CancellationToken, IProgress <uint>, Task <IBuffer> >)(async(cancellationToken, progress) => { progress.Report(0); try { if (_inputStream == null) { await SendRequestAsync().ConfigureAwait(false); } } catch (Exception ex) { Debug.WriteLine(ex); throw; } IBuffer result = await _inputStream.ReadAsync(buffer, count, options).AsTask(cancellationToken, progress).ConfigureAwait(false); Position += result.Length; Debug.WriteLine("requestedPosition = {0:N0}", Position); return result; }))); }
public IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { //try //{ // return _inputStream.ReadAsync(buffer, count, options); //} //catch (OperationCanceledException) //{ // return AsyncInfo.Run<IBuffer, uint>((token, progress) => new byte[count].AsBuffer()) //} return(AsyncInfo.Run <IBuffer, uint>(async(token, progress) => { Debug.WriteLine($"Read {count} bytes"); try { var result = await _inputStream.ReadAsync(buffer, count, options); progress.Report(buffer.Length); return result; } catch (OperationCanceledException) { progress.Report(count); var noise = new byte[count]; _rand.NextBytes(noise); return noise.AsBuffer(); } catch (Exception e) { throw; } })); }
/// <summary> /// Responsible for processing (reading, validating and calling answerer) the request asynchronously. /// </summary> /// <param name="socket">The socket received from the Event Arguments.</param> public async void ProcessRequestAsync(StreamSocket socket) { StringBuilder request = new StringBuilder(); using (IInputStream input = socket.InputStream) { byte[] data = new byte[bufferSize]; IBuffer buffer = data.AsBuffer(); uint dataRead = bufferSize; while (dataRead == bufferSize) { await input.ReadAsync(buffer, bufferSize, InputStreamOptions.Partial); request.Append(Encoding.UTF8.GetString(data, 0, data.Length)); dataRead = buffer.Length; } } using (IOutputStream output = socket.OutputStream) { string requestMethod = request.ToString().Split('\n').First(); string[] requestParts = requestMethod.Split(' '); if (requestParts[0] == Constants.WebServer.GETMethod) { await WriteResponseAsync(requestParts[1], output); } else { throw new InvalidDataException(Constants.WebServer.RequestNotSupportedException + requestParts[0]); } } }
private async void ProcessRequestAsync(StreamSocket socket) { // this works for text only StringBuilder request = new StringBuilder(); using (IInputStream input = socket.InputStream) { byte[] data = new byte[BufferSize]; IBuffer buffer = data.AsBuffer(); uint dataRead = BufferSize; while (dataRead == BufferSize) { await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial); request.Append(Encoding.UTF8.GetString(data, 0, data.Length)); dataRead = buffer.Length; } } using (IOutputStream output = socket.OutputStream) { string requestMethod = request.ToString().Split('\n')[0]; string[] requestParts = requestMethod.Split(' '); if (requestParts[0] == "GET") { await WriteResponseAsync(requestParts[1], output); } else { throw new InvalidDataException("HTTP method not supported: " + requestParts[0]); } } }
private async void ProcessRequestAsync(StreamSocket socket) { weatherShield.GreenLEDPin.Write(GpioPinValue.High); // Read in the HTTP request, we only care about type 'GET' StringBuilder request = new StringBuilder(); using (IInputStream input = socket.InputStream) { byte[] data = new byte[bufLen]; IBuffer buffer = data.AsBuffer(); uint dataRead = bufLen; while (dataRead == bufLen) { await input.ReadAsync(buffer, bufLen, InputStreamOptions.Partial); request.Append(Encoding.UTF8.GetString(data, 0, data.Length)); dataRead = buffer.Length; } } using (IOutputStream output = socket.OutputStream) { string requestMethod = request.ToString().Split('\n')[0]; string[] requestParts = requestMethod.Split(' '); await WriteResponseAsync(requestParts, output); } weatherShield.GreenLEDPin.Write(GpioPinValue.Low); }
private async void ProcessRequestAsync(StreamSocket socket) { // Read in the HTTP request, we only care about type 'GET' StringBuilder request = new StringBuilder(); using (IInputStream input = socket.InputStream) { byte[] data = new byte[bufLen]; IBuffer buffer = data.AsBuffer(); uint dataRead = bufLen; while (dataRead == bufLen) { await input.ReadAsync(buffer, bufLen, InputStreamOptions.Partial); request.Append(Encoding.UTF8.GetString(data, 0, data.Length)); dataRead = buffer.Length; } if (RecivedMeg != null) { Debug.WriteLine(request.ToString()); RecivedMeg(request.ToString(), EventArgs.Empty); } } using (IOutputStream output = socket.OutputStream) { string requestMethod = request.ToString().Split('\n')[0]; string[] requestParts = requestMethod.Split(' '); await WriteResponseAsync(requestParts, output); } }
private static async Task <WriteableBitmap> createWriteableBitmap(ZipArchiveEntry entry) { WriteableBitmap writableBitmap = null; using (Stream entryStream = entry.Open()) { using (IInputStream inputStream = entryStream.AsInputStream()) { byte[] buffBytes = new byte[entry.Length]; await inputStream.ReadAsync(buffBytes.AsBuffer(), (uint)buffBytes.Length, InputStreamOptions.None); using (MemoryStream memStream = new MemoryStream(buffBytes)) { BitmapImage bitmap = new BitmapImage(); await bitmap.SetSourceAsync(memStream.AsRandomAccessStream()); memStream.Seek(0, SeekOrigin.Begin); writableBitmap = new WriteableBitmap(bitmap.PixelWidth, bitmap.PixelHeight); await writableBitmap.SetSourceAsync(memStream.AsRandomAccessStream()); } } } return(writableBitmap); }
public async static Task <IBuffer> ReadBuffer(this IInputStream stream, uint length) { var buff = WindowsRuntimeBufferExtensions.AsBuffer(new byte[length]); await stream.ReadAsync(buff, length, InputStreamOptions.Partial); return(buff); } /*
private async static Task <string> GetResponseMessage(UploadOperation uploadOperation) { ResponseInformation responseInformation = uploadOperation.GetResponseInformation(); //uint contentLength = Convert.ToUInt32(responseInformation.Headers["Content-Length"]); uint contentLength = (uint)uploadOperation.Progress.BytesReceived; uint statusCode = responseInformation.StatusCode; IInputStream resultStreamAt = uploadOperation.GetResultStreamAt(0); IBuffer result = await resultStreamAt.ReadAsync( new Windows.Storage.Streams.Buffer(contentLength), contentLength, InputStreamOptions.None); Stream responseStream = result.AsStream(); XDocument xDocument = XDocument.Load(responseStream); foreach (XElement xe in xDocument.Root.Descendants()) { if (xe.Name.LocalName.Equals("Ok")) { return("SUCCESS"); } if (xe.Name.LocalName.Equals("Error")) { return(xe.Value); } } return("Unspecified error submiting video"); }
public async Task DownloadFile(string path, StorageFile destFile) { Uri uri = GetUri($"/api/files/{Utils.EncodePath(path)}/download"); if (uri == null) { return; } using (IRandomAccessStream fileStream = await destFile.OpenAsync(FileAccessMode.ReadWrite)) { using (HttpClient client = GetClient()) { using (IInputStream downloadStream = await client.GetInputStreamAsync(uri)) { const uint capacity = 1_000_000; Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer(capacity); while (true) { await downloadStream.ReadAsync(buffer, capacity, InputStreamOptions.None); if (buffer.Length == 0) { break; } await fileStream.WriteAsync(buffer); } } } } }
/// <summary> /// Main Method to Process async requests /// </summary> /// <param name="socket"></param> private async void ProcessRequestAsync(StreamSocket socket) { try { StringBuilder request = new StringBuilder(); using (IInputStream input = socket.InputStream) { byte[] data = new byte[BufferSize]; IBuffer buffer = data.AsBuffer(); uint dataRead = BufferSize; while (dataRead == BufferSize) { await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial); request.Append(Encoding.UTF8.GetString(data, 0, data.Length)); dataRead = buffer.Length; } } _response = RouteManager.Current.InvokeMethod(request.ToString()); using (IOutputStream output = socket.OutputStream) { await WriteResponseAsync(_response, output); } } catch (Exception ex) { Debug.WriteLine("Error in ProcessRequestAsync: " + ex); } }
/// <summary> /// Process the incoming request /// </summary> /// <param name="socket"></param> private async void processRequestAsync(StreamSocket socket) { try { StringBuilder request = new StringBuilder(); using (IInputStream input = socket.InputStream) { // Convert the request bytes to a string that we understand byte[] data = new byte[BufferSize]; IBuffer buffer = data.AsBuffer(); uint dataRead = BufferSize; while (dataRead == BufferSize) { await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial); request.Append(Encoding.UTF8.GetString(data, 0, data.Length)); dataRead = buffer.Length; } //// Print out the incoming HTTP request in the Trace window. //StringBuilder b = new StringBuilder(); //foreach(char c in data) //{ // b.Append(c); //} //Debug.Write(b); } using (IOutputStream output = socket.OutputStream) { // Parse the request string[] requestParts = request.ToString().Split('\n'); string requestMethod = requestParts[0]; string[] requestMethodParts = requestMethod.Split(' '); // Process the request and write a response to send back to the browser if (requestMethodParts[0] == "GET") { await writeResponseAsync(requestMethodParts[1], output, socket.Information); } else { throw new InvalidDataException("HTTP method not supported: " + requestMethodParts[0]); } } }catch (Exception ex) { Debug.WriteLine("Exception in processRequestAsync(): " + ex.Message); //This exception is thrown when someone clicks on a link while the current page is still loading. This isn't really an exception worth tracking as it will be thrown a lot, but doesn't affect anything. /* * // Log telemetry event about this exception * var events = new Dictionary<string, string> { { "WebServer", ex.Message } }; * TelemetryHelper.TrackEvent("FailedToProcessRequestAsync", events); */ } }
public async Task Start(FarmController theFarmController) { webFarmController = theFarmController; var listener = new StreamSocketListener(); await listener.BindServiceNameAsync("80"); listener.ConnectionReceived += async(sender, args) => { StringBuilder request = new StringBuilder(); using (IInputStream input = args.Socket.InputStream) { byte[] data = new byte[BufferSize]; IBuffer buffer = data.AsBuffer(); uint dataRead = BufferSize; while (dataRead == BufferSize) { await input.ReadAsync( buffer, BufferSize, InputStreamOptions.Partial); request.Append(Encoding.UTF8.GetString( data, 0, data.Length)); dataRead = buffer.Length; } } string query = GetQuery(request); Parse(query); PerformActions(); //now respond to the request and display the current status string myhtml = BuildMyHTMLResponse(query); using (IOutputStream output = args.Socket.OutputStream) { using (Stream response = output.AsStreamForWrite()) { //byte[] html = Encoding.GetEncoding("iso-8859-1").GetBytes(myhtml); byte[] html = Encoding.UTF8.GetBytes(myhtml); MemoryStream bodyStream = new MemoryStream(html); string header = "HTTP/1.1 200 OK\r\n" + $"Content-Length: {bodyStream.Length}\r\n" + "Connection: close\r\n\r\n"; //var headerArray = Encoding.UTF8.GetBytes(header); //byte[] headerArray = Encoding.GetEncoding("iso-8859-1").GetBytes(header); byte[] headerArray = Encoding.UTF8.GetBytes(header); await response.WriteAsync(headerArray, 0, headerArray.Length); await bodyStream.CopyToAsync(response); await response.FlushAsync(); } } }; }
public async void HandleRequest(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { StringBuilder request = new StringBuilder(); string responseHTML = "<html><body>ERROR</body></html>"; // Handle a incoming request // First read the request using (IInputStream input = args.Socket.InputStream) { byte[] data = new byte[BufferSize]; IBuffer buffer = data.AsBuffer(); uint dataRead = BufferSize; while (dataRead == BufferSize) { await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial); request.Append(Encoding.UTF8.GetString(data, 0, data.Length)); dataRead = buffer.Length; } } responseHTML = PrepareResponse(ParseRequest(request.ToString())); // Send a response back using (IOutputStream output = args.Socket.OutputStream) { using (Stream response = output.AsStreamForWrite()) { byte[] bodyArray = Encoding.UTF8.GetBytes(responseHTML); var bodyStream = new MemoryStream(bodyArray); var header = String.Empty; header = "HTTP/1.1 200 OK\r\n" + $"Content-Length: {bodyStream.Length}\r\n" + "Connection: close\r\n\r\n"; if (request.ToString().Contains("csv")) { header = "HTTP/1.1 200 OK\r\n" + $"Content-Length: {bodyStream.Length}\r\n" + $"Content-Type: application/csv" + "Connection: close\r\n\r\n"; } byte[] headerArray = Encoding.UTF8.GetBytes(header); await response.WriteAsync(headerArray, 0, headerArray.Length); await bodyStream.CopyToAsync(response); await response.FlushAsync(); } } }
public static async Task OnReceived(IInputStream dataStream, HostName remoteAddress) { IBuffer buffer = new Windows.Storage.Streams.Buffer(ReadBufferSize); await dataStream.ReadAsync(buffer, ReadBufferSize, InputStreamOptions.None); dataStream.Dispose(); var info = Encoding.UTF8.GetString(buffer.ToArray()); // TODO process unicast }
public async ValueTask <int> StartRecv(ArraySegment <byte> outBuf, CancellationToken cancellationToken = default) { var recvBuf = await inputStream.ReadAsync(outBuf.Array.AsBuffer(outBuf.Offset, outBuf.Count), (uint)outBuf.Count, InputStreamOptions.Partial).AsTask(cancellationToken).ConfigureAwait(false); if (recvBuf.Length == 0) { return(0); } return((int)recvBuf.Length); }
private async void ListenerOnConnectionReceived( StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { StringBuilder request = new StringBuilder(); using (IInputStream input = args.Socket.InputStream) { byte[] data = new byte[BufferSize]; IBuffer buffer = data.AsBuffer(); uint dataRead = BufferSize; while (dataRead == BufferSize) { await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial); request.Append(Encoding.UTF8.GetString(data, 0, data.Length)); dataRead = buffer.Length; } } var lines = request.ToString().Split(new[] { "\r\n", "\n" }, StringSplitOptions.None); var autoRemoteResponse = new Response(); try { var jsonData = lines.Last(); var autoRemoteRequest = Communication.GetRequestFromJson(jsonData); this.RequestReceived?.Invoke(autoRemoteRequest, args.Socket.Information.RemoteAddress); autoRemoteResponse = autoRemoteRequest.ExecuteRequest(); } catch (Exception) { autoRemoteResponse.responseError = "Unknown request type"; } var jsonResponse = JsonConvert.SerializeObject(autoRemoteResponse); using (IOutputStream output = args.Socket.OutputStream) { using (Stream response = output.AsStreamForWrite()) { byte[] bodyArray = Encoding.UTF8.GetBytes(jsonResponse); var bodyStream = new MemoryStream(bodyArray); var header = "HTTP/1.1 200 OK\r\n" + $"Content-Length: {bodyStream.Length}\r\n" + "Connection: close\r\n\r\n"; byte[] headerArray = Encoding.UTF8.GetBytes(header); await response.WriteAsync(headerArray, 0, headerArray.Length); await bodyStream.CopyToAsync(response); await response.FlushAsync(); } } }
public async Task <StorageFile> Download() { if (m_SourceUri == null || m_SourceUri.IsFile) { return(null); } StorageFile tempFile = await m_DestinationStorageFolder.CreateFileAsync(m_DestinationFileName + ".tmp", CreationCollisionOption.GenerateUniqueName); using (HttpClient httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"); HttpResponseMessage response = await httpClient.GetAsync(m_SourceUri, HttpCompletionOption.ResponseHeadersRead); if (response.StatusCode != HttpStatusCode.Ok /*|| * Path.GetFileName(response.RequestMessage.RequestUri.AbsoluteUri) != Path.GetFileName(m_SourceUri.ToString())*/) { string result = await response.Content.ReadAsStringAsync(); throw new Exception(result); } if (response.Content.Headers.ContentLength != null) { m_TotalBytes = response.Content.Headers.ContentLength.Value; } IBuffer buffer = new Windows.Storage.Streams.Buffer(m_bufferSize); using (IRandomAccessStream fileStream = await tempFile.OpenAsync(FileAccessMode.ReadWrite)) { using (IInputStream httpStream = await response.Content.ReadAsInputStreamAsync()) { do { await httpStream.ReadAsync(buffer, m_bufferSize, InputStreamOptions.ReadAhead); if (buffer.Length > 0) { await fileStream.WriteAsync(buffer); if (m_Progress != null) { m_DownloadedBytes += buffer.Length; ((IProgress <Downloader>)m_Progress).Report(this); } } }while (buffer.Length > 0); } await fileStream.FlushAsync(); } } await tempFile.RenameAsync(Path.GetFileName(m_DestinationFileName), NameCollisionOption.ReplaceExisting); return(tempFile); }
private async void Socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args) { byte[] data = new byte[BUFFER_SIZE]; IBuffer buffer = data.AsBuffer(); IInputStream input = args.GetDataStream(); await input.ReadAsync(buffer, BUFFER_SIZE, InputStreamOptions.Partial); MessageReceived?.Invoke(this, data.Take((int)buffer.Length).ToArray()); _sw = _sw ?? Stopwatch.StartNew(); _sw.Restart(); }
/****************************************** * This procedure listens for messages arriving to socket 8090. This information will be * built to string. It will then extract the data from the received string * by calling GetQuery method. The data is properly dispatched to the service connection * established / stored by this application. * Finally OutputWebpage is called to provide feedback to the webclient. * bMsg bool is added to ensure that when multiple messages are received, the messages are discarded. * This is required. Without this, the Webservice crashes after some time. ******************************************/ private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { if (!bMsg) { bMsg = true; StringBuilder request = new StringBuilder(); try { using (IInputStream input = args.Socket.InputStream) { byte[] data = new byte[BUFFERSIZE]; IBuffer buffer = data.AsBuffer(); uint dataRead = BUFFERSIZE; while (dataRead == BUFFERSIZE) { await input.ReadAsync(buffer, BUFFERSIZE, InputStreamOptions.Partial); request.Append(Encoding.UTF8.GetString(data, 0, data.Length)); dataRead = buffer.Length; } } string inputString = GetQuery(request); //If you are running as a background webserver serviceConnection will be null //Dispatch the message to the service connection. if (serviceConnection != null) { await serviceConnection.SendMessageAsync(new ValueSet { new KeyValuePair <string, object>("Query", inputString) }); } OutputWebPage(args, inputString); } catch (Exception Ex) { Debug.WriteLine("Exception occurred: {0}", Ex); //Uncomment next two lines for logging the exception errors lc = new LoggingChannel("my provider", null, new Guid("4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a")); lc.LogMessage("Exception at Input String: " + Ex); bMsg = false; } bMsg = false; } //Uncomment the else statement if you want to use debugging /* * else * { * lc = new LoggingChannel("my provider", null, new Guid("4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a")); * lc.LogMessage("Multiple messages received"); * } */ }
/// <summary> /// Handle a HTTP request. Only GET requests are supported. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private async void HandleRequest(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { try { StringBuilder request = new StringBuilder(); // Handle an incoming request // First read the request using (IInputStream input = args.Socket.InputStream) { byte[] data = new byte[BufferSize]; IBuffer buffer = data.AsBuffer(); uint dataRead = BufferSize; while (dataRead == BufferSize) { await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial); request.Append(Encoding.UTF8.GetString(data, 0, data.Length)); dataRead = buffer.Length; } } var requestLines = request.ToString().Split('\r', '\n'); if ((requestLines.Length > 0) && requestLines[0].ToUpper().StartsWith("GET ")) { var url = requestLines[0].Substring(4).Split(' ')[0]; if (!await SendFile(args.Socket.OutputStream, url)) { // if no static file has been served, check for a REST call var e = new RestCommandArgs(url); RestCommand?.Invoke(this, e); if (e.IsValid) { var htmlResponse = string.IsNullOrEmpty(e.HtmlResponse) ? $"<html><body>Ok. ({e.Command})</body></html>" : e.HtmlResponse; SendHtmlResponse(args.Socket.OutputStream, 200, "OK", htmlResponse); } else { SendHtmlResponse(args.Socket.OutputStream, 400, "Bad Request", $"<html><body><h1>Bad Request</h1>Invalid command: {e.Command}<br/>{e.ErrorMessage}</body></html>"); } } } else { SendHtmlResponse(args.Socket.OutputStream, 400, "Bad Request", "<html><body>Bad Request</body></html>"); } } catch (Exception ex) { SendHtmlResponse(args.Socket.OutputStream, 500, "Internal Server Error", $"<html><body>Internal Server Error{ex}</body></html>"); } }
private async Task <byte[]> ConvertStreamToByteArrayAsync(IInputStream inputStream) { // Don't expect to ever be 1MB but this is the upper limit Block until we get all the data await inputStream.ReadAsync(lengthBuffer.AsBuffer(), lengthBuffer.AsBuffer().Capacity, InputStreamOptions.None); // We don't expect the image size to fill all of UInt32, ONE_MEGABYTE should be the image size's upper limit // We don't use BitConverter because we can't specify whether to convert with little or big endian. // The camera client uses big endian so here, we will use bit operations to get the data UInt32 imageLength = Convert.ToUInt32( (lengthBuffer[0] << 24 | lengthBuffer[1] << 16 | lengthBuffer[2] << 8 | lengthBuffer[3])); imageBytes = new byte[imageLength]; if (imageLength > 0 && imageLength < 1000000) // If client suddenly stops, the data it sends is corrupted. Crude way of checking for corrpution { await inputStream.ReadAsync(imageBytes.AsBuffer(), imageLength, InputStreamOptions.None); return(imageBytes); } return(null); }
public static async Task<string> ComputeMd5(IInputStream stream, BinaryStringEncoding encoding = BinaryStringEncoding.Utf8) { var hashAlgorithmProvider = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5); var hash = hashAlgorithmProvider.CreateHash(); uint size = 1024*64; var buffer = new Buffer(size); while (true) { var x = await stream.ReadAsync(buffer, size, InputStreamOptions.Partial); if (x.Length < 1) { break; } hash.Append(x); } var result = hash.GetValueAndReset(); var hex = CryptographicBuffer.EncodeToHexString(result); return hex; }
/// <summary> /// Parse the headers fields. /// </summary> /// <param name="input">The input stream.</param> /// <param name="buffer">The header bytes reader.</param> /// <returns>The file headers.</returns> private static async Task<FileHeaders> GetHeaders( IInputStream input, IBuffer buffer) { var result = new FileHeaders(); while (true) { buffer = await input.ReadAsync(buffer, 3); var field = (HeaderFields)buffer.GetByte(0); var size = BitConverter.ToUInt16(buffer.ToArray(1, 2), 0); if (size > 0) buffer = await input.ReadAsync(buffer, size); switch (field) { case HeaderFields.EndOfHeader: return result; case HeaderFields.CompressionFlags: result.UseGZip = buffer.GetByte(0) == 1; break; case HeaderFields.EncryptionIV: result.EncryptionIV = buffer .ToArray().AsBuffer(); break; case HeaderFields.MasterSeed: result.MasterSeed = buffer .ToArray().AsBuffer(); break; case HeaderFields.StreamStartBytes: result.StartBytes = buffer .ToArray().AsBuffer(); break; case HeaderFields.TransformSeed: result.TransformSeed = buffer .ToArray().AsBuffer(); break; case HeaderFields.TransformRounds: result.TransformRounds = BitConverter.ToUInt64( buffer.ToArray(), 0); break; case HeaderFields.ProtectedStreamKey: result.ProtectedStreamKey = buffer .ToArray().AsBuffer(); break; case HeaderFields.InnerRandomStreamID: result.RandomAlgorithm = (CrsAlgorithm) BitConverter.ToUInt32(buffer.ToArray(), 0); break; } } }
/// <summary> /// Gets the SHA 256 hash of the specified file. /// </summary> /// <param name="input">The keyfile stream.</param> /// <param name="buffer">The buffer.</param> /// <returns>The hash of the keyfile.</returns> private static async Task<IBuffer> GetFileHash( IInputStream input, IBuffer buffer) { var sha = HashAlgorithmProvider .OpenAlgorithm(HashAlgorithmNames.Sha256) .CreateHash(); while (true) { buffer = await input.ReadAsync( buffer, buffer.Capacity); if (buffer.Length == 0) break; sha.Append(buffer); } return sha.GetValueAndReset(); }
/// <summary> /// Reads the specified hashed block stream into a memory stream. /// </summary> /// <param name="input">The hashed block stream.</param> /// <returns>The de-hashed stream.</returns> public static async Task<Stream> Read(IInputStream input) { if (input == null) throw new ArgumentNullException("input"); var blockIndex = 0; var result = new MemoryStream(); var hash = WindowsRuntimeBuffer.Create(32); var reader = new DataReader(input) { ByteOrder = ByteOrder.LittleEndian, }; var sha = HashAlgorithmProvider .OpenAlgorithm(HashAlgorithmNames.Sha256); try { while (true) { // Detect end of file var read = await reader.LoadAsync(4); if (read == 0) break; // Verify block index var index = reader.ReadInt32(); if (index != blockIndex) { throw new InvalidDataException(string.Format( "Wrong block ID detected, expected: {0}, actual: {1}", blockIndex, index)); } blockIndex++; // Block hash hash = await input.ReadAsync(hash, 32); if (hash.Length != 32) { throw new InvalidDataException( "Data corruption detected (truncated data)"); } read = await reader.LoadAsync(4); if (read != 4) { throw new InvalidDataException( "Data corruption detected (truncated data)"); } // Validate block size (< 10MB) var blockSize = reader.ReadInt32(); if (blockSize == 0) { // Terminator block var isTerminator = hash .ToArray() .All(x => x == 0); if (!isTerminator) { throw new InvalidDataException( "Data corruption detected (invalid hash for terminator block)"); } break; } if (0 > blockSize || blockSize > 10485760) { throw new InvalidDataException( "Data corruption detected (truncated data)"); } // Check data truncate var loaded = await reader.LoadAsync((uint)blockSize); if (loaded < blockSize) { throw new InvalidDataException( "Data corruption detected (truncated data)"); } var buffer = reader.ReadBuffer((uint)blockSize); // Verify block integrity var actual = sha.HashData(buffer); if (!CryptographicBuffer.Compare(hash, actual)) { throw new InvalidDataException( "Data corruption detected (content corrupted)"); } await result.WriteAsync(buffer.ToArray(), 0, (int)buffer.Length); } result.Position = 0; return result; } catch { result.Dispose(); throw; } }
private async Task<HTTPRequest> ProcessStream(IInputStream stream) { Dictionary<string, string> _httpHeaders = null; Dictionary<string, string> _urlParameters = null; byte[] data = new byte[BufferSize]; StringBuilder requestString = new StringBuilder(); uint dataRead = BufferSize; IBuffer buffer = data.AsBuffer(); string hValue = ""; string hKey = ""; try { // binary data buffer index uint bfndx = 0; // Incoming message may be larger than the buffer size. while (dataRead == BufferSize) { await stream.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial); requestString.Append(Encoding.UTF8.GetString(data, 0, data.Length)); dataRead = buffer.Length; // read buffer index uint ndx = 0; do { switch (ParserState) { case HttpParserState.METHOD: if (data[ndx] != ' ') HTTPRequest.Method += (char)buffer.GetByte(ndx++); else { ndx++; ParserState = HttpParserState.URL; } break; case HttpParserState.URL: if (data[ndx] == '?') { ndx++; hKey = ""; HTTPRequest.Execute = true; _urlParameters = new Dictionary<string, string>(); ParserState = HttpParserState.URLPARM; } else if (data[ndx] != ' ') HTTPRequest.URL += (char)buffer.GetByte(ndx++); else { ndx++; HTTPRequest.URL = WebUtility.UrlDecode(HTTPRequest.URL); ParserState = HttpParserState.VERSION; } break; case HttpParserState.URLPARM: if (data[ndx] == '=') { ndx++; hValue = ""; ParserState = HttpParserState.URLVALUE; } else if (data[ndx] == ' ') { ndx++; HTTPRequest.URL = WebUtility.UrlDecode(HTTPRequest.URL); ParserState = HttpParserState.VERSION; } else { hKey += (char)buffer.GetByte(ndx++); } break; case HttpParserState.URLVALUE: if (data[ndx] == '&') { ndx++; hKey = WebUtility.UrlDecode(hKey); hValue = WebUtility.UrlDecode(hValue); _urlParameters[hKey] = _urlParameters.ContainsKey(hKey) ? _urlParameters[hKey] + ", " + hValue : hValue; hKey = ""; ParserState = HttpParserState.URLPARM; } else if (data[ndx] == ' ') { ndx++; hKey = WebUtility.UrlDecode(hKey); hValue = WebUtility.UrlDecode(hValue); _urlParameters[hKey] = _urlParameters.ContainsKey(hKey) ? _urlParameters[hKey] + ", " + hValue : hValue; HTTPRequest.URL = WebUtility.UrlDecode(HTTPRequest.URL); ParserState = HttpParserState.VERSION; } else { hValue += (char)buffer.GetByte(ndx++); } break; case HttpParserState.VERSION: if (data[ndx] == '\r') ndx++; else if (data[ndx] != '\n') HTTPRequest.Version += (char)buffer.GetByte(ndx++); else { ndx++; hKey = ""; _httpHeaders = new Dictionary<string, string>(); ParserState = HttpParserState.HEADERKEY; } break; case HttpParserState.HEADERKEY: if (data[ndx] == '\r') ndx++; else if (data[ndx] == '\n') { ndx++; if (_httpHeaders.ContainsKey("Content-Length")) { HTTPRequest.BodySize = Convert.ToInt32(_httpHeaders["Content-Length"]); ParserState = HttpParserState.BODY; } else ParserState = HttpParserState.OK; } else if (data[ndx] == ':') ndx++; else if (data[ndx] != ' ') hKey += (char)buffer.GetByte(ndx++); else { ndx++; hValue = ""; ParserState = HttpParserState.HEADERVALUE; } break; case HttpParserState.HEADERVALUE: if (data[ndx] == '\r') ndx++; else if (data[ndx] != '\n') hValue += (char)buffer.GetByte(ndx++); else { ndx++; _httpHeaders.Add(hKey, hValue); hKey = ""; ParserState = HttpParserState.HEADERKEY; } break; case HttpParserState.BODY: // Append to request BodyData this.HTTPRequest.BodyContent = Encoding.UTF8.GetString(data, 0, this.HTTPRequest.BodySize); bfndx += dataRead - ndx; ndx = dataRead; if (this.HTTPRequest.BodySize <= bfndx) { ParserState = HttpParserState.OK; } break; //default: // ndx++; // break; } } while (ndx < dataRead); }; // Print out the received message to the console. Debug.WriteLine("You received the following message : \n" + requestString); if (_httpHeaders != null) HTTPRequest.Headers = _httpHeaders.AsEnumerable(); if (_urlParameters != null) HTTPRequest.URLParametes = _urlParameters.AsEnumerable(); return HTTPRequest; } catch (Exception e) { Debug.WriteLine(e.ToString()); } return null; }