Program.cs 11 KB

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