LinuxIsoManager.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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. namespace IsoMounter
  11. {
  12. public class LinuxIsoManager : IIsoMounter
  13. {
  14. [DllImport("libc", SetLastError = true)]
  15. 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. Environment.GetEnvironmentVariable("PATH") ?? ""
  39. );
  40. _logger.LogDebug(
  41. "[{0}] System path separator is [{1}].",
  42. Name,
  43. Path.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. {
  73. ExecutablesAvailable = true;
  74. }
  75. else
  76. {
  77. ExecutablesAvailable = false;
  78. }
  79. }
  80. #endregion
  81. #region Interface Implementation for IIsoMounter
  82. public bool IsInstalled => true;
  83. public string Name => "LinuxMount";
  84. public bool RequiresInstallation => false;
  85. public bool CanMount(string path)
  86. {
  87. if (EnvironmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Linux)
  88. {
  89. return false;
  90. }
  91. _logger.LogInformation(
  92. "[{0}] Checking we can attempt to mount [{1}], Extension = [{2}], Operating System = [{3}], Executables Available = [{4}].",
  93. Name,
  94. path,
  95. Path.GetExtension(path),
  96. EnvironmentInfo.OperatingSystem,
  97. ExecutablesAvailable.ToString()
  98. );
  99. if (ExecutablesAvailable)
  100. {
  101. return string.Equals(Path.GetExtension(path), ".iso", StringComparison.OrdinalIgnoreCase);
  102. }
  103. else
  104. {
  105. return false;
  106. }
  107. }
  108. public Task Install(CancellationToken cancellationToken)
  109. {
  110. return Task.FromResult(false);
  111. }
  112. public Task<IIsoMount> Mount(string isoPath, CancellationToken cancellationToken)
  113. {
  114. if (MountISO(isoPath, out LinuxMount mountedISO))
  115. {
  116. return Task.FromResult<IIsoMount>(mountedISO);
  117. }
  118. else
  119. {
  120. throw new IOException(string.Format(
  121. "An error occurred trying to mount image [$0].",
  122. isoPath
  123. ));
  124. }
  125. }
  126. #endregion
  127. #region Interface Implementation for IDisposable
  128. // Flag: Has Dispose already been called?
  129. private bool disposed = false;
  130. public void Dispose()
  131. {
  132. // Dispose of unmanaged resources.
  133. Dispose(true);
  134. // Suppress finalization.
  135. GC.SuppressFinalize(this);
  136. }
  137. protected virtual void Dispose(bool disposing)
  138. {
  139. if (disposed)
  140. {
  141. return;
  142. }
  143. _logger.LogInformation(
  144. "[{0}] Disposing [{1}].",
  145. Name,
  146. disposing.ToString()
  147. );
  148. if (disposing)
  149. {
  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 (Environment.GetEnvironmentVariable("PATH") ?? "").Split(Path.PathSeparator))
  164. {
  165. string path = test.Trim();
  166. if (!string.IsNullOrEmpty(path) && FileSystem.FileExists(path = Path.Combine(path, name)))
  167. {
  168. return FileSystem.GetFullPath(path);
  169. }
  170. }
  171. return string.Empty;
  172. }
  173. private uint GetUID()
  174. {
  175. var uid = getuid();
  176. _logger.LogDebug(
  177. "[{0}] Our current UID is [{1}], GetUserId() returned [{2}].",
  178. Name,
  179. uid.ToString(),
  180. uid
  181. );
  182. return uid;
  183. }
  184. private bool ExecuteCommand(string cmdFilename, string cmdArguments)
  185. {
  186. bool processFailed = false;
  187. var process = ProcessFactory.Create(
  188. new ProcessOptions
  189. {
  190. CreateNoWindow = true,
  191. RedirectStandardOutput = true,
  192. RedirectStandardError = true,
  193. UseShellExecute = false,
  194. FileName = cmdFilename,
  195. Arguments = cmdArguments,
  196. IsHidden = true,
  197. ErrorDialog = false,
  198. EnableRaisingEvents = true
  199. }
  200. );
  201. try
  202. {
  203. process.Start();
  204. //StreamReader outputReader = process.StandardOutput.;
  205. //StreamReader errorReader = process.StandardError;
  206. _logger.LogDebug(
  207. "[{Name}] Standard output from process is [{Error}].",
  208. Name,
  209. process.StandardOutput.ReadToEnd()
  210. );
  211. _logger.LogDebug(
  212. "[{Name}] Standard error from process is [{Error}].",
  213. Name,
  214. process.StandardError.ReadToEnd()
  215. );
  216. }
  217. catch (Exception ex)
  218. {
  219. processFailed = true;
  220. _logger.LogDebug(ex, "[{Name}] Unhandled exception executing command.", Name);
  221. }
  222. if (!processFailed && process.ExitCode == 0)
  223. {
  224. return true;
  225. }
  226. else
  227. {
  228. return false;
  229. }
  230. }
  231. private bool MountISO(string isoPath, out LinuxMount mountedISO)
  232. {
  233. string cmdArguments;
  234. string cmdFilename;
  235. string mountPoint = Path.Combine(MountPointRoot, Guid.NewGuid().ToString());
  236. if (!string.IsNullOrEmpty(isoPath))
  237. {
  238. _logger.LogInformation(
  239. "[{Name}] Attempting to mount [{Path}].",
  240. Name,
  241. isoPath
  242. );
  243. _logger.LogDebug(
  244. "[{Name}] ISO will be mounted at [{Path}].",
  245. Name,
  246. mountPoint
  247. );
  248. }
  249. else
  250. {
  251. throw new ArgumentNullException(nameof(isoPath));
  252. }
  253. try
  254. {
  255. FileSystem.CreateDirectory(mountPoint);
  256. }
  257. catch (UnauthorizedAccessException)
  258. {
  259. throw new IOException("Unable to create mount point(Permission denied) for " + isoPath);
  260. }
  261. catch (Exception)
  262. {
  263. throw new IOException("Unable to create mount point for " + isoPath);
  264. }
  265. if (GetUID() == 0)
  266. {
  267. cmdFilename = MountCommand;
  268. cmdArguments = string.Format("\"{0}\" \"{1}\"", isoPath, mountPoint);
  269. }
  270. else
  271. {
  272. cmdFilename = SudoCommand;
  273. cmdArguments = string.Format("\"{0}\" \"{1}\" \"{2}\"", MountCommand, isoPath, mountPoint);
  274. }
  275. _logger.LogDebug(
  276. "[{0}] Mount command [{1}], mount arguments [{2}].",
  277. Name,
  278. cmdFilename,
  279. cmdArguments
  280. );
  281. if (ExecuteCommand(cmdFilename, cmdArguments))
  282. {
  283. _logger.LogInformation(
  284. "[{0}] ISO mount completed successfully.",
  285. Name
  286. );
  287. mountedISO = new LinuxMount(this, isoPath, mountPoint);
  288. }
  289. else
  290. {
  291. _logger.LogInformation(
  292. "[{0}] ISO mount completed with errors.",
  293. Name
  294. );
  295. try
  296. {
  297. FileSystem.DeleteDirectory(mountPoint, false);
  298. }
  299. catch (Exception ex)
  300. {
  301. _logger.LogInformation(ex, "[{Name}] Unhandled exception removing mount point.", Name);
  302. }
  303. mountedISO = null;
  304. }
  305. return mountedISO != null;
  306. }
  307. private void UnmountISO(LinuxMount mount)
  308. {
  309. string cmdArguments;
  310. string cmdFilename;
  311. if (mount != null)
  312. {
  313. _logger.LogInformation(
  314. "[{0}] Attempting to unmount ISO [{1}] mounted on [{2}].",
  315. Name,
  316. mount.IsoPath,
  317. mount.MountedPath
  318. );
  319. }
  320. else
  321. {
  322. throw new ArgumentNullException(nameof(mount));
  323. }
  324. if (GetUID() == 0)
  325. {
  326. cmdFilename = UmountCommand;
  327. cmdArguments = string.Format("\"{0}\"", mount.MountedPath);
  328. }
  329. else
  330. {
  331. cmdFilename = SudoCommand;
  332. cmdArguments = string.Format("\"{0}\" \"{1}\"", UmountCommand, mount.MountedPath);
  333. }
  334. _logger.LogDebug(
  335. "[{0}] Umount command [{1}], umount arguments [{2}].",
  336. Name,
  337. cmdFilename,
  338. cmdArguments
  339. );
  340. if (ExecuteCommand(cmdFilename, cmdArguments))
  341. {
  342. _logger.LogInformation(
  343. "[{0}] ISO unmount completed successfully.",
  344. Name
  345. );
  346. }
  347. else
  348. {
  349. _logger.LogInformation(
  350. "[{0}] ISO unmount completed with errors.",
  351. Name
  352. );
  353. }
  354. try
  355. {
  356. FileSystem.DeleteDirectory(mount.MountedPath, false);
  357. }
  358. catch (Exception ex)
  359. {
  360. _logger.LogInformation(ex, "[{Name}] Unhandled exception removing mount point.", Name);
  361. }
  362. }
  363. #endregion
  364. #region Internal Methods
  365. internal void OnUnmount(LinuxMount mount)
  366. {
  367. UnmountISO(mount);
  368. }
  369. #endregion
  370. }
  371. }