Program.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. using MediaBrowser.Model.Logging;
  2. using MediaBrowser.Server.Mono.Native;
  3. using MediaBrowser.Server.Startup.Common;
  4. using System;
  5. using System.Diagnostics;
  6. using System.Globalization;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Net.Security;
  11. using System.Reflection;
  12. using System.Text.RegularExpressions;
  13. using System.Threading.Tasks;
  14. using Emby.Server.Core.Cryptography;
  15. using Emby.Server.Core;
  16. using Emby.Server.Implementations;
  17. using Emby.Server.Implementations.EnvironmentInfo;
  18. using Emby.Server.Implementations.IO;
  19. using Emby.Server.Implementations.Logging;
  20. using Emby.Server.Implementations.Networking;
  21. using MediaBrowser.Model.IO;
  22. using MediaBrowser.Model.System;
  23. using Mono.Unix.Native;
  24. using ILogger = MediaBrowser.Model.Logging.ILogger;
  25. using X509Certificate = System.Security.Cryptography.X509Certificates.X509Certificate;
  26. namespace MediaBrowser.Server.Mono
  27. {
  28. public class MainClass
  29. {
  30. private static ApplicationHost _appHost;
  31. private static ILogger _logger;
  32. private static IFileSystem FileSystem;
  33. private static readonly TaskCompletionSource<bool> ApplicationTaskCompletionSource = new TaskCompletionSource<bool>();
  34. private static bool _restartOnShutdown;
  35. public static void Main(string[] args)
  36. {
  37. var applicationPath = Assembly.GetEntryAssembly().Location;
  38. var appFolderPath = Path.GetDirectoryName(applicationPath);
  39. SetSqliteProvider();
  40. var options = new StartupOptions(Environment.GetCommandLineArgs());
  41. // Allow this to be specified on the command line.
  42. var customProgramDataPath = options.GetOption("-programdata");
  43. var appPaths = CreateApplicationPaths(applicationPath, customProgramDataPath);
  44. var logManager = new SimpleLogManager(appPaths.LogDirectoryPath, "server");
  45. logManager.ReloadLogger(LogSeverity.Info);
  46. logManager.AddConsoleOutput();
  47. var logger = _logger = logManager.GetLogger("Main");
  48. ApplicationHost.LogEnvironmentInfo(logger, appPaths, true);
  49. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  50. try
  51. {
  52. RunApplication(appPaths, logManager, options);
  53. }
  54. finally
  55. {
  56. _logger.Info("Disposing app host");
  57. _appHost.Dispose();
  58. if (_restartOnShutdown)
  59. {
  60. StartNewInstance(options);
  61. }
  62. }
  63. }
  64. private static void SetSqliteProvider()
  65. {
  66. SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_sqlite3());
  67. }
  68. private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, string programDataPath)
  69. {
  70. if (string.IsNullOrEmpty(programDataPath))
  71. {
  72. programDataPath = ApplicationPathHelper.GetProgramDataPath(applicationPath);
  73. }
  74. var appFolderPath = Path.GetDirectoryName(applicationPath);
  75. return new ServerApplicationPaths(programDataPath, appFolderPath, Path.GetDirectoryName(applicationPath));
  76. }
  77. private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, StartupOptions options)
  78. {
  79. // Allow all https requests
  80. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
  81. var environmentInfo = GetEnvironmentInfo();
  82. var fileSystem = new MonoFileSystem(logManager.GetLogger("FileSystem"), environmentInfo, appPaths.TempDirectory);
  83. FileSystem = fileSystem;
  84. var imageEncoder = ImageEncoderHelper.GetImageEncoder(_logger, logManager, fileSystem, options, () => _appHost.HttpClient, appPaths, environmentInfo);
  85. _appHost = new MonoAppHost(appPaths,
  86. logManager,
  87. options,
  88. fileSystem,
  89. new PowerManagement(),
  90. "emby.mono.zip",
  91. environmentInfo,
  92. imageEncoder,
  93. new SystemEvents(logManager.GetLogger("SystemEvents")),
  94. new NetworkManager(logManager.GetLogger("NetworkManager")));
  95. if (options.ContainsOption("-v"))
  96. {
  97. Console.WriteLine(_appHost.ApplicationVersion.ToString());
  98. return;
  99. }
  100. Console.WriteLine("appHost.Init");
  101. var initProgress = new Progress<double>();
  102. var task = _appHost.Init(initProgress);
  103. Task.WaitAll(task);
  104. Console.WriteLine("Running startup tasks");
  105. task = _appHost.RunStartupTasks();
  106. Task.WaitAll(task);
  107. task = ApplicationTaskCompletionSource.Task;
  108. Task.WaitAll(task);
  109. }
  110. private static MonoEnvironmentInfo GetEnvironmentInfo()
  111. {
  112. var info = new MonoEnvironmentInfo();
  113. var uname = GetUnixName();
  114. var sysName = uname.sysname ?? string.Empty;
  115. if (string.Equals(sysName, "Darwin", StringComparison.OrdinalIgnoreCase))
  116. {
  117. info.OperatingSystem = Model.System.OperatingSystem.OSX;
  118. }
  119. else if (string.Equals(sysName, "Linux", StringComparison.OrdinalIgnoreCase))
  120. {
  121. info.OperatingSystem = Model.System.OperatingSystem.Linux;
  122. }
  123. else if (string.Equals(sysName, "BSD", StringComparison.OrdinalIgnoreCase))
  124. {
  125. info.OperatingSystem = Model.System.OperatingSystem.BSD;
  126. }
  127. var archX86 = new Regex("(i|I)[3-6]86");
  128. if (archX86.IsMatch(uname.machine))
  129. {
  130. info.SystemArchitecture = Architecture.X86;
  131. }
  132. else if (string.Equals(uname.machine, "x86_64", StringComparison.OrdinalIgnoreCase))
  133. {
  134. info.SystemArchitecture = Architecture.X64;
  135. }
  136. else if (uname.machine.StartsWith("arm", StringComparison.OrdinalIgnoreCase))
  137. {
  138. info.SystemArchitecture = Architecture.Arm;
  139. }
  140. else if (System.Environment.Is64BitOperatingSystem)
  141. {
  142. info.SystemArchitecture = Architecture.X64;
  143. }
  144. else
  145. {
  146. info.SystemArchitecture = 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 UnhandledException event of the CurrentDomain control.
  181. /// </summary>
  182. /// <param name="sender">The source of the event.</param>
  183. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  184. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  185. {
  186. var exception = (Exception)e.ExceptionObject;
  187. new UnhandledExceptionWriter(_appHost.ServerConfigurationManager.ApplicationPaths, _logger, _appHost.LogManager, FileSystem, new ConsoleLogger()).Log(exception);
  188. if (!Debugger.IsAttached)
  189. {
  190. var message = LogHelper.GetLogMessage(exception).ToString();
  191. if (message.IndexOf("InotifyWatcher", StringComparison.OrdinalIgnoreCase) == -1 &&
  192. message.IndexOf("_IOCompletionCallback", StringComparison.OrdinalIgnoreCase) == -1)
  193. {
  194. Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception));
  195. }
  196. }
  197. }
  198. public static void Shutdown()
  199. {
  200. ApplicationTaskCompletionSource.SetResult(true);
  201. }
  202. public static void Restart()
  203. {
  204. _restartOnShutdown = true;
  205. Shutdown();
  206. }
  207. private static void StartNewInstance(StartupOptions startupOptions)
  208. {
  209. _logger.Info("Starting new instance");
  210. string module = startupOptions.GetOption("-restartpath");
  211. string commandLineArgsString = startupOptions.GetOption("-restartargs") ?? string.Empty;
  212. if (string.IsNullOrWhiteSpace(module))
  213. {
  214. module = Environment.GetCommandLineArgs().First();
  215. }
  216. if (!startupOptions.ContainsOption("-restartargs"))
  217. {
  218. var args = Environment.GetCommandLineArgs()
  219. .Skip(1)
  220. .Select(NormalizeCommandLineArgument)
  221. .ToArray();
  222. commandLineArgsString = string.Join(" ", args);
  223. }
  224. _logger.Info("Executable: {0}", module);
  225. _logger.Info("Arguments: {0}", commandLineArgsString);
  226. Process.Start(module, commandLineArgsString);
  227. }
  228. private static string NormalizeCommandLineArgument(string arg)
  229. {
  230. if (arg.IndexOf(" ", StringComparison.OrdinalIgnoreCase) == -1)
  231. {
  232. return arg;
  233. }
  234. return "\"" + arg + "\"";
  235. }
  236. }
  237. class NoCheckCertificatePolicy : ICertificatePolicy
  238. {
  239. public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)
  240. {
  241. return true;
  242. }
  243. }
  244. public class MonoEnvironmentInfo : EnvironmentInfo
  245. {
  246. public override string GetUserId()
  247. {
  248. return Syscall.getuid().ToString(CultureInfo.InvariantCulture);
  249. }
  250. }
  251. }