2
0

Program.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. using MediaBrowser.Model.Logging;
  2. using MediaBrowser.Server.Implementations;
  3. using MediaBrowser.Server.Mono.Native;
  4. using MediaBrowser.Server.Startup.Common;
  5. using Microsoft.Win32;
  6. using System;
  7. using System.Diagnostics;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Net;
  11. using System.Net.Security;
  12. using System.Reflection;
  13. using System.Security.Cryptography.X509Certificates;
  14. using System.Text.RegularExpressions;
  15. using System.Threading.Tasks;
  16. using Emby.Common.Implementations.EnvironmentInfo;
  17. using Emby.Common.Implementations.IO;
  18. using Emby.Common.Implementations.Logging;
  19. using Emby.Server.Core;
  20. using Emby.Server.Implementations.IO;
  21. using MediaBrowser.Model.System;
  22. using Mono.Unix.Native;
  23. using NLog;
  24. using ILogger = MediaBrowser.Model.Logging.ILogger;
  25. namespace MediaBrowser.Server.Mono
  26. {
  27. public class MainClass
  28. {
  29. private static ApplicationHost _appHost;
  30. private static ILogger _logger;
  31. public static void Main(string[] args)
  32. {
  33. var applicationPath = Assembly.GetEntryAssembly().Location;
  34. var options = new StartupOptions();
  35. // Allow this to be specified on the command line.
  36. var customProgramDataPath = options.GetOption("-programdata");
  37. var appPaths = CreateApplicationPaths(applicationPath, customProgramDataPath);
  38. var logManager = new NlogManager(appPaths.LogDirectoryPath, "server");
  39. logManager.ReloadLogger(LogSeverity.Info);
  40. logManager.AddConsoleOutput();
  41. var logger = _logger = logManager.GetLogger("Main");
  42. ApplicationHost.LogEnvironmentInfo(logger, appPaths, true);
  43. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  44. try
  45. {
  46. RunApplication(appPaths, logManager, options);
  47. }
  48. finally
  49. {
  50. logger.Info("Shutting down");
  51. _appHost.Dispose();
  52. }
  53. }
  54. private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, string programDataPath)
  55. {
  56. if (string.IsNullOrEmpty(programDataPath))
  57. {
  58. programDataPath = ApplicationPathHelper.GetProgramDataPath(applicationPath);
  59. }
  60. return new ServerApplicationPaths(programDataPath, applicationPath, Path.GetDirectoryName(applicationPath));
  61. }
  62. private static readonly TaskCompletionSource<bool> ApplicationTaskCompletionSource = new TaskCompletionSource<bool>();
  63. private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, StartupOptions options)
  64. {
  65. Microsoft.Win32.SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  66. // Allow all https requests
  67. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
  68. var fileSystem = new MonoFileSystem(logManager.GetLogger("FileSystem"), false, false);
  69. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  70. var environmentInfo = GetEnvironmentInfo();
  71. var nativeApp = new MonoApp(options, logManager.GetLogger("App"), environmentInfo);
  72. _appHost = new ApplicationHost(appPaths, logManager, options, fileSystem, nativeApp, new PowerManagement(), "emby.mono.zip", environmentInfo);
  73. if (options.ContainsOption("-v"))
  74. {
  75. Console.WriteLine(_appHost.ApplicationVersion.ToString());
  76. return;
  77. }
  78. Console.WriteLine("appHost.Init");
  79. var initProgress = new Progress<double>();
  80. var task = _appHost.Init(initProgress);
  81. Task.WaitAll(task);
  82. Console.WriteLine("Running startup tasks");
  83. task = _appHost.RunStartupTasks();
  84. Task.WaitAll(task);
  85. task = ApplicationTaskCompletionSource.Task;
  86. Task.WaitAll(task);
  87. }
  88. private static MonoEnvironmentInfo GetEnvironmentInfo()
  89. {
  90. var info = new MonoEnvironmentInfo();
  91. var uname = GetUnixName();
  92. var sysName = uname.sysname ?? string.Empty;
  93. if (string.Equals(sysName, "Darwin", StringComparison.OrdinalIgnoreCase))
  94. {
  95. //info.OperatingSystem = Startup.Common.OperatingSystem.Osx;
  96. }
  97. else if (string.Equals(sysName, "Linux", StringComparison.OrdinalIgnoreCase))
  98. {
  99. //info.OperatingSystem = Startup.Common.OperatingSystem.Linux;
  100. }
  101. else if (string.Equals(sysName, "BSD", StringComparison.OrdinalIgnoreCase))
  102. {
  103. //info.OperatingSystem = Startup.Common.OperatingSystem.Bsd;
  104. info.IsBsd = true;
  105. }
  106. var archX86 = new Regex("(i|I)[3-6]86");
  107. if (archX86.IsMatch(uname.machine))
  108. {
  109. info.CustomArchitecture = Architecture.X86;
  110. }
  111. else if (string.Equals(uname.machine, "x86_64", StringComparison.OrdinalIgnoreCase))
  112. {
  113. info.CustomArchitecture = Architecture.X64;
  114. }
  115. else if (uname.machine.StartsWith("arm", StringComparison.OrdinalIgnoreCase))
  116. {
  117. info.CustomArchitecture = Architecture.Arm;
  118. }
  119. else if (System.Environment.Is64BitOperatingSystem)
  120. {
  121. info.CustomArchitecture = Architecture.X64;
  122. }
  123. else
  124. {
  125. info.CustomArchitecture = Architecture.X86;
  126. }
  127. return info;
  128. }
  129. private static Uname _unixName;
  130. private static Uname GetUnixName()
  131. {
  132. if (_unixName == null)
  133. {
  134. var uname = new Uname();
  135. try
  136. {
  137. Utsname utsname;
  138. var callResult = Syscall.uname(out utsname);
  139. if (callResult == 0)
  140. {
  141. uname.sysname = utsname.sysname ?? string.Empty;
  142. uname.machine = utsname.machine ?? string.Empty;
  143. }
  144. }
  145. catch (Exception ex)
  146. {
  147. _logger.ErrorException("Error getting unix name", ex);
  148. }
  149. _unixName = uname;
  150. }
  151. return _unixName;
  152. }
  153. public class Uname
  154. {
  155. public string sysname = string.Empty;
  156. public string machine = string.Empty;
  157. }
  158. /// <summary>
  159. /// Handles the SessionEnding event of the SystemEvents control.
  160. /// </summary>
  161. /// <param name="sender">The source of the event.</param>
  162. /// <param name="e">The <see cref="SessionEndingEventArgs"/> instance containing the event data.</param>
  163. static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  164. {
  165. if (e.Reason == SessionEndReasons.SystemShutdown)
  166. {
  167. Shutdown();
  168. }
  169. }
  170. /// <summary>
  171. /// Handles the UnhandledException event of the CurrentDomain control.
  172. /// </summary>
  173. /// <param name="sender">The source of the event.</param>
  174. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  175. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  176. {
  177. var exception = (Exception)e.ExceptionObject;
  178. new UnhandledExceptionWriter(_appHost.ServerConfigurationManager.ApplicationPaths, _logger, _appHost.LogManager).Log(exception);
  179. if (!Debugger.IsAttached)
  180. {
  181. Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception));
  182. }
  183. }
  184. public static void Shutdown()
  185. {
  186. ApplicationTaskCompletionSource.SetResult(true);
  187. }
  188. public static void Restart(StartupOptions startupOptions)
  189. {
  190. _logger.Info("Disposing app host");
  191. _appHost.Dispose();
  192. _logger.Info("Starting new instance");
  193. string module = startupOptions.GetOption("-restartpath");
  194. string commandLineArgsString = startupOptions.GetOption("-restartargs") ?? string.Empty;
  195. if (string.IsNullOrWhiteSpace(module))
  196. {
  197. module = Environment.GetCommandLineArgs().First();
  198. }
  199. if (!startupOptions.ContainsOption("-restartargs"))
  200. {
  201. var args = Environment.GetCommandLineArgs()
  202. .Skip(1)
  203. .Select(NormalizeCommandLineArgument);
  204. commandLineArgsString = string.Join(" ", args.ToArray());
  205. }
  206. _logger.Info("Executable: {0}", module);
  207. _logger.Info("Arguments: {0}", commandLineArgsString);
  208. Process.Start(module, commandLineArgsString);
  209. _logger.Info("Calling Environment.Exit");
  210. Environment.Exit(0);
  211. }
  212. private static string NormalizeCommandLineArgument(string arg)
  213. {
  214. if (arg.IndexOf(" ", StringComparison.OrdinalIgnoreCase) == -1)
  215. {
  216. return arg;
  217. }
  218. return "\"" + arg + "\"";
  219. }
  220. }
  221. class NoCheckCertificatePolicy : ICertificatePolicy
  222. {
  223. public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)
  224. {
  225. return true;
  226. }
  227. }
  228. public class MonoEnvironmentInfo : EnvironmentInfo
  229. {
  230. public bool IsBsd { get; set; }
  231. }
  232. }