private void GetPostData() { var ms = new MemoryStream(); if (HttpHeaders.ContainsKey("Content-Length")) { var contentLen = Convert.ToInt32(HttpHeaders["Content-Length"]); if (contentLen > MaxPostSize) { throw new Exception($"POST Content-Length({contentLen}) too big!"); } var buf = new byte[BufSize]; var toRead = contentLen; while (toRead > 0) { var numread = _inputStream.Read(buf, 0, Math.Min(BufSize, toRead)); if (numread == 0) { if (toRead == 0) { break; } throw new Exception("Client disconnected while reading POST data."); } toRead -= numread; ms.Write(buf, 0, numread); } ms.Seek(0, SeekOrigin.Begin); } var reader = new StreamReader(ms); HttpPostData = reader.ReadToEnd(); reader.Close(); }
public void HandleGetRequest(string content_type = "text/html") { if (http_url.Equals("/") || http_url.Equals("")) { http_url = "/Index.html"; } if (!Resources.TryGet(http_url, out binSend)) { MemoryStream ms = new MemoryStream(); if (GetJavaScriptProject(ms)) { content_type = GetHttpExtensionType(); writeSuccess(content_type); } else { if (File.Exists("../../Web" + http_url)) { content_type = GetHttpExtensionType(); Stream fs = File.Open("../../Web" + http_url, FileMode.Open); fs.CopyTo(ms); fs.Close(); writeSuccess(content_type); } else { writeFailure(); } } if (HttpHeaders.ContainsKey("Connection")) { writeClose(HttpHeaders["Connection"].ToString()); } else { writeClose(); } if (content_type.Contains("text") || content_type.Contains("json")) { ResponseBuilder.Append((ms.ToArray().ToChars(CharEncoding.UTF8))); binSend = ResponseBuilder.ToString().ToBytes(CharEncoding.UTF8); Resources.Add(http_url, binSend); } else { binSend = ResponseBuilder.ToString().ToBytes(CharEncoding.UTF8).Concat(ms.ToArray()).ToArray(); Resources.Add(http_url, binSend); } ms.Dispose(); } }
public bool VerifyRequest() { bool verified = false; string ip = tr.MyHeader.Context.RemoteEndPoint.Address.ToString(); if (HttpHeaders.ContainsKey("DealerToken")) { if (HttpHeaders["DealerToken"].ToString() != "") { string token = HttpHeaders["DealerToken"].ToString(); MemberIdentity di = null; if (DealServer.Security.Register(token, out di, ip)) { verified = true; HttpOptions["DealerToken"] = di.Token; HttpOptions["DealerUserId"] = di.UserId; HttpOptions["DealerDeptId"] = di.DeptId; } } } if (!verified) { if (HttpHeaders.ContainsKey("Authorization")) { if (HttpHeaders["Authorization"].ToString() != "") { string[] codes = HttpHeaders["Authorization"].ToString().Split(' '); string decode64 = ""; string name = ""; string key = ""; if (codes.Length > 1) { decode64 = Encoding.UTF8.GetString(Convert.FromBase64String(codes[1])); string[] namekey = decode64.Split(':'); name = namekey[0]; key = namekey[1]; MemberIdentity di = null; if (DealServer.Security.Register(name, key, out di, ip)) { verified = true; HttpOptions["DealerToken"] = di.Token; HttpOptions["DealerUserId"] = di.UserId; HttpOptions["DealerDeptId"] = di.DeptId; } } } } } return(verified); }
/// <summary> /// Handles this request as a POST /// </summary> /// <param name="stream"></param> public void HandlePOSTRequest(Stream stream) { using (var ms = new MemoryStream()) { if (HttpHeaders.ContainsKey(Headers.CONTENT_LENGTH)) { var contentLength = Convert.ToInt32(HttpHeaders[Headers.CONTENT_LENGTH]); if (contentLength > MaxPostSize) { throw new Exception( $"POST Content-Length({contentLength}) too big for this simple server (max: {MaxPostSize})" ); } var buf = new byte[BUF_SIZE]; var toRead = contentLength; while (toRead > 0) { var numread = stream.Read(buf, 0, Math.Min(BUF_SIZE, toRead)); if (numread == 0) { if (toRead == 0) { break; } else { throw new Exception("client disconnected during post"); } } toRead -= numread; ms.Write(buf, 0, numread); } ms.Seek(0, SeekOrigin.Begin); } ParseFormElementsIfRequired(ms); Server.HandlePOSTRequest(this, ms); } }
/// <summary> /// Parses form data on the request, if available /// </summary> /// <param name="ms"></param> public void ParseFormElementsIfRequired(MemoryStream ms) { if (!HttpHeaders.ContainsKey(Headers.CONTENT_TYPE)) { return; } if (HttpHeaders[Headers.CONTENT_TYPE] != "application/x-www-form-urlencoded") { return; } try { var formData = Encoding.UTF8.GetString(ms.ToArray()); FormData = EncodedStringToDictionary(formData); } catch { /* intentionally left blank */ } }
public void HandlePostRequest() { HttpRequestEvent("Started: Get POST data"); int contentLength = 0; var memStream = new MemoryStream(); if (HttpHeaders.ContainsKey("Content-Length")) { contentLength = Convert.ToInt32(this.HttpHeaders["Content-Length"]); if (contentLength > MAX_POST_SIZE) { throw new Exception(String.Format("POST Content-Length({0}) to large for this server", contentLength)); } byte[] buf = new byte[BUF_SIZE]; int toRead = contentLength; while (toRead > 0) { HttpRequestEvent("starting Read, toRead=" + toRead); int numRead = this.m_InputStream.Read(buf, 0, Math.Min(BUF_SIZE, toRead)); HttpRequestEvent("read finished, numread=" + numRead); if (numRead == 0) { if (toRead == 0) { break; } else { throw new Exception("client disconnected during post"); } } toRead -= numRead; memStream.Write(buf, 0, numRead); } memStream.Seek(0, SeekOrigin.Begin); } HttpRequestEvent("Finished: Get POST data"); Srv.HandlePostRequest(this, new StreamReader(memStream)); }
public void Initialize() { if (HttpHeaders.ContainsKey("X-RateLimit-Remaining")) { HttpHeaders["X-RateLimit-Remaining"] = "-1"; } else { HttpHeaders.Add("X-RateLimit-Remaining", "-1"); } if (HttpHeaders.ContainsKey("X-RateLimit-Limit")) { HttpHeaders["X-RateLimit-Limit"] = "-1"; } else { HttpHeaders.Add("X-RateLimit-Limit", "-1"); } if (HttpHeaders.ContainsKey("X-RateLimit-Reset")) { HttpHeaders["X-RateLimit-Reset"] = "-1"; } else { HttpHeaders.Add("X-RateLimit-Reset", "-1"); } if (HttpHeaders.ContainsKey("X-Access-Level")) { HttpHeaders["X-Access-Level"] = "read-write-directmessages"; } else { HttpHeaders.Add("X-Access-Level", "read-write-directmessages"); } if (HttpHeaders.ContainsKey("X-MediaRateLimit-Remaining")) { HttpHeaders["X-MediaRateLimit-Remaining"] = "-1"; } else { HttpHeaders.Add("X-MediaRateLimit-Remaining", "-1"); } if (HttpHeaders.ContainsKey("X-MediaRateLimit-Limit")) { HttpHeaders["X-MediaRateLimit-Limit"] = "-1"; } else { HttpHeaders.Add("X-MediaRateLimit-Limit", "-1"); } if (HttpHeaders.ContainsKey("X-MediaRateLimit-Reset")) { HttpHeaders["X-MediaRateLimit-Reset"] = "-1"; } else { HttpHeaders.Add("X-MediaRateLimit-Reset", "-1"); } maxCount = -1; remainCount = -1; resetTime = new DateTime(); resetTimeInSeconds = -1; mediaMaxCount = -1; mediaRemainCount = -1; mediaResetTime = new DateTime(); AccessLevel = ApiAccessLevel.None; // _UsingCount = -1 if (Changed != null) { Changed(this, new ApiInformationChangedEventArgs()); } }
public void WriteResponse(string status, string response = null, string contentType = null) { if (ResponseWritten) { throw new Exception("Cannot send new response after response has been sent."); } ResponseWritten = true; Logger.Log("<Thread " + Thread.CurrentThread.ManagedThreadId + "> Response: " + status, status.StartsWith("2") ? LogLevel.Success : LogLevel.Warn); byte[] encodedBytes = null; var length = string.IsNullOrWhiteSpace(response) ? 0 : Encoding.UTF8.GetByteCount(response); if (HttpHeaders.ContainsKey("Accept-Encoding") && ((string)HttpHeaders["Accept-Encoding"]).Contains("gzip") && response != null) { HttpResponseHeaders["Content-Encoding"] = "gzip"; encodedBytes = GzipCompressString(response); contentType += "; charset=utf-8"; length = encodedBytes.Length; } HttpResponseHeaders["X-Powered-By"] = "Knoxius Servius"; HttpResponseHeaders["Access-Control-Allow-Origin"] = "*"; _outputStream.WriteLine("HTTP/1.1 " + status); var connection = (string)HttpHeaders["Connection"]; if (string.IsNullOrWhiteSpace(connection)) { connection = "close"; HttpHeaders["Connection"] = connection; } _outputStream.WriteLine("Connection: " + connection); if (!string.IsNullOrWhiteSpace(response)) { contentType = string.IsNullOrWhiteSpace(contentType) ? "text/html" : contentType; _outputStream.WriteLine("Content-Type: " + contentType); _outputStream.WriteLine("Content-Length: " + length); } foreach (var header in HttpResponseHeaders.Keys) { _outputStream.WriteLine(header + ": " + HttpResponseHeaders[header]); } foreach (var cookie in HttpResponseSetCookies.Keys) { _outputStream.WriteLine("Set-Cookie: " + cookie + "=" + HttpResponseSetCookies[cookie]); } _outputStream.WriteLine(""); if (string.IsNullOrWhiteSpace(response) || HttpMethod == HttpMethod.Head) { return; } if (encodedBytes != null) { _outputStream.Flush(); _outputStream.BaseStream.Write(encodedBytes, 0, encodedBytes.Length); } else { _outputStream.Write(response); } }