Program.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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. using (var logManager = new SimpleLogManager(appPaths.LogDirectoryPath, "server"))
  45. {
  46. logManager.ReloadLogger(LogSeverity.Info);
  47. logManager.AddConsoleOutput();
  48. var logger = _logger = logManager.GetLogger("Main");
  49. ApplicationHost.LogEnvironmentInfo(logger, appPaths, true);
  50. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  51. try
  52. {
  53. RunApplication(appPaths, logManager, options);
  54. }
  55. finally
  56. {
  57. _logger.Info("Disposing app host");
  58. _appHost.Dispose();
  59. if (_restartOnShutdown)
  60. {
  61. StartNewInstance(options);
  62. }
  63. }
  64. }
  65. }
  66. private static void SetSqliteProvider()
  67. {
  68. SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_sqlite3());
  69. }
  70. private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, string programDataPath)
  71. {
  72. if (string.IsNullOrEmpty(programDataPath))
  73. {
  74. programDataPath = ApplicationPathHelper.GetProgramDataPath(applicationPath);
  75. }
  76. var appFolderPath = Path.GetDirectoryName(applicationPath);
  77. return new ServerApplicationPaths(programDataPath, appFolderPath, Path.GetDirectoryName(applicationPath));
  78. }
  79. private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, StartupOptions options)
  80. {
  81. // Allow all https requests
  82. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
  83. var environmentInfo = GetEnvironmentInfo();
  84. var fileSystem = new MonoFileSystem(logManager.GetLogger("FileSystem"), environmentInfo, appPaths.TempDirectory);
  85. FileSystem = fileSystem;
  86. var imageEncoder = ImageEncoderHelper.GetImageEncoder(_logger, logManager, fileSystem, options, () => _appHost.HttpClient, appPaths, environmentInfo);
  87. _appHost = new MonoAppHost(appPaths,
  88. logManager,
  89. options,
  90. fileSystem,
  91. new PowerManagement(),
  92. "emby.mono.zip",
  93. environmentInfo,
  94. imageEncoder,
  95. new SystemEvents(logManager.GetLogger("SystemEvents")),
  96. new NetworkManager(logManager.GetLogger("NetworkManager")));
  97. if (options.ContainsOption("-v"))
  98. {
  99. Console.WriteLine(_appHost.ApplicationVersion.ToString());
  100. return;
  101. }
  102. Console.WriteLine("appHost.Init");
  103. var initProgress = new Progress<double>();
  104. var task = _appHost.Init(initProgress);
  105. Task.WaitAll(task);
  106. Console.WriteLine("Running startup tasks");
  107. task = _appHost.RunStartupTasks();
  108. Task.WaitAll(task);
  109. task = ApplicationTaskCompletionSource.Task;
  110. Task.WaitAll(task);
  111. }
  112. private static MonoEnvironmentInfo GetEnvironmentInfo()
  113. {
  114. var info = new MonoEnvironmentInfo();
  115. var uname = GetUnixName();
  116. var sysName = uname.sysname ?? string.Empty;
  117. if (string.Equals(sysName, "Darwin", StringComparison.OrdinalIgnoreCase))
  118. {
  119. info.OperatingSystem = Model.System.OperatingSystem.OSX;
  120. }
  121. else if (string.Equals(sysName, "Linux", StringComparison.OrdinalIgnoreCase))
  122. {
  123. info.OperatingSystem = Model.System.OperatingSystem.Linux;
  124. }
  125. else if (string.Equals(sysName, "BSD", StringComparison.OrdinalIgnoreCase))
  126. {
  127. info.OperatingSystem = Model.System.OperatingSystem.BSD;
  128. }
  129. var archX86 = new Regex("(i|I)[3-6]86");
  130. if (archX86.IsMatch(uname.machine))
  131. {
  132. info.SystemArchitecture = Architecture.X86;
  133. }
  134. else if (string.Equals(uname.machine, "x86_64", StringComparison.OrdinalIgnoreCase))
  135. {
  136. info.SystemArchitecture = Architecture.X64;
  137. }
  138. else if (uname.machine.StartsWith("arm", StringComparison.OrdinalIgnoreCase))
  139. {
  140. info.SystemArchitecture = Architecture.Arm;
  141. }
  142. else if (System.Environment.Is64BitOperatingSystem)
  143. {
  144. info.SystemArchitecture = Architecture.X64;
  145. }
  146. else
  147. {
  148. info.SystemArchitecture = Architecture.X86;
  149. }
  150. return info;
  151. }
  152. private static Uname _unixName;
  153. private static Uname GetUnixName()
  154. {
  155. if (_unixName == null)
  156. {
  157. var uname = new Uname();
  158. try
  159. {
  160. Utsname utsname;
  161. var callResult = Syscall.uname(out utsname);
  162. if (callResult == 0)
  163. {
  164. uname.sysname = utsname.sysname ?? string.Empty;
  165. uname.machine = utsname.machine ?? string.Empty;
  166. }
  167. }
  168. catch (Exception ex)
  169. {
  170. _logger.ErrorException("Error getting unix name", ex);
  171. }
  172. _unixName = uname;
  173. }
  174. return _unixName;
  175. }
  176. public class Uname
  177. {
  178. public string sysname = string.Empty;
  179. public string machine = string.Empty;
  180. }
  181. /// <summary>
  182. /// Handles the UnhandledException event of the CurrentDomain control.
  183. /// </summary>
  184. /// <param name="sender">The source of the event.</param>
  185. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  186. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  187. {
  188. var exception = (Exception)e.ExceptionObject;
  189. new UnhandledExceptionWriter(_appHost.ServerConfigurationManager.ApplicationPaths, _logger, _appHost.LogManager, FileSystem, new ConsoleLogger()).Log(exception);
  190. if (!Debugger.IsAttached)
  191. {
  192. var message = LogHelper.GetLogMessage(exception).ToString();
  193. if (message.IndexOf("InotifyWatcher", StringComparison.OrdinalIgnoreCase) == -1 &&
  194. message.IndexOf("_IOCompletionCallback", StringComparison.OrdinalIgnoreCase) == -1)
  195. {
  196. Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception));
  197. }
  198. }
  199. }
  200. public static void Shutdown()
  201. {
  202. ApplicationTaskCompletionSource.SetResult(true);
  203. }
  204. public static void Restart()
  205. {
  206. _restartOnShutdown = true;
  207. Shutdown();
  208. }
  209. private static void StartNewInstance(StartupOptions startupOptions)
  210. {
  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. .ToArray();
  224. commandLineArgsString = string.Join(" ", args);
  225. }
  226. _logger.Info("Executable: {0}", module);
  227. _logger.Info("Arguments: {0}", commandLineArgsString);
  228. Process.Start(module, commandLineArgsString);
  229. }
  230. private static string NormalizeCommandLineArgument(string arg)
  231. {
  232. if (arg.IndexOf(" ", StringComparison.OrdinalIgnoreCase) == -1)
  233. {
  234. return arg;
  235. }
  236. return "\"" + arg + "\"";
  237. }
  238. }
  239. class NoCheckCertificatePolicy : ICertificatePolicy
  240. {
  241. public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)
  242. {
  243. return true;
  244. }
  245. }
  246. public class MonoEnvironmentInfo : EnvironmentInfo
  247. {
  248. public override string GetUserId()
  249. {
  250. return Syscall.getuid().ToString(CultureInfo.InvariantCulture);
  251. }
  252. }
  253. }