Run Nancy SelfHost locally only

Will run locally when URL hasn't been registered and not running in administrator context.
This commit is contained in:
Mark McDowall 2013-03-25 21:03:16 -07:00
parent 6ec700c632
commit 29ec800996
2 changed files with 107 additions and 68 deletions

View File

@ -18,6 +18,7 @@ namespace NzbDrone.Common
public class HostController : IHostController public class HostController : IHostController
{ {
private readonly ConfigFileProvider _configFileProvider; private readonly ConfigFileProvider _configFileProvider;
private readonly SecurityProvider _securityProvider;
private readonly INancyBootstrapper _bootstrapper; private readonly INancyBootstrapper _bootstrapper;
private readonly Logger _logger; private readonly Logger _logger;
private NancyHost _host; private NancyHost _host;
@ -25,18 +26,22 @@ namespace NzbDrone.Common
public bool ServerStarted { get; private set; } public bool ServerStarted { get; private set; }
public HostController(ConfigFileProvider configFileProvider, INancyBootstrapper bootstrapper, Logger logger) public HostController(ConfigFileProvider configFileProvider, SecurityProvider securityProvider, INancyBootstrapper bootstrapper, Logger logger)
{ {
_configFileProvider = configFileProvider; _configFileProvider = configFileProvider;
_securityProvider = securityProvider;
_bootstrapper = bootstrapper; _bootstrapper = bootstrapper;
_logger = logger; _logger = logger;
} }
public void StartServer() public void StartServer()
{ {
//Todo: We need this to be able run when the user isn't an admin if (_securityProvider.IsNzbDroneUrlRegistered())
//Todo: And when the URL hasn't been registered in URL ACL: netsh http add urlacl url=http://+:8989/ user=everyone _host = new NancyHost(new Uri(AppUrl), _bootstrapper);
_host = new NancyHost(new Uri(AppUrl), _bootstrapper);
else
_host = new NancyHost(new Uri(AppUrl), _bootstrapper, new HostConfiguration { RewriteLocalhost = false });
_host.Start(); _host.Start();
} }
@ -45,7 +50,6 @@ namespace NzbDrone.Common
get { return string.Format("http://localhost:{0}", _configFileProvider.Port); } get { return string.Format("http://localhost:{0}", _configFileProvider.Port); }
} }
public void RestartServer() public void RestartServer()
{ {

View File

@ -10,38 +10,45 @@ using NetFwTypeLib;
namespace NzbDrone.Common namespace NzbDrone.Common
{ {
public class SecurityProvider public interface ISecurityProvider
{ {
private static readonly Logger Logger = LogManager.GetCurrentClassLogger (); void MakeAccessible();
bool IsCurrentUserAdmin();
bool IsNzbDronePortOpen();
bool IsNzbDroneUrlRegistered();
}
public class SecurityProvider : ISecurityProvider
{
private readonly ConfigFileProvider _configFileProvider; private readonly ConfigFileProvider _configFileProvider;
private readonly EnvironmentProvider _environmentProvider; private readonly EnvironmentProvider _environmentProvider;
private readonly ProcessProvider _processProvider; private readonly ProcessProvider _processProvider;
private readonly Logger _logger;
public SecurityProvider (ConfigFileProvider configFileProvider, EnvironmentProvider environmentProvider, public SecurityProvider(ConfigFileProvider configFileProvider, EnvironmentProvider environmentProvider,
ProcessProvider processProvider) ProcessProvider processProvider, Logger logger)
{ {
_configFileProvider = configFileProvider; _configFileProvider = configFileProvider;
_environmentProvider = environmentProvider; _environmentProvider = environmentProvider;
_processProvider = processProvider; _processProvider = processProvider;
_logger = logger;
} }
public SecurityProvider () public void MakeAccessible()
{ {
} if (!IsCurrentUserAdmin ())
{
public virtual void MakeAccessible () _logger.Trace ("User is not an admin, skipping.");
{
if (!IsCurrentUserAdmin ()) {
Logger.Trace ("User is not an admin, skipping.");
return; return;
} }
int port = 0; int port = 0;
if (IsFirewallEnabled ()) { if (IsFirewallEnabled ())
if (IsNzbDronePortOpen ()) { {
Logger.Trace ("NzbDrone port is already open, skipping."); if (IsNzbDronePortOpen ())
{
_logger.Trace ("NzbDrone port is already open, skipping.");
return; return;
} }
@ -58,24 +65,24 @@ namespace NzbDrone.Common
//Unregister Url (if port != 0) //Unregister Url (if port != 0)
if (port != 0) if (port != 0)
UnregisterUrl (port); UnregisterUrl(port);
//Register Url //Register Url
RegisterUrl (_configFileProvider.Port); RegisterUrl(_configFileProvider.Port);
} }
public virtual bool IsCurrentUserAdmin () public bool IsCurrentUserAdmin()
{ {
try { try {
var principal = new WindowsPrincipal (WindowsIdentity.GetCurrent ()); var principal = new WindowsPrincipal (WindowsIdentity.GetCurrent ());
return principal.IsInRole (WindowsBuiltInRole.Administrator); return principal.IsInRole (WindowsBuiltInRole.Administrator);
} catch (Exception ex) { } catch (Exception ex) {
Logger.WarnException ("Error checking if the current user is an administrator.", ex); _logger.WarnException ("Error checking if the current user is an administrator.", ex);
return false; return false;
} }
} }
public virtual bool IsNzbDronePortOpen () public bool IsNzbDronePortOpen()
{ {
#if __MonoCS__ #if __MonoCS__
#else #else
@ -83,7 +90,6 @@ namespace NzbDrone.Common
try { try {
var netFwMgrType = Type.GetTypeFromProgID ("HNetCfg.FwMgr", false); var netFwMgrType = Type.GetTypeFromProgID ("HNetCfg.FwMgr", false);
var mgr = (INetFwMgr)Activator.CreateInstance (netFwMgrType); var mgr = (INetFwMgr)Activator.CreateInstance (netFwMgrType);
if (!mgr.LocalPolicy.CurrentProfile.FirewallEnabled) if (!mgr.LocalPolicy.CurrentProfile.FirewallEnabled)
@ -95,14 +101,20 @@ namespace NzbDrone.Common
if (p.Port == _configFileProvider.Port) if (p.Port == _configFileProvider.Port)
return true; return true;
} }
} catch (Exception ex) { }
Logger.WarnException ("Failed to check for open port in firewall", ex); catch (Exception ex) {
_logger.WarnException ("Failed to check for open port in firewall", ex);
} }
#endif #endif
return false; return false;
} }
private bool OpenFirewallPort (int portNumber) public bool IsNzbDroneUrlRegistered()
{
return CheckIfUrlIsRegisteredUrl(_configFileProvider.Port);
}
private void OpenFirewallPort(int portNumber)
{ {
#if __MonoCS__ #if __MonoCS__
return true; return true;
@ -121,15 +133,14 @@ namespace NzbDrone.Common
var ports = mgr.LocalPolicy.CurrentProfile.GloballyOpenPorts; var ports = mgr.LocalPolicy.CurrentProfile.GloballyOpenPorts;
ports.Add (port); ports.Add (port);
return true; }
} catch (Exception ex) { catch (Exception ex) {
Logger.WarnException ("Failed to open port in firewall for NzbDrone " + portNumber, ex); _logger.WarnException ("Failed to open port in firewall for NzbDrone " + portNumber, ex);
return false;
} }
#endif #endif
} }
private int CloseFirewallPort () private int CloseFirewallPort()
{ {
#if __MonoCS__ #if __MonoCS__
@ -149,18 +160,21 @@ namespace NzbDrone.Common
} }
} }
if (portNumber != _configFileProvider.Port) { if (portNumber != _configFileProvider.Port)
{
ports.Remove (portNumber, NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP); ports.Remove (portNumber, NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP);
return portNumber; return portNumber;
} }
} catch (Exception ex) { }
Logger.WarnException ("Failed to close port in firewall for NzbDrone", ex); catch (Exception ex)
{
_logger.WarnException ("Failed to close port in firewall for NzbDrone", ex);
} }
#endif #endif
return 0; return 0;
} }
private bool IsFirewallEnabled () private bool IsFirewallEnabled()
{ {
#if __MonoCS__ #if __MonoCS__
return true; return true;
@ -170,49 +184,70 @@ namespace NzbDrone.Common
var netFwMgrType = Type.GetTypeFromProgID ("HNetCfg.FwMgr", false); var netFwMgrType = Type.GetTypeFromProgID ("HNetCfg.FwMgr", false);
var mgr = (INetFwMgr)Activator.CreateInstance (netFwMgrType); var mgr = (INetFwMgr)Activator.CreateInstance (netFwMgrType);
return mgr.LocalPolicy.CurrentProfile.FirewallEnabled; return mgr.LocalPolicy.CurrentProfile.FirewallEnabled;
} catch (Exception ex) { }
Logger.WarnException ("Failed to check if the firewall is enabled", ex); catch (Exception ex)
{
_logger.WarnException ("Failed to check if the firewall is enabled", ex);
return false; return false;
} }
#endif #endif
} }
private bool RegisterUrl (int portNumber) private void RegisterUrl(int portNumber)
{ {
try { var arguments = String.Format("http add urlacl http://+:{0}/ user=EVERYONE", portNumber);
var startInfo = new ProcessStartInfo () RunNetsh(arguments);
{
FileName = "netsh.exe",
Arguments = string.Format("http add urlacl http://*:{0}/ user=EVERYONE", portNumber)
};
var process = _processProvider.Start (startInfo);
process.WaitForExit (5000);
return true;
} catch (Exception ex) {
Logger.WarnException ("Error registering URL", ex);
}
return false;
} }
private bool UnregisterUrl (int portNumber) private void UnregisterUrl(int portNumber)
{ {
try { var arguments = String.Format("http delete urlacl http://+:{0}/", portNumber);
var startInfo = new ProcessStartInfo () RunNetsh(arguments);
}
private bool CheckIfUrlIsRegisteredUrl(int portNumber)
{
var url = String.Format("http://+:{0}/", portNumber);
var arguments = String.Format("http show urlacl url=\"{0}\"", url);
var output = RunNetsh(arguments);
if(String.IsNullOrWhiteSpace(output))
{
_logger.Error("netsh output is invalid for arguments: {0}", arguments);
}
if(!output.Contains(url))
{
_logger.Trace("Url has not already been registered");
return false;
}
_logger.Trace("Url has already been registered!");
return true;
}
private string RunNetsh(string arguments)
{
try
{
var startInfo = new ProcessStartInfo()
{ {
RedirectStandardOutput = true,
UseShellExecute = false,
FileName = "netsh.exe", FileName = "netsh.exe",
Arguments = string.Format("http delete urlacl http://*:{0}/", portNumber) Arguments = arguments
}; };
var process = _processProvider.Start (startInfo); var process = _processProvider.Start(startInfo);
process.WaitForExit (5000); process.WaitForExit(5000);
return true; return process.StandardOutput.ReadToEnd();
} catch (Exception ex) { }
Logger.WarnException ("Error registering URL", ex); catch (Exception ex)
} {
_logger.WarnException("Error executing netsh with arguments: " + arguments, ex);
}
return false; return null;
} }
} }
} }