protected override async Task Process(HttpListenerContext context) { var writer = new StreamWriter(context.Response.OutputStream); context.AddAccessControlHeaders(); string getRequest = context.Request.Url.AbsolutePath.Remove(0,1); //Remove first slash string getUri = context.Request.Url.AbsoluteUri; int index = getUri.IndexOf("?", StringComparison.Ordinal); IDictionary<string, string> dictParams = new Dictionary<string, string>(); if (getUri.Contains("?post")) { try { using (var reader = new StreamReader(context.Request.InputStream)){ IDictionary<string, string> _dictParams = JsonConvert.DeserializeObject<IDictionary<string, string>>(reader.ReadToEnd()); dictParams = _dictParams ?? dictParams; } } catch (JsonException) { writer.WriteLine(JsonConvert.SerializeObject(JSResponse.GetErrorResponse("missing methodname or namespace"))); writer.Flush(); context.Response.OutputStream.Close(); } } else { if (index > 0) { string rawParams = getUri.Substring(index).Remove(0, 1); var nvcParams = HttpUtility.ParseQueryString(rawParams); dictParams = nvcParams.AllKeys.ToDictionary(o => o, o => nvcParams[o]); } } if(!(getRequest.Split('/').Count() >= 2)) { writer.WriteLine(JsonConvert.SerializeObject(JSResponse.GetErrorResponse("missing methodname or namespace"))); writer.Flush(); context.Response.OutputStream.Close(); } var request = new JSRequest(getRequest.Split('/')[0], getRequest.Split('/')[1], dictParams); if (request.MethodParameters.ContainsKey("jsoncallback")) { context.Response.AppendHeader("Content-Type", "application/javascript"); } else { context.Response.AppendHeader("Content-Type", "application/json"); } writer.WriteLine(await this.ProcessRequest(request)); writer.Flush(); context.Response.OutputStream.Close(); }
internal CancellationToken GetDisconnectToken(HttpListenerContext context) { if (_connectionIdField == null || _requestQueueHandle == null) { Debug.WriteLine("Server: Unable to resolve requestQueue handle. Disconnect notifications will be ignored"); return CancellationToken.None; } var connectionId = (ulong)_connectionIdField.GetValue(context.Request); return _connectionCancellationTokens.GetOrAdd(connectionId, key => new Lazy<CancellationToken>(() => CreateToken(key))).Value; }
internal OwinHttpListenerContext(HttpListenerContext httpListenerContext, string basePath, string path, string query) { _httpListenerContext = httpListenerContext; _environment = new CallEnvironment(this); _owinRequest = new OwinHttpListenerRequest(_httpListenerContext.Request, basePath, path, query, _environment); _owinResponse = new OwinHttpListenerResponse(_httpListenerContext, _environment); _environment.OwinVersion = Constants.OwinVersion; _environment.ServerUser = _httpListenerContext.User; }
protected override async Task Process(HttpListenerContext context) { context.AddAccessControlHeaders(); string getRequest = context.Request.Url.AbsolutePath.Remove(0, 1); //Remove first slash Stream input = null; try { var mediastoreKey = HttpUtility.UrlDecode(getRequest.Split('/')[0]); var mediastoreSection = getRequest.Split('/')[1]; var mediastoreItem = getRequest.Split('/')[2]; var mediaStore = new FileMediaStore(mediastoreKey); switch(mediastoreSection){ case "images": input = new FileStream(Path.Combine(this.MediaStoreRoot, mediastoreKey, mediastoreSection, mediaStore.Images[mediastoreItem]), FileMode.Open); context.Response.AddHeader("Content-Type", MimeTypes.GetMimeType(mediaStore.Images[mediastoreItem])); break; case "audio": input = new FileStream(Path.Combine(this.MediaStoreRoot, mediastoreKey, mediastoreSection, mediaStore.Audio[mediastoreItem]), FileMode.Open); context.Response.AddHeader("Content-Type", MimeTypes.GetMimeType(mediaStore.Audio[mediastoreItem])); break; case "video": input = new FileStream(Path.Combine(this.MediaStoreRoot, mediastoreKey, mediastoreSection, mediaStore.Video[mediastoreItem]), FileMode.Open); context.Response.AddHeader("Content-Type", MimeTypes.GetMimeType(mediaStore.Video[mediastoreItem])); break; case "resoruces": input = new FileStream(Path.Combine(this.MediaStoreRoot, mediastoreKey, mediastoreSection, mediaStore.Resources[mediastoreItem]), FileMode.Open); context.Response.AddHeader("Content-Type", MimeTypes.GetMimeType(mediaStore.Resources[mediastoreItem])); break; } } catch { input = new MemoryStream(new UTF8Encoding().GetBytes("404 not found")); } byte[] buffer = new byte[1024 * 16]; int nbytes; //await Task.Run(() => // { while ((nbytes = input.Read(buffer, 0, buffer.Length)) > 0) context.Response.OutputStream.Write(buffer, 0, nbytes); // }); input.Close(); context.Response.OutputStream.Close(); }
/// <summary> /// Initializes a new instance of the <see cref="OwinHttpListenerResponse"/> class. /// Sets up the Environment with the necessary request state items. /// </summary> internal OwinHttpListenerResponse(HttpListenerContext context, CallEnvironment environment) { Contract.Requires(context != null); Contract.Requires(environment != null); _context = context; _response = _context.Response; _environment = environment; _requestState = RequestInProgress; var outputStream = new HttpListenerStreamWrapper(_response.OutputStream); outputStream.OnFirstWrite = ResponseBodyStarted; _environment.ResponseBody = outputStream; _environment.ResponseHeaders = new ResponseHeadersDictionary(_response); _onSendingHeadersActions = new List<Tuple<Action<object>, object>>(); _environment.OnSendingHeaders = RegisterForOnSendingHeaders; }
private bool PropertiesTryRemove(string key) { switch (key.Length) { case 12: if (((_flag0 & 0x1u) != 0) && string.Equals(key, "owin.Version", StringComparison.Ordinal)) { _flag0 &= ~0x1u; _OwinVersion = default(string); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } if (((_flag0 & 0x8000u) != 0) && string.Equals(key, "host.AppName", StringComparison.Ordinal)) { _flag0 &= ~0x8000u; _HostAppName = default(string); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } if (((_flag0 & 0x10000u) != 0) && string.Equals(key, "host.AppMode", StringComparison.Ordinal)) { _flag0 &= ~0x10000u; _HostAppMode = default(string); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } break; case 18: if (((_flag0 & 0x2u) != 0) && string.Equals(key, "owin.CallCancelled", StringComparison.Ordinal)) { _initFlag0 &= ~0x2u; _flag0 &= ~0x2u; _CallCancelled = default(CancellationToken); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } if (((_flag0 & 0x8u) != 0) && string.Equals(key, "owin.RequestMethod", StringComparison.Ordinal)) { _flag0 &= ~0x8u; _RequestMethod = default(string); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } if (((_flag0 & 0x10u) != 0) && string.Equals(key, "owin.RequestScheme", StringComparison.Ordinal)) { _flag0 &= ~0x10u; _RequestScheme = default(string); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } break; case 20: if (((_flag0 & 0x4u) != 0) && string.Equals(key, "owin.RequestProtocol", StringComparison.Ordinal)) { _flag0 &= ~0x4u; _RequestProtocol = default(string); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } if (((_flag0 & 0x20u) != 0) && string.Equals(key, "owin.RequestPathBase", StringComparison.Ordinal)) { _flag0 &= ~0x20u; _RequestPathBase = default(string); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } if (((_flag0 & 0x1000u) != 0) && string.Equals(key, "owin.ResponseHeaders", StringComparison.Ordinal)) { _flag0 &= ~0x1000u; _ResponseHeaders = default(IDictionary<string, string[]>); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } break; case 16: if (((_flag0 & 0x40u) != 0) && string.Equals(key, "owin.RequestPath", StringComparison.Ordinal)) { _flag0 &= ~0x40u; _RequestPath = default(string); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } if (((_flag0 & 0x200u) != 0) && string.Equals(key, "owin.RequestBody", StringComparison.Ordinal)) { _initFlag0 &= ~0x200u; _flag0 &= ~0x200u; _RequestBody = default(Stream); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } if (((_flag0 & 0x4000u) != 0) && string.Equals(key, "host.TraceOutput", StringComparison.Ordinal)) { _flag0 &= ~0x4000u; _HostTraceOutput = default(TextWriter); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } if (((_flag0 & 0x1000000u) != 0) && string.Equals(key, "server.LocalPort", StringComparison.Ordinal)) { _initFlag0 &= ~0x1000000u; _flag0 &= ~0x1000000u; _ServerLocalPort = default(string); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } if (((_flag0 & 0x20000000u) != 0) && string.Equals(key, "websocket.Accept", StringComparison.Ordinal)) { _initFlag0 &= ~0x20000000u; _flag0 &= ~0x20000000u; _WebSocketAccept = default(WebSocketAccept); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } break; case 23: if (((_flag0 & 0x80u) != 0) && string.Equals(key, "owin.RequestQueryString", StringComparison.Ordinal)) { _flag0 &= ~0x80u; _RequestQueryString = default(string); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } if (((_flag0 & 0x400u) != 0) && string.Equals(key, "owin.ResponseStatusCode", StringComparison.Ordinal)) { _flag0 &= ~0x400u; _ResponseStatusCode = default(int); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } if (((_flag0 & 0x80000u) != 0) && string.Equals(key, "server.OnSendingHeaders", StringComparison.Ordinal)) { _flag0 &= ~0x80000u; _OnSendingHeaders = default(Action<Action<object>, object>); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } if (((_flag0 & 0x10000000u) != 0) && string.Equals(key, "ssl.LoadClientCertAsync", StringComparison.Ordinal)) { _flag0 &= ~0x10000000u; _LoadClientCert = default(Func<Task>); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } break; case 19: if (((_flag0 & 0x100u) != 0) && string.Equals(key, "owin.RequestHeaders", StringComparison.Ordinal)) { _flag0 &= ~0x100u; _RequestHeaders = default(IDictionary<string, string[]>); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } if (((_flag0 & 0x20000u) != 0) && string.Equals(key, "host.OnAppDisposing", StringComparison.Ordinal)) { _flag0 &= ~0x20000u; _OnAppDisposing = default(CancellationToken); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } if (((_flag0 & 0x100000u) != 0) && string.Equals(key, "server.Capabilities", StringComparison.Ordinal)) { _flag0 &= ~0x100000u; _ServerCapabilities = default(IDictionary<string, object>); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } break; case 25: if (((_flag0 & 0x800u) != 0) && string.Equals(key, "owin.ResponseReasonPhrase", StringComparison.Ordinal)) { _flag0 &= ~0x800u; _ResponseReasonPhrase = default(string); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } break; case 17: if (((_flag0 & 0x2000u) != 0) && string.Equals(key, "owin.ResponseBody", StringComparison.Ordinal)) { _flag0 &= ~0x2000u; _ResponseBody = default(Stream); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } if (((_flag0 & 0x400000u) != 0) && string.Equals(key, "server.RemotePort", StringComparison.Ordinal)) { _initFlag0 &= ~0x400000u; _flag0 &= ~0x400000u; _ServerRemotePort = default(string); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } break; case 11: if (((_flag0 & 0x40000u) != 0) && string.Equals(key, "server.User", StringComparison.Ordinal)) { _flag0 &= ~0x40000u; _ServerUser = default(IPrincipal); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } break; case 22: if (((_flag0 & 0x200000u) != 0) && string.Equals(key, "server.RemoteIpAddress", StringComparison.Ordinal)) { _initFlag0 &= ~0x200000u; _flag0 &= ~0x200000u; _ServerRemoteIpAddress = default(string); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } break; case 21: if (((_flag0 & 0x800000u) != 0) && string.Equals(key, "server.LocalIpAddress", StringComparison.Ordinal)) { _initFlag0 &= ~0x800000u; _flag0 &= ~0x800000u; _ServerLocalIpAddress = default(string); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } if (((_flag0 & 0x4000000u) != 0) && string.Equals(key, "ssl.ClientCertificate", StringComparison.Ordinal)) { _initFlag0 &= ~0x4000000u; _flag0 &= ~0x4000000u; _ClientCert = default(X509Certificate); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } if (((_flag0 & 0x80000000u) != 0) && string.Equals(key, "Mono.Net.HttpListener", StringComparison.Ordinal)) { _flag0 &= ~0x80000000u; _Listener = default(Mono.Net.HttpListener); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } break; case 14: if (((_flag0 & 0x2000000u) != 0) && string.Equals(key, "server.IsLocal", StringComparison.Ordinal)) { _initFlag0 &= ~0x2000000u; _flag0 &= ~0x2000000u; _ServerIsLocal = default(bool); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } break; case 27: if (((_flag0 & 0x8000000u) != 0) && string.Equals(key, "ssl.ClientCertificateErrors", StringComparison.Ordinal)) { _initFlag0 &= ~0x8000000u; _flag0 &= ~0x8000000u; _ClientCertErrors = default(Exception); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } break; case 28: if (((_flag0 & 0x40000000u) != 0) && string.Equals(key, "Mono.Net.HttpListenerContext", StringComparison.Ordinal)) { _flag0 &= ~0x40000000u; _RequestContext = default(HttpListenerContext); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } break; case 49: if (((_flag1 & 0x1u) != 0) && string.Equals(key, "Microsoft.Owin.Host.HttpListener.OwinHttpListener", StringComparison.Ordinal)) { _flag1 &= ~0x1u; _OwinHttpListener = default(OwinHttpListener); // This can return true incorrectly for values that delayed initialization may determine are not actually present. return true; } break; } return false; }
private void StartProcessingRequest(HttpListenerContext context) { Interlocked.Decrement(ref _currentOutstandingAccepts); Interlocked.Increment(ref _currentOutstandingRequests); OffloadStartNextRequest(); OwinHttpListenerContext owinContext = null; try { string pathBase, path, query; GetPathAndQuery(context.Request.RawUrl, out pathBase, out path, out query); owinContext = new OwinHttpListenerContext(context, pathBase, path, query, _disconnectHandler); PopulateServerKeys(owinContext.Environment); Contract.Assert(!owinContext.Environment.IsExtraDictionaryCreated, "All keys set by the server should have reserved slots."); _appFunc(owinContext.Environment) .Then((Func<Task>)owinContext.Response.CompleteResponseAsync, runSynchronously: true) .Then(() => { owinContext.Response.Close(); EndRequest(owinContext, null); }, runSynchronously: true) .Catch(errorInfo => { EndRequest(owinContext, errorInfo.Exception); return errorInfo.Handled(); }); } catch (Exception ex) { // TODO: Katana#5 - Don't catch everything, only catch what we think we can handle? Otherwise crash the process. EndRequest(owinContext, ex); } }
protected override async Task Process(HttpListenerContext context) { context.AddAccessControlHeaders(); string getRequest = context.Request.Url.AbsolutePath.Remove(0, 1); //Remove first slash Stream input = null; try { string gameUUID = HttpUtility.UrlDecode(getRequest.Split('/')[0]); string fileName = HttpUtility.UrlDecode(getRequest.Split('/')[1]); if (fileName.StartsWith("GameMusic")) { IGameMediaCache mediaCache = new GameMediaCache(gameUUID); string _fileName = mediaCache.GameMusicFileName; context.Response.AddHeader("Content-Type", MimeTypes.GetMimeType(_fileName)); string filePath = Path.Combine(mediaCache.RootPath, mediaCache.CacheKey, _fileName); input = new FileStream(filePath, FileMode.Open); } if (fileName.StartsWith("GameVideo")) { IGameMediaCache mediaCache = new GameMediaCache(gameUUID); string _fileName = mediaCache.GameVideoFileName; context.Response.AddHeader("Content-Type", MimeTypes.GetMimeType(_fileName)); string filePath = Path.Combine(mediaCache.RootPath, mediaCache.CacheKey, _fileName); input = new FileStream(filePath, FileMode.Open); } if (fileName.StartsWith("screenshot")) { context.Response.AddHeader("Content-Type", "image/png"); int index; int.TryParse(fileName.Split('~')[1], out index); IGameScreenshotCache screenCache = new GameScreenshotCache(gameUUID); string _fileName = screenCache.ScreenshotCollection[index]; string filePath = Path.Combine(screenCache.RootPath, screenCache.CacheKey, _fileName); if (context.Request.QueryString["scale"] != null) { string _scalePercentage = context.Request.QueryString["scale"]; int scalePercentage; if (int.TryParse(_scalePercentage, out scalePercentage)) { if (scalePercentage <= 100 && scalePercentage > 0) { double trueScalePercentage = scalePercentage / 100D; using (Image initialImage = Image.FromFile(Path.Combine(filePath))) { using (Image resizedImage = GameMediaCache.ResizeImage(initialImage, trueScalePercentage)) { using (MemoryStream _input = new MemoryStream()) { resizedImage.Save(_input, ImageFormat.Png); input = new MemoryStream(_input.ToArray()); } } } } } } else { input = new FileStream(filePath, FileMode.Open); } } if (fileName.StartsWith("BoxartBack") || fileName.StartsWith("BoxartFront") || fileName.StartsWith("BoxartFull") || fileName.StartsWith("GameFanart")) { StringBuilder imageFileName = new StringBuilder(); if (fileName.StartsWith("BoxartBack")) { imageFileName.Append("BoxartBack.png"); } else if (fileName.StartsWith("BoxartFront")) { imageFileName.Append("BoxartFront.png"); } else if (fileName.StartsWith("BoxartFull")) { imageFileName.Append("BoxartFull.png"); } else if (fileName.StartsWith("GameFanart")) { imageFileName.Append("GameFanart.png"); } if (fileName.Contains("@10")) { imageFileName.Insert(0, "@10_"); } else if (fileName.Contains("@25")) { imageFileName.Insert(0, "@25_"); } else if (fileName.Contains("@50")) { imageFileName.Insert(0, "@50_"); } else if (fileName.Contains("@75_")) { imageFileName.Insert(0, "@75_"); } context.Response.AddHeader("Content-Type", "image/png"); IGameMediaCache mediaCache = new GameMediaCache(gameUUID); if (context.Request.QueryString["scale"] != null) { string _scalePercentage = context.Request.QueryString["scale"]; int scalePercentage; if (int.TryParse(_scalePercentage, out scalePercentage)) { if (scalePercentage <= 100 && scalePercentage > 0){ double trueScalePercentage = scalePercentage / 100D ; using (Image initialImage = Image.FromFile(Path.Combine(mediaCache.RootPath, mediaCache.CacheKey, imageFileName.ToString()))) { using (Image resizedImage = GameMediaCache.ResizeImage(initialImage, trueScalePercentage)) { using (MemoryStream _input = new MemoryStream()) { resizedImage.Save(_input, ImageFormat.Png); input = new MemoryStream(_input.ToArray()); } } } } } } else { input = new FileStream(Path.Combine(mediaCache.RootPath, mediaCache.CacheKey, imageFileName.ToString()), FileMode.Open); } } } catch (FileNotFoundException) { context.Response.AddHeader("Content-Type", "text/plain"); context.Response.StatusCode = 404; context.Response.StatusDescription = "404 Not Found"; input = new MemoryStream(new UTF8Encoding().GetBytes("404 Not Found")); } catch (IndexOutOfRangeException) { context.Response.AddHeader("Content-Type", "text/plain"); context.Response.StatusCode = 404; context.Response.StatusDescription = "404 Not Found"; input = new MemoryStream(new UTF8Encoding().GetBytes("404 Not Found")); } catch { context.Response.AddHeader("Content-Type", "text/plain"); context.Response.StatusCode = 404; context.Response.StatusDescription = "404 Not Found"; input = new MemoryStream(new UTF8Encoding().GetBytes("404 Not Found")); } byte[] buffer = new byte[1024 * 16]; int nbytes; await Task.Run(() => { if (input == null) //not a null check but a conditional { context.Response.AddHeader("Content-Type", "text/plain"); context.Response.StatusCode = 404; context.Response.StatusDescription = "404 Not Found"; input = new MemoryStream(new UTF8Encoding().GetBytes("404 Not Found")); } while ((nbytes = input.Read(buffer, 0, buffer.Length)) > 0) context.Response.OutputStream.Write(buffer, 0, nbytes); }); input.Close(); context.Response.OutputStream.Close(); }
private async void StartProcessingRequest(HttpListenerContext context) { Interlocked.Decrement(ref _currentOutstandingAccepts); Interlocked.Increment(ref _currentOutstandingRequests); OffloadStartNextRequest(); OwinHttpListenerContext owinContext = null; try { string pathBase, path, query; GetPathAndQuery(context.Request.RawUrl, out pathBase, out path, out query); owinContext = new OwinHttpListenerContext(context, pathBase, path, query); PopulateServerKeys(owinContext.Environment); Contract.Assert(!owinContext.Environment.IsExtraDictionaryCreated, "All keys set by the server should have reserved slots."); await _appFunc(owinContext.Environment); await owinContext.Response.CompleteResponseAsync(); owinContext.Response.Close(); EndRequest(owinContext, null); } catch (Exception ex) { // TODO: Katana#5 - Don't catch everything, only catch what we think we can handle? Otherwise crash the process. EndRequest(owinContext, ex); } }
private void sendResponse(HttpListenerContext ctx, string message) { byte[] message_bytes = System.Text.Encoding.UTF8.GetBytes(message); try { ctx.Response.OutputStream.Write(message_bytes,0,message_bytes.Length); } catch { } }
private void sendError(HttpListenerContext ctx, string message) { message = "{\"result\":null,\"error\":\"" + message + "\"}"; byte[] message_bytes = System.Text.Encoding.UTF8.GetBytes(message); try { ctx.Response.OutputStream.Write(message_bytes,0,message_bytes.Length); } catch { } }
public bool tunnelAPI(HttpListenerContext ctx, Nodes.Node publicNode) { string querystring = ctx.Request.RawUrl; string address = publicNode.address; string postData = null; //if POST get data from local browser API call if (ctx.Request.HttpMethod == "POST") { System.IO.StreamReader reader = new System.IO.StreamReader(ctx.Request.InputStream, System.Text.Encoding.UTF8); postData = reader.ReadToEnd(); postData = Uri.UnescapeDataString(postData); reader.Close(); } System.Net.WebResponse webresp = null; try { System.Net.HttpWebRequest wr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create("http://" + address + ":7876" + querystring); wr.Timeout = 20000; //cater for POST calls if (ctx.Request.HttpMethod == "POST") { wr.Method = "POST"; wr.ContentType = "application/x-www-form-urlencoded"; byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postData); wr.ContentLength = postBytes.Length; using (Stream s = wr.GetRequestStream()) { s.Write(postBytes,0,postBytes.Length); } } var sw = new System.Diagnostics.Stopwatch(); sw.Start(); webresp = wr.GetResponse(); sw.Stop(); publicNode.latency = sw.ElapsedMilliseconds; } catch (Exception ex) { publicNode.reachable = false; publicNode.last_error = "Could not connect"; publicNode.connection_failures++; publicNode.consecutive_errors++; return false; } Stream NodeResponseStream = webresp.GetResponseStream(); using (StreamReader sr = new StreamReader(NodeResponseStream)) { string response_data = sr.ReadToEnd(); JObject jo = JObject.Parse(response_data); //check for unknown block response, probably means non sync'd node if (querystring.Length >= 26 && querystring.Substring(0,26) == "/nxt?requestType=getBlock&" && response_data == "{\"errorCode\":5,\"errorDescription\":\"Unknown block\"}") { publicNode.block_sync_failures ++; publicNode.consecutive_errors ++; publicNode.last_error = "Unknown block"; return false; } //check for Not Allowed response (peer has private Api) JToken jt = jo.SelectToken("errorCode"); if (jt != null && jt.ToString() == "7") { publicNode.consecutive_errors ++; publicNode.last_error = "API Not Allowed"; return false; } publicNode.last_reachable = publicNode.last_checked; bool hasBlockHeight = false; if (querystring.Length >= 37 && querystring.Substring(0,37) == "/nxt?requestType=getBlockchainStatus&") { try { JObject joGetBlockResponse = JObject.Parse(response_data); publicNode.last_block = joGetBlockResponse.SelectToken("lastBlock").ToString(); publicNode.block_height = int.Parse(joGetBlockResponse.SelectToken("numberOfBlocks").ToString())-1; publicNode.time = int.Parse(joGetBlockResponse.SelectToken("time").ToString()); publicNode.version = joGetBlockResponse.SelectToken("version").ToString(); hasBlockHeight = true; } catch {} } if (querystring.Length >= 26 && querystring.Substring(0,26) == "/nxt?requestType=getState&") { try { JObject joGetBlockResponse = JObject.Parse(response_data); publicNode.last_block = joGetBlockResponse.SelectToken("lastBlock").ToString(); publicNode.block_height = int.Parse(joGetBlockResponse.SelectToken("numberOfBlocks").ToString())-1; publicNode.time = int.Parse(joGetBlockResponse.SelectToken("time").ToString()); publicNode.version = joGetBlockResponse.SelectToken("version").ToString(); hasBlockHeight = true; } catch {} } if (hasBlockHeight) { if (publicNode.block_height < (Nodes.peer_block_height_history.AgreedBlockHeight - 2)) { publicNode.block_sync_failures ++; publicNode.consecutive_errors ++; publicNode.last_error = "Not fully sync'd"; return false; } } publicNode.consecutive_errors = 0; if (hasBlockHeight) Nodes.peer_block_height_history.Add(publicNode.address, publicNode.block_height); byte[] response_bytes = System.Text.Encoding.UTF8.GetBytes(response_data); try { ctx.Response.OutputStream.Write(response_bytes,0,response_bytes.Length); } catch {} } //try cleanup try { webresp.Close(); ctx.Response.Close(); } catch {} return true; }
public void tryTunnel(HttpListenerContext ctx) { bool hadSuccess = false; bool getBestPeer = false; while (!hadSuccess) { Nodes.Node tmpNode = Nodes.getNxtPeerToUse(getBestPeer); if (tmpNode == null) { sendError(ctx, "No peers to use"); return; } tmpNode.connection_attempts++; hadSuccess = tunnelAPI(ctx, tmpNode); getBestPeer = true; } }
public bool sendUI(string url, HttpListenerContext ctx) { if (url.IndexOf("?") >= 0) url = url.Substring(0, url.IndexOf("?") - 1); Console.WriteLine("Sending: " + url); if (url == "/") { sendResource(ctx, "/index.html"); } else { sendResource(ctx, url); } return true; }
public void sendResource(HttpListenerContext ctx, string filename) { DirectoryInfo dir = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory); byte[] fileData = null; if (dir.Parent.Parent.GetDirectories("assets").Length > 0) dir = dir.Parent.Parent.GetDirectories("assets")[0]; else if (dir.GetDirectories("assets").Length > 0) dir = dir.GetDirectories("assets")[0]; string test = Path.Combine(dir.FullName, filename.Substring(1)); if (File.Exists(test)) fileData = File.ReadAllBytes(test); else { sendError(ctx, "File not found"); return; } if (filename.Substring(filename.Length - 4) == "html") ctx.Response.Headers.Add("Content-Type","text/html"); if (filename.Substring(filename.Length - 3) == "css") ctx.Response.Headers.Add("Content-Type","text/css"); if (filename.Substring(filename.Length - 2) == "js") ctx.Response.Headers.Add("Content-Type","application/javascript"); if (filename.Substring(filename.Length - 3) == "png") ctx.Response.Headers.Add("Content-Type","image/png"); //if its the NRS.js, inject our own JS hooks if (filename == "/js/nrs.js") { string tmpFileData = System.Text.Encoding.UTF8.GetString(fileData); tmpFileData = tmpFileData.Replace("NRS.init();","$.getScript('nxtlite.js');"); fileData = System.Text.Encoding.UTF8.GetBytes(tmpFileData); } try { ctx.Response.ContentLength64 = fileData.Length; ctx.Response.OutputStream.Write(fileData, 0, fileData.Length); } catch { //TODO: do something here } }
internal void Complete(HttpListenerContext context) { Complete(context, false); }