LinuxIsoManager.cs 12 KB

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