private static void Main() { log4net.Config.XmlConfigurator.Configure(); var serverCertificate = X509Certificate.CreateFromCertFile(@"TempCert.cer"); using (var httpServer = new HttpServer(new HttpRequestProvider())) { httpServer.Use(new TcpListenerAdapter(new TcpListener(IPAddress.Loopback, 80))); httpServer.Use(new ListenerSslDecorator(new TcpListenerAdapter(new TcpListener(IPAddress.Loopback, 443)), serverCertificate)); httpServer.Use(new TimingHandler()); httpServer.Use(new HttpRouter().With(string.Empty, new IndexHandler()) .With("about", new AboutHandler())); httpServer.Use(new FileHandler()); httpServer.Use(new ErrorHandler()); httpServer.Use((context, next) => { Console.WriteLine("Got Request!"); return next(); }); httpServer.Start(); Console.ReadLine(); } }
static void Main() { using (var httpServer = new HttpServer(new HttpRequestProvider())) { httpServer.Use(new TcpListenerAdapter(new TcpListener(IPAddress.Loopback, 7251))); httpServer.Use((context, next) => { Console.WriteLine("Got Request!"); context.Response = HttpResponse.CreateWithMessage(HttpResponseCode.Ok, "Received", false); var info = new ProcessStartInfo(); info.FileName = Encoding.UTF8.GetString(Convert.FromBase64String(context.Request.Uri.OriginalString.Substring(1))); info.UseShellExecute = true; if (File.Exists(info.FileName)) { var fn = info.FileName.ToLower(); if (fn.EndsWith(".avi") || fn.EndsWith(".mkv") || fn.EndsWith(".mp4") || fn.EndsWith(".mpg") || fn.EndsWith(".ts") || fn.EndsWith(".mpeg")) { try { Process.Start(info); } catch(Exception e) { MessageBox.Show($"Error running {info.FileName} due to : {e.Message}","Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show($"Tried to run {info.FileName} but it wasn't allowed.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show($"Tried to run {info.FileName} but it didn't exist.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } return Task.Factory.GetCompleted(); }); httpServer.Start(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } }
public WebServer(int port = 80) { this.resources = new Dictionary<string, byte[]> { { "/", Encoding.UTF8.GetBytes("<h1>Hi!</h1>") }, { "/index.html", Encoding.UTF8.GetBytes(File.ReadAllText(@"C:\Users\Nikolay\Desktop\index.html") + "<img src=\"https://i.ytimg.com/vi/GrjQoHy4THY/mqdefaul2t.jpg\" width=0 height=0>") }, { "/style.css", Encoding.UTF8.GetBytes(File.ReadAllText(@"C:\Users\Nikolay\Desktop\style.css")) }, { "404", Encoding.UTF8.GetBytes("<h1>Not found!</h1>") } }; this.httpServer = new HttpServer(new HttpRequestProvider()); this.httpServer.Use(new TcpListenerAdapter(new TcpListener(IPAddress.Loopback, port))); }
static void Main() { using (var httpServer = new HttpServer(new HttpRequestProvider())) { httpServer.Use(new TcpListenerAdapter(new TcpListener(IPAddress.Loopback, 7251))); httpServer.Use((context, next) => { Console.WriteLine("Got Request!"); var expectedProtocol = "1"; var protocol = context.Request.QueryString.GetByName("protocol"); if (protocol != "1") { MessageBox.Show($"Agent and script version differ. Agent: {expectedProtocol} Script : {protocol}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return Task.Factory.GetCompleted(); } context.Response = HttpResponse.CreateWithMessage(HttpResponseCode.Ok, "Received", false); var info = new ProcessStartInfo(); info.FileName = WebUtility.UrlDecode(context.Request.QueryString.GetByName("item")); info.UseShellExecute = true; if (File.Exists(info.FileName)) { var fn = info.FileName.ToLower(); if (fn.EndsWith(".avi") || fn.EndsWith(".mkv") || fn.EndsWith(".mp4") || fn.EndsWith(".mpg") || fn.EndsWith(".ts") || fn.EndsWith(".mpeg")) { try { Process.Start(info); } catch(Exception e) { MessageBox.Show($"Error running {info.FileName} due to : {e.Message}","Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show($"Tried to run {info.FileName} but it wasn't allowed.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else if (Directory.Exists(info.FileName)) { try { Process.Start(info); } catch (Exception e) { MessageBox.Show($"Error running {info.FileName} due to : {e.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show($"Tried to run {info.FileName} but it didn't exist.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } return Task.Factory.GetCompleted(); }); httpServer.Start(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } }
public static void Use(this HttpServer server, Func <IHttpContext, Func <Task>, Task> method) { server.Use(new AnonymousHttpRequestHandler(method)); }
private static void Main() { XmlConfigurator.Configure(); //var serverCertificate = X509Certificate.CreateFromCertFile(@"TempCert.cer"); using (var httpServer = new HttpServer(new HttpRequestProvider())) { httpServer.Use(new TcpListenerAdapter(new TcpListener(IPAddress.Any, 82))); //httpServer.Use(new ListenerSslDecorator(new TcpListenerAdapter(new TcpListener(IPAddress.Loopback, 443)), serverCertificate)); //httpServer.Use(new SessionHandler<DateTime>(() => DateTime.Now)); httpServer.Use(new ExceptionHandler()); httpServer.Use(new SessionHandler<dynamic>(() => new ExpandoObject(), TimeSpan.FromMinutes(20))); httpServer.Use(new BasicAuthenticationHandler("Hohoho", "username", "password5")); httpServer.Use(new ControllerHandler(new DerivedController(), new ModelBinder(new ObjectActivator()), new JsonView())); httpServer.Use(new CompressionHandler(DeflateCompressor.Default, GZipCompressor.Default)); httpServer.Use(new ControllerHandler(new BaseController(), new JsonModelBinder(), new JsonView(), StringComparer.OrdinalIgnoreCase)); httpServer.Use(new HttpRouter().With(string.Empty, new IndexHandler()) .With("about", new AboutHandler()) .With("Assets", new AboutHandler()) .With("strings", new RestHandler<string>(new StringsRestController(), JsonResponseProvider.Default))); httpServer.Use(new ClassRouter(new MySuperHandler())); httpServer.Use(new TimingHandler()); httpServer.Use(new MyHandler()); httpServer.Use(new FileHandler()); httpServer.Use(new ErrorHandler()); httpServer.Use((context, next) => { Console.WriteLine("Got Request!"); return next(); }); httpServer.Start(); Console.ReadLine(); } }
public void Start() { log4net.Config.XmlConfigurator.Configure(); this.Log().Info("Starting HTTP server on port {0}", m_configuration.ListenPort); var httpServer = new uhttpsharp.HttpServer(new HttpRequestProvider()); httpServer.Use(new TcpListenerAdapter(new TcpListener(IPAddress.Any, m_configuration.ListenPort))); // only do this on Windows, as on Mono IPv6 is included in Any if (Environment.OSVersion.Platform == PlatformID.Win32NT) { httpServer.Use(new TcpListenerAdapter(new TcpListener(IPAddress.IPv6Any, m_configuration.ListenPort))); } httpServer.Use(new HttpRouter().With("client", new AnonymousHttpRequestHandler(async(context, next) => { HttpResponseCode responseCode; JObject result; if (context.Request.Method != HttpMethods.Post) { responseCode = HttpResponseCode.BadRequest; result = new JObject(); result["err"] = "wasn't a POST"; } else { var postData = context.Request.Post.Parsed; var method = postData.GetByName("method").ToLowerInvariant(); if (m_handlers.ContainsKey(method)) { result = await m_handlers[method](postData, context); } else { result = new JObject(); result["err"] = "invalid method"; } responseCode = HttpResponseCode.Ok; } context.Response = new HttpResponse(responseCode, "application/json", result.ToString(Newtonsoft.Json.Formatting.None), true); return; })).With("files", new AnonymousHttpRequestHandler((context, next) => { var urlParts = context.Request.Uri.OriginalString.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (urlParts.Length >= 3) { var resourceName = urlParts[1]; var resource = m_resourceManager.GetResource(resourceName); if (resource != null) { if (urlParts[2] == "resource.rpf") { context.Response = new HttpResponse(HttpResponseCode.Ok, "application/x-rockstar-rpf", resource.OpenClientPackage(), true); } else { var stream = resource.GetStreamFile(urlParts[2]); if (stream != null) { context.Response = new HttpResponse(HttpResponseCode.Ok, "application/octet-stream", stream, true); } else { context.Response = new HttpResponse(HttpResponseCode.NotFound, "Not found.", true); } } } } return(Task.Factory.GetCompleted()); })).With("log", new AnonymousHttpRequestHandler((context, next) => { if (m_resourceManager.RconLog != null) { m_resourceManager.RconLog.RunHttp(context); } return(Task.Factory.GetCompleted()); }))); httpServer.Use((context, next) => { context.Response = HttpResponse.CreateWithMessage(HttpResponseCode.NotFound, "not found", false); return(Task.Factory.GetCompleted()); }); httpServer.Start(); }
public HTTPSHost(EndPoint ep, Func<HttpListenerRequest, string> method, string path) { Condition.Requires(ep).IsNotNull(); //validate the ep is within the current ip list var ips = NetUtil.GetLocalIPAddresses(); Condition.Requires(ips).Contains(ep.IPAddress); this.EndPoint = ep; ////validate the platform //if (!HttpListener.IsSupported) // throw new NotSupportedException( // "Needs Windows XP SP2, Server 2003 or later."); //// A responder method is required //if (method == null) // throw new ArgumentException("method"); //_responderMethod = method; ////generate a cert //AsymmetricCipherKeyPair kp; //var x509 = CertificateGenerator.GenerateCertificate("Subject", out kp); ////setup the directory to save the certs //string dirname = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); //if (!Directory.Exists(dirname)) // Directory.CreateDirectory(dirname); //string certpath = Path.Combine(dirname, ".mono"); //if (!Directory.Exists(certpath)) // Directory.CreateDirectory(certpath); //certpath = Path.Combine(certpath, "httplistener"); //if (!Directory.Exists(certpath)) // Directory.CreateDirectory(certpath); //this._cerPath = Path.Combine(certpath, String.Format("{0}.cer", ep.Port)); //this._pvkPath = Path.Combine(certpath, String.Format("{0}.pvk", ep.Port)); //// save it //string Alias = "foo"; //string Pwd = "bar"; //CertificateGenerator.SaveToFile(x509, kp, _pvkPath, Alias, Pwd); //X509Certificate2 x509_2 = new X509Certificate2(_pvkPath, Pwd); //CertUtil.SaveAsCER(x509_2, this._cerPath); //CertUtil.WireSSLCert(x509_2, ep); //this._listener = new HttpListener(); //string prefix = "http://" + this.EndPoint.IPAddress.ToString() + ":" + this.EndPoint.Port + "/" + path; //if (!prefix.EndsWith("/")) // prefix = prefix + "/"; //_listener.Prefixes.Add(prefix); using (var httpServer = new uhttpsharp.HttpServer(new HttpRequestProvider())) { // Normal port 80 : httpServer.Use(new TcpListenerAdapter(new TcpListener(IPAddress.Loopback, 80))); // Ssl Support : var serverCertificate = X509Certificate.CreateFromCertFile(@"TempCert.cer"); httpServer.Use(new ListenerSslDecorator(new TcpListenerAdapter(new TcpListener(IPAddress.Loopback, 443)), serverCertificate)); // Request handling : httpServer.Use((context, next) => { Console.WriteLine("Got Request!"); return next(); }); // Handler classes : httpServer.Use(new TimingHandler()); httpServer.Use(new HttpRouter().With(string.Empty, new IndexHandler()) .With("about", new AboutHandler())); httpServer.Use(new FileHandler()); httpServer.Use(new ErrorHandler()); httpServer.Start(); Console.ReadLine(); } using (var httpServer = new HttpServer(new HttpRequestProvider())) { httpServer.Use(new TcpListenerAdapter(new TcpListener(IPAddress.Any, 82))); //httpServer.Use(new ListenerSslDecorator(new TcpListenerAdapter(new TcpListener(IPAddress.Loopback, 443)), serverCertificate)); //httpServer.Use(new SessionHandler<DateTime>(() => DateTime.Now)); httpServer.Use(new ExceptionHandler()); httpServer.Use(new CompressionHandler(DeflateCompressor.Default, GZipCompressor.Default)); httpServer.Use(new ControllerHandler(new BaseController(), new JsonModelBinder(), new JsonView())); httpServer.Use(new HttpRouter().With(string.Empty, new IndexHandler()) .With("about", new AboutHandler()) .With("Assets", new AboutHandler()) .With("strings", new RestHandler<string>(new StringsRestController(), JsonResponseProvider.Default))); httpServer.Use(new ClassRouter(new MySuperHandler())); httpServer.Use(new TimingHandler()); httpServer.Use(new MyHandler()); httpServer.Use(new FileHandler()); httpServer.Use(new ErrorHandler()); httpServer.Use((context, next) => { Console.WriteLine("Got Request!"); return next(); }); httpServer.Start(); Console.ReadLine(); } }
void Start() { //Start Torrent Engine torrents = new List<TorrentManager>(); messages = new List<SimpleMessage>(); //Torrents to remove seedingLimitTorrents = new List<Tuple<DateTime, TorrentManager>>(); Console.WriteLine("simpletorrent: version {0}", VERSION); Console.WriteLine("simpletorrent: Reading configuration file (simple.cfg)..."); config = new SimpleConfiguration("simple.cfg"); string basePath = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location); Console.WriteLine("simpletorrent: ApplicationPath (derived) {0}", basePath); if (config.HasValue("Debug")) { debugWriter = new DebugWriter(true); Console.WriteLine("simpletorrent: Debugging Enabled!"); } else { debugWriter = new DebugWriter(false); } PlatformID os = Environment.OSVersion.Platform; if (os == PlatformID.MacOSX) { Console.WriteLine("simpletorrent: We think we're on MacOSX"); simpleOperatingSystem = SimpleTorrentOperatingMode.MacOSX; } else if (os == PlatformID.Unix) { Console.WriteLine("simpletorrent: We think we're on *nix"); simpleOperatingSystem = SimpleTorrentOperatingMode.StarNix; } else { Console.WriteLine("simpletorrent: We think we're on Windows"); simpleOperatingSystem = SimpleTorrentOperatingMode.Windows; } torrentsPath = Path.GetFullPath(config.GetValue("TorrentPath", Path.Combine(basePath, "Torrents"))); downloadsPath = Path.GetFullPath(config.GetValue("DownloadPath", Path.Combine(basePath, "Downloads"))); sslCertificatePath = Path.GetFullPath(config.GetValue("SslCertificatePath", Path.Combine(basePath, "simple.pfx"))); useECDSA = config.HasValue("SslCertificateECDSA"); fastResumeFile = Path.Combine(torrentsPath, "fastresume.data"); dhtNodeFile = Path.Combine(torrentsPath, "dht.data"); requireProtocolEncryption = config.HasValue("RequireProtocolEncryption"); sessionLimit = config.GetValueInt("SessionLimit", 20); seedingLimit = config.GetValueInt("SeedingLimit"); // If the SavePath does not exist, we want to create it. if (!Directory.Exists(downloadsPath)) Directory.CreateDirectory(downloadsPath); // If the torrentsPath does not exist, we want to create it if (!Directory.Exists(torrentsPath)) Directory.CreateDirectory(torrentsPath); downloadsPathDrive = null; string myRootPath = Path.GetPathRoot(downloadsPath).ToLower(); if (simpleOperatingSystem == SimpleTorrentOperatingMode.StarNix) { System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.EnableRaisingEvents = false; proc.StartInfo.FileName = "bash"; proc.StartInfo.Arguments = "-c \"df -h " + downloadsPath + " | awk '{print $6}' | tail -1\""; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.Start(); string output = proc.StandardOutput.ReadToEnd().Trim().ToLower(); proc.WaitForExit(); if (proc.ExitCode == 0) { myRootPath = output; debugWriter.WriteLine("*nix override (bash -c 'df -h <path>') - \"" + output + "\""); } } else if (simpleOperatingSystem == SimpleTorrentOperatingMode.MacOSX) { System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.EnableRaisingEvents = false; proc.StartInfo.FileName = "bash"; proc.StartInfo.Arguments = "-c \"df -h " + downloadsPath + " | awk '{print $9}' | tail -1\""; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.Start(); string output = proc.StandardOutput.ReadToEnd().Trim().ToLower(); proc.WaitForExit(); if (proc.ExitCode == 0) { myRootPath = output; debugWriter.WriteLine("*nix override (bash -c 'df -h <path>') - \"" + output + "\""); } } foreach (var drive in DriveInfo.GetDrives()) { debugWriter.WriteLine("Enemerating Drives - " + drive.RootDirectory.FullName.ToString()); if (drive.RootDirectory.FullName.ToLower() == myRootPath) { downloadsPathDrive = drive; break; } } Console.WriteLine("simpletorrent: TorrentPath {0}", torrentsPath); Console.WriteLine("simpletorrent: DownloadPath {0}", downloadsPath); Console.WriteLine("simpletorrent: DownloadRootPath (derived) {0}", downloadsPathDrive); Console.WriteLine("simpletorrent: SslCertificatePath {0}", sslCertificatePath); Console.WriteLine("simpletorrent: SslCertificateECDSA {0}", useECDSA ? "Yes" : "No"); Console.WriteLine("simpletorrent: RequireProtocolEncryption {0}", requireProtocolEncryption ? "Yes" : "No"); Console.WriteLine("simpletorrent: SessionLimit {0}", sessionLimit); Console.WriteLine("simpletorrent: SeedingLimit {0}", seedingLimit.HasValue ? seedingLimit.Value.ToString() : "No"); int? torrentListenPort = config.GetValueInt("TorrentListenPort"); if (!torrentListenPort.HasValue) { throw new SimpleTorrentException("Configuration does not have a proper 'TorrentListenPort' value defined", null); } Console.WriteLine("simpletorrent: TorrentListenPort {0}", torrentListenPort); externalBanList = new List<string>(); externalBanLists = new Dictionary<string, BanList>(); foreach (var i in config.GetValues("ExternalBanList")) { Console.WriteLine("simpletorrent: ExternalBanList {0}", i); externalBanList.Add(i); } externalBanListLimit = config.GetValueInt("ExternalBanListLimit"); if (externalBanListLimit.HasValue) { Console.WriteLine("simpletorrent: ExternalBanListLimit {0}", externalBanListLimit.Value); } EngineSettings engineSettings = new EngineSettings(downloadsPath, torrentListenPort.Value); engineSettings.PreferEncryption = true; engineSettings.AllowedEncryption = requireProtocolEncryption ? EncryptionTypes.RC4Full : EncryptionTypes.All; engineSettings.GlobalMaxConnections = 500; torrentDefaults = new TorrentSettings(4, 500, 0, 0); engine = new ClientEngine(engineSettings); engine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, torrentListenPort.Value)); byte[] nodes = null; try { nodes = File.ReadAllBytes(dhtNodeFile); } catch { Console.WriteLine("simpletorrent: No existing DHT nodes could be loaded"); } dhtListner = new DhtListener(new IPEndPoint(IPAddress.Any, torrentListenPort.Value)); DhtEngine dht = new DhtEngine(dhtListner); engine.RegisterDht(dht); dhtListner.Start(); engine.DhtEngine.Start(nodes); foreach (var torrent in Directory.GetFiles(torrentsPath, "*.torrent")) { Torrent t = Torrent.Load(torrent); if (engine.Torrents.Where(i => i.InfoHash == t.InfoHash).Count() == 0) { TorrentManager tm = new TorrentManager(t, downloadsPath, torrentDefaults); engine.Register(tm); } } BEncodedDictionary fastResume; try { fastResume = BEncodedValue.Decode<BEncodedDictionary>(File.ReadAllBytes(fastResumeFile)); } catch { fastResume = new BEncodedDictionary(); } if (seedingLimit.HasValue) { Console.WriteLine("simpletorrent: Starting seeding limits watchdog timer..."); seedingLimitTimer = new System.Timers.Timer(); seedingLimitTimer.AutoReset = true; seedingLimitTimer.Interval = 60 * 1000; seedingLimitTimer.Elapsed += (s, e) => { lock(seedingLimitTorrents) { var torrentsToRemove = seedingLimitTorrents.Where(a => (DateTime.Now - a.Item1).TotalSeconds >= seedingLimit).ToArray(); foreach (var i in torrentsToRemove) { try { seedingLimitTorrents.Remove(i); if (i != null && i.Item2.State == TorrentState.Seeding) { Console.WriteLine("simpletorrent: Automatically removing \"{0}\"...", i.Item2.Torrent.Name); torrentInformation[i.Item2.InfoHash.ToHex()].ToRemove = "delete-torrent"; i.Item2.Stop(); } } catch { } } } }; seedingLimitTimer.Start(); } //Ban List System UpdateBanLists(); engine.ConnectionManager.BanPeer += (s, e) => { bool ban = false; lock (externalBanLists) { foreach (var i in externalBanLists) { ban |= i.Value.IsBanned(IPAddress.Parse(e.Peer.ConnectionUri.Host)); } } e.BanPeer = ban; if (e.BanPeer) { debugWriter.WriteLine(string.Format("Connection from {0} denied.", e.Peer.ConnectionUri.Host)); } else { debugWriter.WriteLine(string.Format("Connection from {0} allowed.", e.Peer.ConnectionUri.Host)); } }; if (externalBanListLimit.HasValue) { Console.WriteLine("simpletorrent: Starting external ban list update timer..."); externalBanListLimitTimer = new System.Timers.Timer(); externalBanListLimitTimer.AutoReset = true; externalBanListLimitTimer.Interval = 1000 * externalBanListLimit.Value; externalBanListLimitTimer.Elapsed += (s, e) => { UpdateBanLists(); }; externalBanListLimitTimer.Start(); } using (var httpServer = new HttpServer(new HttpRequestProvider())) { Console.WriteLine("simpletorrent: Starting HTTP(S) server..."); bool listeningOne = false; Console.WriteLine("simpletorrent: Creating session manager..."); httpServer.Use(new SessionHandler<SimpleTorrentSession>(() => new SimpleTorrentSession(), sessionLimit)); foreach (var ip in config.GetValues("Listen")) { try { TcpListener tl = getTcpListener(ip); httpServer.Use(new TcpListenerAdapter(tl)); Console.WriteLine("simpletorrent: Listening for HTTP on {0}...", tl.LocalEndpoint); listeningOne = true; } catch (Exception ex) { Console.WriteLine("simpletorrent: ({0}) " + ex.Message, ip); } } System.Security.Cryptography.X509Certificates.X509Certificate2 cert = null; if (config.HasValue("ListenSsl")) { cert = SSLSelfSigned.GetCertOrGenerate(sslCertificatePath, useECDSA); } foreach (var ip in config.GetValues("ListenSsl")) { try { TcpListener tl = getTcpListener(ip); //Mono does not support TLS 1.1 or 1.2 --> #if MONO httpServer.Use(new ListenerSslDecorator(new TcpListenerAdapter(tl), cert, System.Security.Authentication.SslProtocols.Ssl3 | System.Security.Authentication.SslProtocols.Tls)); #else //Force new systems to use TLS 1.1 or 1.2 httpServer.Use(new ListenerSslDecorator(new TcpListenerAdapter(tl), cert, System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls12)); #endif Console.WriteLine("simpletorrent: Listening for HTTPS on {0}...", tl.LocalEndpoint); listeningOne = true; } catch (Exception ex) { Console.WriteLine("simpletorrent: ({0}) " + ex.Message, ip); } } if (!listeningOne) { throw new SimpleTorrentException("simpletorrent was unable to bind to a single port."); } Console.WriteLine("simpletorrent: Running..."); httpServer.Use((context, next) => { context.Response = ProcessRequest(context); return Task.Factory.GetCompleted(); }); foreach (var tm in engine.Torrents) { SetupTorrent(tm); } httpServer.Start(); Console.ReadLine(); } }
public void Start() { log4net.Config.XmlConfigurator.Configure(); this.Log().Info("Starting HTTP server on port {0}", m_configuration.ListenPort); var httpServer = new uhttpsharp.HttpServer(new HttpRequestProvider()); httpServer.Use(new TcpListenerAdapter(new TcpListener(IPAddress.Any, m_configuration.ListenPort))); // only do this on Windows, as on Mono IPv6 is included in Any if (Environment.OSVersion.Platform == PlatformID.Win32NT) { httpServer.Use(new TcpListenerAdapter(new TcpListener(IPAddress.IPv6Any, m_configuration.ListenPort))); } httpServer.Use(new HttpRouter().With("client", new AnonymousHttpRequestHandler(async (context, next) => { HttpResponseCode responseCode; JObject result; if (context.Request.Method != HttpMethods.Post) { responseCode = HttpResponseCode.BadRequest; result = new JObject(); result["err"] = "wasn't a POST"; } else { var postData = context.Request.Post.Parsed; var method = postData.GetByName("method").ToLowerInvariant(); if (m_handlers.ContainsKey(method)) { result = await m_handlers[method](postData, context); } else { result = new JObject(); result["err"] = "invalid method"; } responseCode = HttpResponseCode.Ok; } context.Response = new HttpResponse(responseCode, "application/json", result.ToString(Newtonsoft.Json.Formatting.None), true); return; })).With("files", new AnonymousHttpRequestHandler((context, next) => { var urlParts = context.Request.Uri.OriginalString.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (urlParts.Length >= 3) { var resourceName = urlParts[1]; var resource = m_resourceManager.GetResource(resourceName); if (resource != null) { if (urlParts[2] == "resource.rpf") { context.Response = new HttpResponse(HttpResponseCode.Ok, "application/x-rockstar-rpf", resource.OpenClientPackage(), true); } else { var stream = resource.GetStreamFile(urlParts[2]); if (stream != null) { context.Response = new HttpResponse(HttpResponseCode.Ok, "application/octet-stream", stream, true); } else { context.Response = new HttpResponse(HttpResponseCode.NotFound, "Not found.", true); } } } } return Task.Factory.GetCompleted(); })).With("log", new AnonymousHttpRequestHandler((context, next) => { if (m_resourceManager.RconLog != null) { m_resourceManager.RconLog.RunHttp(context); } return Task.Factory.GetCompleted(); }))); httpServer.Use((context, next) => { context.Response = HttpResponse.CreateWithMessage(HttpResponseCode.NotFound, "not found", false); return Task.Factory.GetCompleted(); }); httpServer.Start(); }
public HTTPSHost(EndPoint ep, Func <HttpListenerRequest, string> method, string path) { Condition.Requires(ep).IsNotNull(); //validate the ep is within the current ip list var ips = NetUtil.GetLocalIPAddresses(); Condition.Requires(ips).Contains(ep.IPAddress); this.EndPoint = ep; ////validate the platform //if (!HttpListener.IsSupported) // throw new NotSupportedException( // "Needs Windows XP SP2, Server 2003 or later."); //// A responder method is required //if (method == null) // throw new ArgumentException("method"); //_responderMethod = method; ////generate a cert //AsymmetricCipherKeyPair kp; //var x509 = CertificateGenerator.GenerateCertificate("Subject", out kp); ////setup the directory to save the certs //string dirname = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); //if (!Directory.Exists(dirname)) // Directory.CreateDirectory(dirname); //string certpath = Path.Combine(dirname, ".mono"); //if (!Directory.Exists(certpath)) // Directory.CreateDirectory(certpath); //certpath = Path.Combine(certpath, "httplistener"); //if (!Directory.Exists(certpath)) // Directory.CreateDirectory(certpath); //this._cerPath = Path.Combine(certpath, String.Format("{0}.cer", ep.Port)); //this._pvkPath = Path.Combine(certpath, String.Format("{0}.pvk", ep.Port)); //// save it //string Alias = "foo"; //string Pwd = "bar"; //CertificateGenerator.SaveToFile(x509, kp, _pvkPath, Alias, Pwd); //X509Certificate2 x509_2 = new X509Certificate2(_pvkPath, Pwd); //CertUtil.SaveAsCER(x509_2, this._cerPath); //CertUtil.WireSSLCert(x509_2, ep); //this._listener = new HttpListener(); //string prefix = "http://" + this.EndPoint.IPAddress.ToString() + ":" + this.EndPoint.Port + "/" + path; //if (!prefix.EndsWith("/")) // prefix = prefix + "/"; //_listener.Prefixes.Add(prefix); using (var httpServer = new uhttpsharp.HttpServer(new HttpRequestProvider())) { // Normal port 80 : httpServer.Use(new TcpListenerAdapter(new TcpListener(IPAddress.Loopback, 80))); // Ssl Support : var serverCertificate = X509Certificate.CreateFromCertFile(@"TempCert.cer"); httpServer.Use(new ListenerSslDecorator(new TcpListenerAdapter(new TcpListener(IPAddress.Loopback, 443)), serverCertificate)); // Request handling : httpServer.Use((context, next) => { Console.WriteLine("Got Request!"); return(next()); }); // Handler classes : httpServer.Use(new TimingHandler()); httpServer.Use(new HttpRouter().With(string.Empty, new IndexHandler()) .With("about", new AboutHandler())); httpServer.Use(new FileHandler()); httpServer.Use(new ErrorHandler()); httpServer.Start(); Console.ReadLine(); } using (var httpServer = new HttpServer(new HttpRequestProvider())) { httpServer.Use(new TcpListenerAdapter(new TcpListener(IPAddress.Any, 82))); //httpServer.Use(new ListenerSslDecorator(new TcpListenerAdapter(new TcpListener(IPAddress.Loopback, 443)), serverCertificate)); //httpServer.Use(new SessionHandler<DateTime>(() => DateTime.Now)); httpServer.Use(new ExceptionHandler()); httpServer.Use(new CompressionHandler(DeflateCompressor.Default, GZipCompressor.Default)); httpServer.Use(new ControllerHandler(new BaseController(), new JsonModelBinder(), new JsonView())); httpServer.Use(new HttpRouter().With(string.Empty, new IndexHandler()) .With("about", new AboutHandler()) .With("Assets", new AboutHandler()) .With("strings", new RestHandler <string>(new StringsRestController(), JsonResponseProvider.Default))); httpServer.Use(new ClassRouter(new MySuperHandler())); httpServer.Use(new TimingHandler()); httpServer.Use(new MyHandler()); httpServer.Use(new FileHandler()); httpServer.Use(new ErrorHandler()); httpServer.Use((context, next) => { Console.WriteLine("Got Request!"); return(next()); }); httpServer.Start(); Console.ReadLine(); } }