Program.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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 imageEncoder = ImageEncoderHelper.GetImageEncoder(_logger, logManager, fileSystem, options, () => _appHost.HttpClient, appPaths);
  75. _appHost = new MonoAppHost(appPaths,
  76. logManager,
  77. options,
  78. fileSystem,
  79. new PowerManagement(),
  80. "emby.mono.zip",
  81. environmentInfo,
  82. imageEncoder,
  83. new Startup.Common.SystemEvents(logManager.GetLogger("SystemEvents")),
  84. new MemoryStreamProvider(),
  85. new NetworkManager(logManager.GetLogger("NetworkManager")),
  86. GenerateCertificate,
  87. () => Environment.UserDomainName);
  88. if (options.ContainsOption("-v"))
  89. {
  90. Console.WriteLine(_appHost.ApplicationVersion.ToString());
  91. return;
  92. }
  93. Console.WriteLine("appHost.Init");
  94. var initProgress = new Progress<double>();
  95. var task = _appHost.Init(initProgress);
  96. Task.WaitAll(task);
  97. Console.WriteLine("Running startup tasks");
  98. task = _appHost.RunStartupTasks();
  99. Task.WaitAll(task);
  100. task = ApplicationTaskCompletionSource.Task;
  101. Task.WaitAll(task);
  102. }
  103. private static void GenerateCertificate(string certPath, string certHost)
  104. {
  105. CertificateGenerator.CreateSelfSignCertificatePfx(certPath, certHost, _logger);
  106. }
  107. private static MonoEnvironmentInfo GetEnvironmentInfo()
  108. {
  109. var info = new MonoEnvironmentInfo();
  110. var uname = GetUnixName();
  111. var sysName = uname.sysname ?? string.Empty;
  112. if (string.Equals(sysName, "Darwin", StringComparison.OrdinalIgnoreCase))
  113. {
  114. //info.OperatingSystem = Startup.Common.OperatingSystem.Osx;
  115. }
  116. else if (string.Equals(sysName, "Linux", StringComparison.OrdinalIgnoreCase))
  117. {
  118. //info.OperatingSystem = Startup.Common.OperatingSystem.Linux;
  119. }
  120. else if (string.Equals(sysName, "BSD", StringComparison.OrdinalIgnoreCase))
  121. {
  122. //info.OperatingSystem = Startup.Common.OperatingSystem.Bsd;
  123. info.IsBsd = true;
  124. }
  125. var archX86 = new Regex("(i|I)[3-6]86");
  126. if (archX86.IsMatch(uname.machine))
  127. {
  128. info.CustomArchitecture = Architecture.X86;
  129. }
  130. else if (string.Equals(uname.machine, "x86_64", StringComparison.OrdinalIgnoreCase))
  131. {
  132. info.CustomArchitecture = Architecture.X64;
  133. }
  134. else if (uname.machine.StartsWith("arm", StringComparison.OrdinalIgnoreCase))
  135. {
  136. info.CustomArchitecture = Architecture.Arm;
  137. }
  138. else if (System.Environment.Is64BitOperatingSystem)
  139. {
  140. info.CustomArchitecture = Architecture.X64;
  141. }
  142. else
  143. {
  144. info.CustomArchitecture = Architecture.X86;
  145. }
  146. return info;
  147. }
  148. private static Uname _unixName;
  149. private static Uname GetUnixName()
  150. {
  151. if (_unixName == null)
  152. {
  153. var uname = new Uname();
  154. try
  155. {
  156. Utsname utsname;
  157. var callResult = Syscall.uname(out utsname);
  158. if (callResult == 0)
  159. {
  160. uname.sysname = utsname.sysname ?? string.Empty;
  161. uname.machine = utsname.machine ?? string.Empty;
  162. }
  163. }
  164. catch (Exception ex)
  165. {
  166. _logger.ErrorException("Error getting unix name", ex);
  167. }
  168. _unixName = uname;
  169. }
  170. return _unixName;
  171. }
  172. public class Uname
  173. {
  174. public string sysname = string.Empty;
  175. public string machine = string.Empty;
  176. }
  177. /// <summary>
  178. /// Handles the SessionEnding event of the SystemEvents control.
  179. /// </summary>
  180. /// <param name="sender">The source of the event.</param>
  181. /// <param name="e">The <see cref="SessionEndingEventArgs"/> instance containing the event data.</param>
  182. static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  183. {
  184. if (e.Reason == SessionEndReasons.SystemShutdown)
  185. {
  186. Shutdown();
  187. }
  188. }
  189. /// <summary>
  190. /// Handles the UnhandledException event of the CurrentDomain control.
  191. /// </summary>
  192. /// <param name="sender">The source of the event.</param>
  193. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  194. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  195. {
  196. var exception = (Exception)e.ExceptionObject;
  197. new UnhandledExceptionWriter(_appHost.ServerConfigurationManager.ApplicationPaths, _logger, _appHost.LogManager).Log(exception);
  198. if (!Debugger.IsAttached)
  199. {
  200. Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception));
  201. }
  202. }
  203. public static void Shutdown()
  204. {
  205. ApplicationTaskCompletionSource.SetResult(true);
  206. }
  207. public static void Restart(StartupOptions startupOptions)
  208. {
  209. _logger.Info("Disposing app host");
  210. _appHost.Dispose();
  211. _logger.Info("Starting new instance");
  212. string module = startupOptions.GetOption("-restartpath");
  213. string commandLineArgsString = startupOptions.GetOption("-restartargs") ?? string.Empty;
  214. if (string.IsNullOrWhiteSpace(module))
  215. {
  216. module = Environment.GetCommandLineArgs().First();
  217. }
  218. if (!startupOptions.ContainsOption("-restartargs"))
  219. {
  220. var args = Environment.GetCommandLineArgs()
  221. .Skip(1)
  222. .Select(NormalizeCommandLineArgument);
  223. commandLineArgsString = string.Join(" ", args.ToArray());
  224. }
  225. _logger.Info("Executable: {0}", module);
  226. _logger.Info("Arguments: {0}", commandLineArgsString);
  227. Process.Start(module, commandLineArgsString);
  228. _logger.Info("Calling Environment.Exit");
  229. Environment.Exit(0);
  230. }
  231. private static string NormalizeCommandLineArgument(string arg)
  232. {
  233. if (arg.IndexOf(" ", StringComparison.OrdinalIgnoreCase) == -1)
  234. {
  235. return arg;
  236. }
  237. return "\"" + arg + "\"";
  238. }
  239. }
  240. class NoCheckCertificatePolicy : ICertificatePolicy
  241. {
  242. public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)
  243. {
  244. return true;
  245. }
  246. }
  247. public class MonoEnvironmentInfo : EnvironmentInfo
  248. {
  249. public bool IsBsd { get; set; }
  250. }
  251. }