2
0

Program.cs 11 KB

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