2
0

Program.cs 11 KB

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