LinuxIsoManager.cs 13 KB

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