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