LinuxIsoManager.cs 12 KB

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