LinuxIsoManager.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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 = Path.DirectorySeparatorChar + "tmp" + Path.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
  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
  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) && File.Exists(path = Path.Combine(path, name)))
  167. {
  168. return Path.GetFullPath(path);
  169. }
  170. }
  171. return string.Empty;
  172. }
  173. private uint GetUID()
  174. {
  175. var uid = getuid();
  176. _logger.LogDebug(
  177. "[{0}] GetUserId() returned [{2}].",
  178. Name,
  179. uid
  180. );
  181. return uid;
  182. }
  183. private bool ExecuteCommand(string cmdFilename, string cmdArguments)
  184. {
  185. bool processFailed = false;
  186. var process = ProcessFactory.Create(
  187. new ProcessOptions
  188. {
  189. CreateNoWindow = true,
  190. RedirectStandardOutput = true,
  191. RedirectStandardError = true,
  192. UseShellExecute = false,
  193. FileName = cmdFilename,
  194. Arguments = cmdArguments,
  195. IsHidden = true,
  196. ErrorDialog = false,
  197. EnableRaisingEvents = true
  198. }
  199. );
  200. try
  201. {
  202. process.Start();
  203. //StreamReader outputReader = process.StandardOutput.;
  204. //StreamReader errorReader = process.StandardError;
  205. _logger.LogDebug(
  206. "[{Name}] Standard output from process is [{Error}].",
  207. Name,
  208. process.StandardOutput.ReadToEnd()
  209. );
  210. _logger.LogDebug(
  211. "[{Name}] Standard error from process is [{Error}].",
  212. Name,
  213. process.StandardError.ReadToEnd()
  214. );
  215. }
  216. catch (Exception ex)
  217. {
  218. processFailed = true;
  219. _logger.LogDebug(ex, "[{Name}] Unhandled exception executing command.", Name);
  220. }
  221. if (!processFailed && process.ExitCode == 0)
  222. {
  223. return true;
  224. }
  225. else
  226. {
  227. return false;
  228. }
  229. }
  230. private bool MountISO(string isoPath, out LinuxMount mountedISO)
  231. {
  232. string cmdArguments;
  233. string cmdFilename;
  234. string mountPoint = Path.Combine(MountPointRoot, Guid.NewGuid().ToString());
  235. if (!string.IsNullOrEmpty(isoPath))
  236. {
  237. _logger.LogInformation(
  238. "[{Name}] Attempting to mount [{Path}].",
  239. Name,
  240. isoPath
  241. );
  242. _logger.LogDebug(
  243. "[{Name}] ISO will be mounted at [{Path}].",
  244. Name,
  245. mountPoint
  246. );
  247. }
  248. else
  249. {
  250. throw new ArgumentNullException(nameof(isoPath));
  251. }
  252. try
  253. {
  254. Directory.CreateDirectory(mountPoint);
  255. }
  256. catch (UnauthorizedAccessException)
  257. {
  258. throw new IOException("Unable to create mount point(Permission denied) for " + isoPath);
  259. }
  260. catch (Exception)
  261. {
  262. throw new IOException("Unable to create mount point for " + isoPath);
  263. }
  264. if (GetUID() == 0)
  265. {
  266. cmdFilename = MountCommand;
  267. cmdArguments = string.Format("\"{0}\" \"{1}\"", isoPath, mountPoint);
  268. }
  269. else
  270. {
  271. cmdFilename = SudoCommand;
  272. cmdArguments = string.Format("\"{0}\" \"{1}\" \"{2}\"", MountCommand, isoPath, mountPoint);
  273. }
  274. _logger.LogDebug(
  275. "[{0}] Mount command [{1}], mount arguments [{2}].",
  276. Name,
  277. cmdFilename,
  278. cmdArguments
  279. );
  280. if (ExecuteCommand(cmdFilename, cmdArguments))
  281. {
  282. _logger.LogInformation(
  283. "[{0}] ISO mount completed successfully.",
  284. Name
  285. );
  286. mountedISO = new LinuxMount(this, isoPath, mountPoint);
  287. }
  288. else
  289. {
  290. _logger.LogInformation(
  291. "[{0}] ISO mount completed with errors.",
  292. Name
  293. );
  294. try
  295. {
  296. Directory.Delete(mountPoint, false);
  297. }
  298. catch (Exception ex)
  299. {
  300. _logger.LogInformation(ex, "[{Name}] Unhandled exception removing mount point.", Name);
  301. }
  302. mountedISO = null;
  303. }
  304. return mountedISO != null;
  305. }
  306. private void UnmountISO(LinuxMount mount)
  307. {
  308. string cmdArguments;
  309. string cmdFilename;
  310. if (mount != null)
  311. {
  312. _logger.LogInformation(
  313. "[{0}] Attempting to unmount ISO [{1}] mounted on [{2}].",
  314. Name,
  315. mount.IsoPath,
  316. mount.MountedPath
  317. );
  318. }
  319. else
  320. {
  321. throw new ArgumentNullException(nameof(mount));
  322. }
  323. if (GetUID() == 0)
  324. {
  325. cmdFilename = UmountCommand;
  326. cmdArguments = string.Format("\"{0}\"", mount.MountedPath);
  327. }
  328. else
  329. {
  330. cmdFilename = SudoCommand;
  331. cmdArguments = string.Format("\"{0}\" \"{1}\"", UmountCommand, mount.MountedPath);
  332. }
  333. _logger.LogDebug(
  334. "[{0}] Umount command [{1}], umount arguments [{2}].",
  335. Name,
  336. cmdFilename,
  337. cmdArguments
  338. );
  339. if (ExecuteCommand(cmdFilename, cmdArguments))
  340. {
  341. _logger.LogInformation(
  342. "[{0}] ISO unmount completed successfully.",
  343. Name
  344. );
  345. }
  346. else
  347. {
  348. _logger.LogInformation(
  349. "[{0}] ISO unmount completed with errors.",
  350. Name
  351. );
  352. }
  353. try
  354. {
  355. Directory.Delete(mount.MountedPath, false);
  356. }
  357. catch (Exception ex)
  358. {
  359. _logger.LogInformation(ex, "[{Name}] Unhandled exception removing mount point.", Name);
  360. }
  361. }
  362. #endregion
  363. #region Internal Methods
  364. internal void OnUnmount(LinuxMount mount)
  365. {
  366. UnmountISO(mount);
  367. }
  368. #endregion
  369. }
  370. }