LinuxIsoManager.cs 12 KB

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