LinuxIsoManager.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. using System;
  2. using System.IO;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using MediaBrowser.Model.Diagnostics;
  6. using MediaBrowser.Model.IO;
  7. using Microsoft.Extensions.Logging;
  8. using MediaBrowser.Model.System;
  9. using System.Runtime.InteropServices;
  10. namespace IsoMounter
  11. {
  12. public class LinuxIsoManager : IIsoMounter
  13. {
  14. [DllImport("libc", SetLastError = true)]
  15. public static extern uint getuid();
  16. #region Private Fields
  17. private readonly IEnvironmentInfo EnvironmentInfo;
  18. private readonly bool ExecutablesAvailable;
  19. private readonly IFileSystem FileSystem;
  20. private readonly ILogger _logger;
  21. private readonly string MountCommand;
  22. private readonly string MountPointRoot;
  23. private readonly IProcessFactory ProcessFactory;
  24. private readonly string SudoCommand;
  25. private readonly string UmountCommand;
  26. #endregion
  27. #region Constructor(s)
  28. public LinuxIsoManager(ILogger logger, IFileSystem fileSystem, IEnvironmentInfo environment, IProcessFactory processFactory)
  29. {
  30. EnvironmentInfo = environment;
  31. FileSystem = fileSystem;
  32. _logger = logger;
  33. ProcessFactory = processFactory;
  34. MountPointRoot = FileSystem.DirectorySeparatorChar + "tmp" + FileSystem.DirectorySeparatorChar + "Emby";
  35. _logger.LogDebug(
  36. "[{0}] System PATH is currently set to [{1}].",
  37. Name,
  38. EnvironmentInfo.GetEnvironmentVariable("PATH") ?? ""
  39. );
  40. _logger.LogDebug(
  41. "[{0}] System path separator is [{1}].",
  42. Name,
  43. EnvironmentInfo.PathSeparator
  44. );
  45. _logger.LogDebug(
  46. "[{0}] Mount point root is [{1}].",
  47. Name,
  48. MountPointRoot
  49. );
  50. //
  51. // Get the location of the executables we need to support mounting/unmounting ISO images.
  52. //
  53. SudoCommand = GetFullPathForExecutable("sudo");
  54. _logger.LogInformation(
  55. "[{0}] Using version of [sudo] located at [{1}].",
  56. Name,
  57. SudoCommand
  58. );
  59. MountCommand = GetFullPathForExecutable("mount");
  60. _logger.LogInformation(
  61. "[{0}] Using version of [mount] located at [{1}].",
  62. Name,
  63. MountCommand
  64. );
  65. UmountCommand = GetFullPathForExecutable("umount");
  66. _logger.LogInformation(
  67. "[{0}] Using version of [umount] located at [{1}].",
  68. Name,
  69. UmountCommand
  70. );
  71. if (!String.IsNullOrEmpty(SudoCommand) && !String.IsNullOrEmpty(MountCommand) && !String.IsNullOrEmpty(UmountCommand)) {
  72. ExecutablesAvailable = true;
  73. } else {
  74. ExecutablesAvailable = false;
  75. }
  76. }
  77. #endregion
  78. #region Interface Implementation for IIsoMounter
  79. public bool IsInstalled {
  80. get {
  81. return true;
  82. }
  83. }
  84. public string Name {
  85. get { return "LinuxMount"; }
  86. }
  87. public bool RequiresInstallation {
  88. get {
  89. return false;
  90. }
  91. }
  92. public bool CanMount(string path)
  93. {
  94. if (EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Linux) {
  95. _logger.LogInformation(
  96. "[{0}] Checking we can attempt to mount [{1}], Extension = [{2}], Operating System = [{3}], Executables Available = [{4}].",
  97. Name,
  98. path,
  99. Path.GetExtension(path),
  100. EnvironmentInfo.OperatingSystem,
  101. ExecutablesAvailable.ToString()
  102. );
  103. if (ExecutablesAvailable) {
  104. return string.Equals(Path.GetExtension(path), ".iso", StringComparison.OrdinalIgnoreCase);
  105. } else {
  106. return false;
  107. }
  108. } else {
  109. return false;
  110. }
  111. }
  112. public Task Install(CancellationToken cancellationToken)
  113. {
  114. return Task.FromResult(false);
  115. }
  116. public Task<IIsoMount> Mount(string isoPath, CancellationToken cancellationToken)
  117. {
  118. if (MountISO(isoPath, out LinuxMount mountedISO)) {
  119. return Task.FromResult<IIsoMount>(mountedISO);
  120. }
  121. else {
  122. throw new IOException(String.Format(
  123. "An error occurred trying to mount image [$0].",
  124. isoPath
  125. ));
  126. }
  127. }
  128. #endregion
  129. #region Interface Implementation for IDisposable
  130. // Flag: Has Dispose already been called?
  131. private bool disposed = false;
  132. public void Dispose()
  133. {
  134. // Dispose of unmanaged resources.
  135. Dispose(true);
  136. // Suppress finalization.
  137. GC.SuppressFinalize(this);
  138. }
  139. protected virtual void Dispose(bool disposing)
  140. {
  141. if (disposed) {
  142. return;
  143. }
  144. _logger.LogInformation(
  145. "[{0}] Disposing [{1}].",
  146. Name,
  147. disposing.ToString()
  148. );
  149. if (disposing) {
  150. //
  151. // Free managed objects here.
  152. //
  153. }
  154. //
  155. // Free any unmanaged objects here.
  156. //
  157. disposed = true;
  158. }
  159. #endregion
  160. #region Private Methods
  161. private string GetFullPathForExecutable(string name)
  162. {
  163. foreach (string test in (EnvironmentInfo.GetEnvironmentVariable("PATH") ?? "").Split(EnvironmentInfo.PathSeparator)) {
  164. string path = test.Trim();
  165. if (!String.IsNullOrEmpty(path) && FileSystem.FileExists(path = Path.Combine(path, name))) {
  166. return FileSystem.GetFullPath(path);
  167. }
  168. }
  169. return String.Empty;
  170. }
  171. private uint GetUID()
  172. {
  173. var uid = getuid();
  174. _logger.LogDebug(
  175. "[{0}] Our current UID is [{1}], GetUserId() returned [{2}].",
  176. Name,
  177. uid.ToString(),
  178. uid
  179. );
  180. return uid;
  181. }
  182. private bool ExecuteCommand(string cmdFilename, string cmdArguments)
  183. {
  184. bool processFailed = false;
  185. var process = ProcessFactory.Create(
  186. new ProcessOptions {
  187. CreateNoWindow = true,
  188. RedirectStandardOutput = true,
  189. RedirectStandardError = true,
  190. UseShellExecute = false,
  191. FileName = cmdFilename,
  192. Arguments = cmdArguments,
  193. IsHidden = true,
  194. ErrorDialog = false,
  195. EnableRaisingEvents = true
  196. }
  197. );
  198. try
  199. {
  200. process.Start();
  201. //StreamReader outputReader = process.StandardOutput.;
  202. //StreamReader errorReader = process.StandardError;
  203. _logger.LogDebug(
  204. "[{Name}] Standard output from process is [{Error}].",
  205. Name,
  206. process.StandardOutput.ReadToEnd()
  207. );
  208. _logger.LogDebug(
  209. "[{Name}] Standard error from process is [{Error}].",
  210. Name,
  211. process.StandardError.ReadToEnd()
  212. );
  213. }
  214. catch (Exception ex)
  215. {
  216. processFailed = true;
  217. _logger.LogDebug(ex, "[{Name}] Unhandled exception executing command.", Name);
  218. }
  219. if (!processFailed && process.ExitCode == 0) {
  220. return true;
  221. } else {
  222. return false;
  223. }
  224. }
  225. private bool MountISO(string isoPath, out LinuxMount mountedISO)
  226. {
  227. string cmdArguments;
  228. string cmdFilename;
  229. string mountPoint = Path.Combine(MountPointRoot, Guid.NewGuid().ToString());
  230. if (!string.IsNullOrEmpty(isoPath)) {
  231. _logger.LogInformation(
  232. "[{Name}] Attempting to mount [{Path}].",
  233. Name,
  234. isoPath
  235. );
  236. _logger.LogDebug(
  237. "[{Name}] ISO will be mounted at [{Path}].",
  238. Name,
  239. mountPoint
  240. );
  241. } else {
  242. throw new ArgumentNullException(nameof(isoPath));
  243. }
  244. try
  245. {
  246. FileSystem.CreateDirectory(mountPoint);
  247. }
  248. catch (UnauthorizedAccessException)
  249. {
  250. throw new IOException("Unable to create mount point(Permission denied) for " + isoPath);
  251. }
  252. catch (Exception)
  253. {
  254. throw new IOException("Unable to create mount point for " + isoPath);
  255. }
  256. if (GetUID() == 0) {
  257. cmdFilename = MountCommand;
  258. cmdArguments = string.Format("\"{0}\" \"{1}\"", isoPath, mountPoint);
  259. } else {
  260. cmdFilename = SudoCommand;
  261. cmdArguments = string.Format("\"{0}\" \"{1}\" \"{2}\"", MountCommand, isoPath, mountPoint);
  262. }
  263. _logger.LogDebug(
  264. "[{0}] Mount command [{1}], mount arguments [{2}].",
  265. Name,
  266. cmdFilename,
  267. cmdArguments
  268. );
  269. if (ExecuteCommand(cmdFilename, cmdArguments)) {
  270. _logger.LogInformation(
  271. "[{0}] ISO mount completed successfully.",
  272. Name
  273. );
  274. mountedISO = new LinuxMount(this, isoPath, mountPoint);
  275. } else {
  276. _logger.LogInformation(
  277. "[{0}] ISO mount completed with errors.",
  278. Name
  279. );
  280. try
  281. {
  282. FileSystem.DeleteDirectory(mountPoint, false);
  283. }
  284. catch (Exception ex)
  285. {
  286. _logger.LogInformation(ex, "[{Name}] Unhandled exception removing mount point.", Name);
  287. }
  288. mountedISO = null;
  289. }
  290. return mountedISO != null;
  291. }
  292. private void UnmountISO(LinuxMount mount)
  293. {
  294. string cmdArguments;
  295. string cmdFilename;
  296. if (mount != null) {
  297. _logger.LogInformation(
  298. "[{0}] Attempting to unmount ISO [{1}] mounted on [{2}].",
  299. Name,
  300. mount.IsoPath,
  301. mount.MountedPath
  302. );
  303. } else {
  304. throw new ArgumentNullException(nameof(mount));
  305. }
  306. if (GetUID() == 0) {
  307. cmdFilename = UmountCommand;
  308. cmdArguments = string.Format("\"{0}\"", mount.MountedPath);
  309. } else {
  310. cmdFilename = SudoCommand;
  311. cmdArguments = string.Format("\"{0}\" \"{1}\"", UmountCommand, mount.MountedPath);
  312. }
  313. _logger.LogDebug(
  314. "[{0}] Umount command [{1}], umount arguments [{2}].",
  315. Name,
  316. cmdFilename,
  317. cmdArguments
  318. );
  319. if (ExecuteCommand(cmdFilename, cmdArguments)) {
  320. _logger.LogInformation(
  321. "[{0}] ISO unmount completed successfully.",
  322. Name
  323. );
  324. } else {
  325. _logger.LogInformation(
  326. "[{0}] ISO unmount completed with errors.",
  327. Name
  328. );
  329. }
  330. try
  331. {
  332. FileSystem.DeleteDirectory(mount.MountedPath, false);
  333. }
  334. catch (Exception ex)
  335. {
  336. _logger.LogInformation(ex, "[{Name}] Unhandled exception removing mount point.", Name);
  337. }
  338. }
  339. #endregion
  340. #region Internal Methods
  341. internal void OnUnmount(LinuxMount mount)
  342. {
  343. UnmountISO(mount);
  344. }
  345. #endregion
  346. }
  347. }