Refactor services for ASP.NET Core

This commit is contained in:
flightlevel
2018-05-01 21:41:34 +10:00
parent d87d0f87b1
commit 13426fe7ec
3 changed files with 23 additions and 177 deletions

View File

@@ -9,7 +9,7 @@ using Jackett.Common.Models.Config;
using Jackett.Common.Services.Interfaces; using Jackett.Common.Services.Interfaces;
using Jackett.Common.Utils; using Jackett.Common.Utils;
namespace Jackett.Services namespace Jackett.Server.Services
{ {
public class ProtectionService : IProtectionService public class ProtectionService : IProtectionService

View File

@@ -6,7 +6,7 @@ using System.Text;
using Jackett.Common.Models.Config; using Jackett.Common.Models.Config;
using Jackett.Common.Services.Interfaces; using Jackett.Common.Services.Interfaces;
namespace Jackett.Services namespace Jackett.Server.Services
{ {
class SecuityService : ISecuityService class SecuityService : ISecuityService
@@ -60,10 +60,10 @@ namespace Jackett.Services
try try
{ {
var cookie = request.Headers.GetCookies(COOKIENAME).FirstOrDefault(); var cookie = request.Headers.GetValues(COOKIENAME).FirstOrDefault();
if (cookie != null) if (cookie != null)
{ {
return cookie[COOKIENAME].Value == _serverConfig.AdminPassword; return cookie == _serverConfig.AdminPassword;
} }
} }
catch { } catch { }

View File

@@ -1,4 +1,7 @@
using Microsoft.Owin.Hosting; using Jackett.Common.Models.Config;
using Jackett.Common.Services.Interfaces;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.WebUtilities;
using NLog; using NLog;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -6,23 +9,12 @@ using System.Globalization;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using System.Web;
using System.Collections;
using System.Text.RegularExpressions;
using Jackett.Common;
using Jackett.Common.Models.Config;
using Jackett.Common.Services.Interfaces;
using Jackett.Common.Utils.Clients;
namespace Jackett.Services namespace Jackett.Server.Services
{ {
public class ServerService : IServerService public class ServerService : IServerService
{ {
private IDisposable _server = null; private IDisposable _server = null;
@@ -36,7 +28,7 @@ namespace Jackett.Services
private IUpdateService updater; private IUpdateService updater;
private List<string> _notices = new List<string>(); private List<string> _notices = new List<string>();
private ServerConfig config; private ServerConfig config;
IProtectionService _protectionService; private IProtectionService _protectionService;
public ServerService(IIndexerManagerService i, IProcessService p, ISerializeService s, IConfigurationService c, Logger l, Common.Utils.Clients.WebClient w, IUpdateService u, IProtectionService protectionService, ServerConfig serverConfig) public ServerService(IIndexerManagerService i, IProcessService p, ISerializeService s, IConfigurationService c, Logger l, Common.Utils.Clients.WebClient w, IUpdateService u, IProtectionService protectionService, ServerConfig serverConfig)
{ {
@@ -65,7 +57,7 @@ namespace Jackett.Services
return link; return link;
var encryptedLink = _protectionService.Protect(link.ToString()); var encryptedLink = _protectionService.Protect(link.ToString());
var encodedLink = HttpServerUtility.UrlTokenEncode(Encoding.UTF8.GetBytes(encryptedLink)); var encodedLink = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(encryptedLink));
string urlEncodedFile = WebUtility.UrlEncode(file); string urlEncodedFile = WebUtility.UrlEncode(file);
var proxyLink = string.Format("{0}{1}/{2}/?jackett_apikey={3}&path={4}&file={5}", serverUrl, action, indexerId, config.APIKey, encodedLink, urlEncodedFile); var proxyLink = string.Format("{0}{1}/{2}/?jackett_apikey={3}&path={4}&file={5}", serverUrl, action, indexerId, config.APIKey, encodedLink, urlEncodedFile);
return new Uri(proxyLink); return new Uri(proxyLink);
@@ -129,129 +121,6 @@ namespace Jackett.Services
{ {
logger.Error(e, "Error while reading the issue file"); logger.Error(e, "Error while reading the issue file");
} }
Type monotype = Type.GetType("Mono.Runtime");
if (monotype != null)
{
MethodInfo displayName = monotype.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static);
var monoVersion = "unknown";
if (displayName != null)
monoVersion = displayName.Invoke(null, null).ToString();
logger.Info("mono version: " + monoVersion);
var monoVersionO = new Version(monoVersion.Split(' ')[0]);
if (monoVersionO.Major < 4)
{
logger.Error("Your mono version is to old (mono 3 is no longer supported). Please update to the latest version from http://www.mono-project.com/download/");
Engine.Exit(2);
}
else if (monoVersionO.Major == 4 && monoVersionO.Minor == 2)
{
var notice = "mono version 4.2.* is known to cause problems with Jackett. If you experience any problems please try updating to the latest mono version from http://www.mono-project.com/download/ first.";
_notices.Add(notice);
logger.Error(notice);
}
try
{
// Check for mono-devel
// Is there any better way which doesn't involve a hard cashes?
var mono_devel_file = Path.Combine(runtimedir, "mono-api-info.exe");
if (!File.Exists(mono_devel_file))
{
var notice = "It looks like the mono-devel package is not installed, please make sure it's installed to avoid crashes.";
_notices.Add(notice);
logger.Error(notice);
}
}
catch (Exception e)
{
logger.Error(e, "Error while checking for mono-devel");
}
try
{
// Check for ca-certificates-mono
var mono_cert_file = Path.Combine(runtimedir, "cert-sync.exe");
if (!File.Exists(mono_cert_file))
{
if ((monoVersionO.Major >= 4 && monoVersionO.Minor >= 8) || monoVersionO.Major >= 5)
{
var notice = "The ca-certificates-mono package is not installed, HTTPS trackers won't work. Please install it.";
_notices.Add(notice);
logger.Error(notice);
}
else
{
logger.Info("The ca-certificates-mono package is not installed, it will become mandatory once mono >= 4.8 is used.");
}
}
}
catch (Exception e)
{
logger.Error(e, "Error while checking for ca-certificates-mono");
}
try
{
Encoding.GetEncoding("windows-1255");
}
catch (NotSupportedException e)
{
logger.Debug(e);
logger.Error(e.Message + " Most likely the mono-locale-extras package is not installed.");
Engine.Exit(2);
}
if (Engine.WebClientType == typeof(HttpWebClient) || Engine.WebClientType == typeof(HttpWebClient2))
{
// check if the certificate store was initialized using Mono.Security.X509.X509StoreManager.TrustedRootCertificates.Count
try
{
var monoSecurity = Assembly.Load("Mono.Security");
Type monoX509StoreManager = monoSecurity.GetType("Mono.Security.X509.X509StoreManager");
if (monoX509StoreManager != null)
{
var TrustedRootCertificatesProperty = monoX509StoreManager.GetProperty("TrustedRootCertificates");
var TrustedRootCertificates = (ICollection)TrustedRootCertificatesProperty.GetValue(null);
logger.Info("TrustedRootCertificates count: " + TrustedRootCertificates.Count);
if (TrustedRootCertificates.Count == 0)
{
var CACertificatesFiles = new string[] {
"/etc/ssl/certs/ca-certificates.crt", // Debian based
"/etc/pki/tls/certs/ca-bundle.c", // RedHat based
"/etc/ssl/ca-bundle.pem", // SUSE
};
var notice = "The mono certificate store is not initialized.<br/>\n";
var logSpacer = " ";
var CACertificatesFile = CACertificatesFiles.Where(f => File.Exists(f)).FirstOrDefault();
var CommandRoot = "curl -sS https://curl.haxx.se/ca/cacert.pem | cert-sync /dev/stdin";
var CommandUser = "curl -sS https://curl.haxx.se/ca/cacert.pem | cert-sync --user /dev/stdin";
if (CACertificatesFile != null)
{
CommandRoot = "cert-sync " + CACertificatesFile;
CommandUser = "cert-sync --user " + CACertificatesFile;
}
notice += logSpacer + "Please run the following command as root:<br/>\n";
notice += logSpacer + "<pre>" + CommandRoot + "</pre><br/>\n";
notice += logSpacer + "If you don't have root access or you're running MacOS, please run the following command as the jackett user (" + Environment.UserName + "):<br/>\n";
notice += logSpacer + "<pre>" + CommandUser + "</pre>";
_notices.Add(notice);
logger.Error(Regex.Replace(notice, "<.*?>", String.Empty));
}
}
}
catch (Exception e)
{
logger.Error(e, "Error while chekcing the mono certificate store");
}
}
}
} }
catch (Exception e) catch (Exception e)
{ {
@@ -281,31 +150,6 @@ namespace Jackett.Services
public void Start() public void Start()
{ {
// Start the server
logger.Info("Starting web server at " + config.GetListenAddresses()[0]);
var startOptions = new StartOptions();
config.GetListenAddresses().ToList().ForEach(u => startOptions.Urls.Add(u));
config.RuntimeSettings.BasePath = BasePath();
try
{
_server = WebApp.Start<Startup>(startOptions);
}
catch (TargetInvocationException e)
{
var inner = e.InnerException;
if (inner is SocketException && ((SocketException)inner).SocketErrorCode == SocketError.AddressAlreadyInUse) // Linux (mono)
{
logger.Error("Address already in use: Most likely Jackett is already running.");
Engine.Exit(1);
}
else if (inner is HttpListenerException && ((HttpListenerException)inner).ErrorCode == 183) // Windows
{
logger.Error(inner.Message + " Most likely Jackett is already running.");
Engine.Exit(1);
}
throw e;
}
logger.Debug("Web server started");
updater.StartUpdateChecker(); updater.StartUpdateChecker();
} }
@@ -339,15 +183,15 @@ namespace Jackett.Services
{ {
string serverUrl = ""; string serverUrl = "";
if (obj is HttpRequestMessage request) if (obj is HttpRequest request)
{ {
var scheme = request.RequestUri.Scheme; var scheme = request.Scheme;
var port = request.RequestUri.Port; var port = request.HttpContext.Request.Host.Port;
// Check for protocol headers added by reverse proxys // Check for protocol headers added by reverse proxys
// X-Forwarded-Proto: A de facto standard for identifying the originating protocol of an HTTP request // X-Forwarded-Proto: A de facto standard for identifying the originating protocol of an HTTP request
var X_Forwarded_Proto = request.Headers.Where(x => x.Key == "X-Forwarded-Proto").Select(x => x.Value).FirstOrDefault(); var X_Forwarded_Proto = request.Headers.Where(x => x.Key == "X-Forwarded-Proto").Select(x => x.Value).FirstOrDefault();
if (X_Forwarded_Proto != null) if (X_Forwarded_Proto.Count > 0)
{ {
scheme = X_Forwarded_Proto.First(); scheme = X_Forwarded_Proto.First();
} }
@@ -357,11 +201,13 @@ namespace Jackett.Services
scheme = "https"; scheme = "https";
} }
// default to 443 if the Host header doesn't contain the port (needed for reverse proxy setups) //default to 443 if the Host header doesn't contain the port (needed for reverse proxy setups)
if (scheme == "https" && !request.RequestUri.Authority.Contains(":")) if (scheme == "https" && !request.HttpContext.Request.Host.Value.Contains(":"))
{
port = 443; port = 443;
}
serverUrl = string.Format("{0}://{1}:{2}{3}/", scheme, request.RequestUri.Host, port, BasePath()); serverUrl = string.Format("{0}://{1}:{2}{3}/", scheme, request.HttpContext.Request.Host.Host, port, BasePath());
} }
return serverUrl; return serverUrl;