public static void Http11SendResponse(SecureSocket socket) { string[] headers = GetHttp11Headers(socket); string filename = GetFileName(headers); if (headers.Length == 0) { Http2Logger.LogError("Request headers empty!"); } string path = Path.GetFullPath(AssemblyPath + @"\root" + filename); string contentType = ContentTypes.GetTypeFromFileName(filename); if (!File.Exists(path)) { Http2Logger.LogError("File " + filename + " not found"); SendResponse(socket, new byte[0], StatusCode.Code404NotFound, contentType); socket.Close(); return; } try { using (var sr = new StreamReader(path)) { string file = sr.ReadToEnd(); var fileBytes = Encoding.UTF8.GetBytes(file); int sent = SendResponse(socket, fileBytes, StatusCode.Code200Ok, contentType); Http2Logger.LogDebug(string.Format("Sent: {0} bytes", sent)); Http2Logger.LogInfo("File sent: " + filename); socket.Close(); if (OnSocketClosed != null) { OnSocketClosed(null, new SocketCloseEventArgs()); } } } catch (Exception ex) { var msgBytes = Encoding.UTF8.GetBytes(ex.Message); SendResponse(socket, msgBytes, StatusCode.Code500InternalServerError, contentType); Http2Logger.LogError(ex.Message); } }
private void Listen() { InitializeRootFileList(); Http2Logger.LogInfo("Started on port " + _port); _server.Start(); while (!_disposed) { try { var client = new HttpConnectingClient(_server, _options, _next, _useHandshake, _usePriorities, _useFlowControl, _listOfRootFiles); client.Accept(); } catch (Exception ex) { Http2Logger.LogError("Unhandled exception was caught: " + ex.Message); } } }
public HttpSocketServer(Func <IOwinContext, Task> next, IDictionary <string, object> properties) { _next = next; var addresses = (IList <IDictionary <string, object> >)properties["host.Addresses"]; var address = addresses.First(); _port = Int32.Parse(address.Get <string>("port")); _scheme = address.Get <string>("scheme"); _cancelAccept = new CancellationTokenSource(); _useHandshake = (bool)properties["use-handshake"]; _usePriorities = (bool)properties["use-priorities"]; _useFlowControl = (bool)properties["use-flowControl"]; int securePort; if (!int.TryParse(ConfigurationManager.AppSettings["securePort"], out securePort)) { Http2Logger.LogError("Incorrect port in the config file!"); return; } try { _serverCert = LoadPKCS12Certificate(AssemblyName + CertificateFilename, "p@ssw0rd"); } catch (Exception ex) { Http2Logger.LogInfo("Unable to start server. Check certificate. Exception: " + ex.Message); return; } _isSecure = _port == securePort; _server = new TcpListener(IPAddress.Any, _port); ThreadPool.SetMaxThreads(30, 10); _listenThread = new Thread(Listen); _listenThread.Start(); }
private void Listen() { Http2Logger.LogInfo("Server running at port " + _port); _server.Start(); while (!_disposed) { try { var client = new HttpConnectingClient(_server, _next.Invoke, _serverCert, _isSecure, _useHandshake, _usePriorities, _useFlowControl); client.Accept(_cancelAccept.Token); } catch (Exception ex) { Http2Logger.LogError("Unhandled exception was caught: " + ex.Message); } } Http2Logger.LogDebug("Listen thread was finished"); }
/// <summary> /// Pumps the incomming data and calls dispatch for it /// </summary> private void PumpIncommingData() { while (!_goAwayReceived && !_disposed) { Frame frame; try { frame = _frameReader.ReadFrame(); if (!_wasResponseReceived) { _wasResponseReceived = true; } } catch (IOException) { //Connection was closed by the remote endpoint Http2Logger.LogInfo("Connection was closed by the remote endpoint"); Dispose(); break; } catch (Exception) { // Read failure, abort the connection/session. Http2Logger.LogInfo("Read failure, abort the connection/session"); Dispose(); break; } if (frame != null) { DispatchIncomingFrame(frame); } else { // Looks like connection was lost Dispose(); break; } } Http2Logger.LogDebug("Read thread finished"); }
private static void SaveFile(string directory, string fileName, byte[] fileBytes) { string newfilepath; // create local file path if (!string.IsNullOrEmpty(directory)) { if (directory[0] == '\\') { directory = '.' + directory; } Directory.CreateDirectory(directory); newfilepath = directory + '\\' + fileName; } else { newfilepath = fileName; } if (File.Exists(newfilepath)) { try { File.Delete(newfilepath); } catch (Exception) { Http2Logger.LogError("Cant overwrite file: " + newfilepath); } } using (var fs = new FileStream(newfilepath, FileMode.Create)) { fs.Write(fileBytes, 0, fileBytes.Length); } Http2Logger.LogInfo("File saved: " + fileName); }
/// <summary> /// Get files via http request. /// </summary> /// <param name="content">Downloaded file.</param> /// <param name="type">Type of file.</param> /// <param name="requestUri">Full name of file.</param> /// <param name="uri">The address site.</param> private void PrivateGetFile(byte[] content, string type, Uri requestUri, string uri) { byte[] headers = this.GetHeaders(content); if (headers == null) { Http2Logger.LogError("HTTP response: Invalid"); return; } this.httpMonitor.LogResponse(headers, content.Length); int status = this.GetStatus(headers); if (useHttp2Handshake) { Http2Logger.LogDebug(Encoding.UTF8.GetString(headers)); } Http2Logger.LogInfo(string.Format("HTTP response: {0}, length: {1} name:{2}", status, content.LongLength, uri)); if (status == 200 || status == 101) { string url = requestUri.Scheme + "://" + requestUri.Authority; string directory = string.Empty; string localDir = string.Empty; string file = requestUri.LocalPath; string localFile = Path.GetFileName(uri); for (int i = 0; i < requestUri.Segments.Length - 1; i++) { directory += requestUri.Segments[i]; localDir += requestUri.Segments[i].Replace('/', '\\'); } if (!string.IsNullOrEmpty(localDir)) { if (localDir[0] == '\\') { localDir = '.' + localDir; } Directory.CreateDirectory(localDir); localFile = localDir + '\\' + localFile; } int contentOffset = headers.Length; using (var fs = new FileStream(localFile, FileMode.Create)) { fs.Write(content, contentOffset, content.Length - contentOffset); } if (type == ContentTypes.TextHtml) { string strContent = Encoding.UTF8.GetString(content, contentOffset, content.Length - contentOffset) .Replace("http2frame_start\r\n", "") .Replace("http2frame_end", ""); XHtmlDocument document = XHtmlDocument.Parse(strContent); string path = url + directory; foreach (var image in document.Images) { this.AddNameToDownloadList(string.Format("{0}/{1}", path.ToLower(), image.ToLower())); } foreach (var link in document.Links) { this.AddNameToDownloadList(string.Format("{0}/{1}", path.ToLower(), link.ToLower())); } foreach (var script in document.Scripts) { this.AddNameToDownloadList(string.Format("{0}/{1}", path.ToLower(), script.ToLower())); } } } // if status 200 }