NTFileSystemAdapter.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. /* Copyright (C) 2014-2017 Tal Aloni <tal.aloni.il@gmail.com>. All rights reserved.
  2. *
  3. * You can redistribute this program and/or modify it under the terms of
  4. * the GNU Lesser Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using Utilities;
  11. namespace SMBLibrary
  12. {
  13. public partial class NTFileSystemAdapter : INTFileStore
  14. {
  15. private const int BytesPerSector = 512;
  16. private const int ClusterSize = 4096;
  17. private IFileSystem m_fileSystem;
  18. public event EventHandler<LogEntry> OnLogEntry;
  19. public NTFileSystemAdapter(IFileSystem fileSystem)
  20. {
  21. m_fileSystem = fileSystem;
  22. }
  23. public NTStatus CreateFile(out object handle, out FileStatus fileStatus, string path, AccessMask desiredAccess, ShareAccess shareAccess, CreateDisposition createDisposition, CreateOptions createOptions)
  24. {
  25. handle = null;
  26. fileStatus = FileStatus.FILE_DOES_NOT_EXIST;
  27. FileAccess createAccess = NTFileStoreHelper.ToCreateFileAccess(desiredAccess, createDisposition);
  28. bool requestedWriteAccess = (createAccess & FileAccess.Write) > 0;
  29. bool forceDirectory = (createOptions & CreateOptions.FILE_DIRECTORY_FILE) > 0;
  30. bool forceFile = (createOptions & CreateOptions.FILE_NON_DIRECTORY_FILE) > 0;
  31. if (forceDirectory & (createDisposition != CreateDisposition.FILE_CREATE &&
  32. createDisposition != CreateDisposition.FILE_OPEN &&
  33. createDisposition != CreateDisposition.FILE_OPEN_IF &&
  34. createDisposition != CreateDisposition.FILE_SUPERSEDE))
  35. {
  36. return NTStatus.STATUS_INVALID_PARAMETER;
  37. }
  38. // Windows will try to access named streams (alternate data streams) regardless of the FILE_NAMED_STREAMS flag, we need to prevent this behaviour.
  39. if (path.Contains(":"))
  40. {
  41. // Windows Server 2003 will return STATUS_OBJECT_NAME_NOT_FOUND
  42. return NTStatus.STATUS_NO_SUCH_FILE;
  43. }
  44. FileSystemEntry entry;
  45. try
  46. {
  47. entry = m_fileSystem.GetEntry(path);
  48. }
  49. catch (Exception ex)
  50. {
  51. NTStatus status = ToNTStatus(ex);
  52. Log(Severity.Debug, "CreateFile: Error retrieving '{0}'. {1}.", path, status);
  53. return status;
  54. }
  55. if (createDisposition == CreateDisposition.FILE_OPEN)
  56. {
  57. if (entry == null)
  58. {
  59. return NTStatus.STATUS_OBJECT_PATH_NOT_FOUND;
  60. }
  61. fileStatus = FileStatus.FILE_EXISTS;
  62. if (entry.IsDirectory && forceFile)
  63. {
  64. return NTStatus.STATUS_FILE_IS_A_DIRECTORY;
  65. }
  66. if (!entry.IsDirectory && forceDirectory)
  67. {
  68. return NTStatus.STATUS_OBJECT_PATH_INVALID;
  69. }
  70. }
  71. else if (createDisposition == CreateDisposition.FILE_CREATE)
  72. {
  73. if (entry != null)
  74. {
  75. // File already exists, fail the request
  76. Log(Severity.Debug, "CreateFile: File '{0}' already exist", path);
  77. fileStatus = FileStatus.FILE_EXISTS;
  78. return NTStatus.STATUS_OBJECT_NAME_COLLISION;
  79. }
  80. if (!requestedWriteAccess)
  81. {
  82. return NTStatus.STATUS_ACCESS_DENIED;
  83. }
  84. try
  85. {
  86. if (forceDirectory)
  87. {
  88. Log(Severity.Information, "CreateFile: Creating directory '{0}'", path);
  89. entry = m_fileSystem.CreateDirectory(path);
  90. }
  91. else
  92. {
  93. Log(Severity.Information, "CreateFile: Creating file '{0}'", path);
  94. entry = m_fileSystem.CreateFile(path);
  95. }
  96. }
  97. catch (Exception ex)
  98. {
  99. NTStatus status = ToNTStatus(ex);
  100. Log(Severity.Debug, "CreateFile: Error creating '{0}'. {1}.", path, status);
  101. return status;
  102. }
  103. fileStatus = FileStatus.FILE_CREATED;
  104. }
  105. else if (createDisposition == CreateDisposition.FILE_OPEN_IF ||
  106. createDisposition == CreateDisposition.FILE_OVERWRITE ||
  107. createDisposition == CreateDisposition.FILE_OVERWRITE_IF ||
  108. createDisposition == CreateDisposition.FILE_SUPERSEDE)
  109. {
  110. if (entry == null)
  111. {
  112. if (createDisposition == CreateDisposition.FILE_OVERWRITE)
  113. {
  114. return NTStatus.STATUS_OBJECT_PATH_NOT_FOUND;
  115. }
  116. if (!requestedWriteAccess)
  117. {
  118. return NTStatus.STATUS_ACCESS_DENIED;
  119. }
  120. try
  121. {
  122. if (forceDirectory)
  123. {
  124. Log(Severity.Information, "CreateFile: Creating directory '{0}'", path);
  125. entry = m_fileSystem.CreateDirectory(path);
  126. }
  127. else
  128. {
  129. Log(Severity.Information, "CreateFile: Creating file '{0}'", path);
  130. entry = m_fileSystem.CreateFile(path);
  131. }
  132. }
  133. catch (Exception ex)
  134. {
  135. NTStatus status = ToNTStatus(ex);
  136. Log(Severity.Debug, "CreateFile: Error creating '{0}'. {1}.", path, status);
  137. return status;
  138. }
  139. fileStatus = FileStatus.FILE_CREATED;
  140. }
  141. else
  142. {
  143. fileStatus = FileStatus.FILE_EXISTS;
  144. if (!requestedWriteAccess)
  145. {
  146. return NTStatus.STATUS_ACCESS_DENIED;
  147. }
  148. if (createDisposition == CreateDisposition.FILE_OVERWRITE ||
  149. createDisposition == CreateDisposition.FILE_OVERWRITE_IF)
  150. {
  151. // Truncate the file
  152. try
  153. {
  154. Stream temp = m_fileSystem.OpenFile(path, FileMode.Truncate, FileAccess.ReadWrite, FileShare.ReadWrite);
  155. temp.Close();
  156. }
  157. catch (Exception ex)
  158. {
  159. NTStatus status = ToNTStatus(ex);
  160. Log(Severity.Debug, "CreateFile: Error truncating '{0}'. {1}.", path, status);
  161. return status;
  162. }
  163. fileStatus = FileStatus.FILE_OVERWRITTEN;
  164. }
  165. else if (createDisposition == CreateDisposition.FILE_SUPERSEDE)
  166. {
  167. // Delete the old file
  168. try
  169. {
  170. m_fileSystem.Delete(path);
  171. }
  172. catch(Exception ex)
  173. {
  174. NTStatus status = ToNTStatus(ex);
  175. Log(Severity.Debug, "CreateFile: Error deleting '{0}'. {1}.", path, status);
  176. return status;
  177. }
  178. try
  179. {
  180. if (forceDirectory)
  181. {
  182. Log(Severity.Information, "CreateFile: Creating directory '{0}'", path);
  183. entry = m_fileSystem.CreateDirectory(path);
  184. }
  185. else
  186. {
  187. Log(Severity.Information, "CreateFile: Creating file '{0}'", path);
  188. entry = m_fileSystem.CreateFile(path);
  189. }
  190. }
  191. catch (Exception ex)
  192. {
  193. NTStatus status = ToNTStatus(ex);
  194. Log(Severity.Debug, "CreateFile: Error creating '{0}'. {1}.", path, status);
  195. return status;
  196. }
  197. fileStatus = FileStatus.FILE_SUPERSEDED;
  198. }
  199. }
  200. }
  201. else
  202. {
  203. return NTStatus.STATUS_INVALID_PARAMETER;
  204. }
  205. FileAccess fileAccess = NTFileStoreHelper.ToFileAccess(desiredAccess.File);
  206. Stream stream;
  207. bool deleteOnClose = false;
  208. if (fileAccess == (FileAccess)0 || entry.IsDirectory)
  209. {
  210. stream = null;
  211. }
  212. else
  213. {
  214. deleteOnClose = (createOptions & CreateOptions.FILE_DELETE_ON_CLOSE) > 0;
  215. NTStatus openStatus = OpenFileStream(out stream, path, fileAccess, shareAccess, createOptions);
  216. if (openStatus != NTStatus.STATUS_SUCCESS)
  217. {
  218. return openStatus;
  219. }
  220. }
  221. handle = new FileHandle(path, entry.IsDirectory, stream, deleteOnClose);
  222. if (fileStatus != FileStatus.FILE_CREATED &&
  223. fileStatus != FileStatus.FILE_OVERWRITTEN &&
  224. fileStatus != FileStatus.FILE_SUPERSEDED)
  225. {
  226. fileStatus = FileStatus.FILE_OPENED;
  227. }
  228. return NTStatus.STATUS_SUCCESS;
  229. }
  230. private NTStatus OpenFileStream(out Stream stream, string path, FileAccess fileAccess, ShareAccess shareAccess, CreateOptions openOptions)
  231. {
  232. stream = null;
  233. // When FILE_OPEN_REPARSE_POINT is specified, the operation should continue normally if the file is not a reparse point.
  234. // FILE_OPEN_REPARSE_POINT is a hint that the caller does not intend to actually read the file, with the exception
  235. // of a file copy operation (where the caller will attempt to simply copy the reparse point).
  236. bool openReparsePoint = (openOptions & CreateOptions.FILE_OPEN_REPARSE_POINT) > 0;
  237. bool disableBuffering = (openOptions & CreateOptions.FILE_NO_INTERMEDIATE_BUFFERING) > 0;
  238. bool buffered = (openOptions & CreateOptions.FILE_SEQUENTIAL_ONLY) > 0 && !disableBuffering && !openReparsePoint;
  239. FileShare fileShare = NTFileStoreHelper.ToFileShare(shareAccess);
  240. Log(Severity.Verbose, "OpenFileStream: Opening '{0}', Access={1}, Share={2}, Buffered={3}", path, fileAccess, fileShare, buffered);
  241. try
  242. {
  243. stream = m_fileSystem.OpenFile(path, FileMode.Open, fileAccess, fileShare);
  244. }
  245. catch (Exception ex)
  246. {
  247. NTStatus status = ToNTStatus(ex);
  248. Log(Severity.Debug, "OpenFile: Cannot open '{0}'. {1}.", path, status);
  249. return status;
  250. }
  251. if (buffered)
  252. {
  253. stream = new PrefetchedStream(stream);
  254. }
  255. return NTStatus.STATUS_SUCCESS;
  256. }
  257. public NTStatus CloseFile(object handle)
  258. {
  259. FileHandle fileHandle = (FileHandle)handle;
  260. if (fileHandle.Stream != null)
  261. {
  262. fileHandle.Stream.Close();
  263. }
  264. if (fileHandle.DeleteOnClose)
  265. {
  266. try
  267. {
  268. m_fileSystem.Delete(fileHandle.Path);
  269. }
  270. catch
  271. {
  272. }
  273. }
  274. return NTStatus.STATUS_SUCCESS;
  275. }
  276. public NTStatus ReadFile(out byte[] data, object handle, long offset, int maxCount)
  277. {
  278. data = null;
  279. FileHandle fileHandle = (FileHandle)handle;
  280. string path = fileHandle.Path;
  281. Stream stream = fileHandle.Stream;
  282. if (stream == null || !stream.CanRead)
  283. {
  284. Log(Severity.Debug, "ReadFile: Cannot read '{0}', Invalid Operation.", path);
  285. return NTStatus.STATUS_ACCESS_DENIED;
  286. }
  287. int bytesRead;
  288. try
  289. {
  290. stream.Seek(offset, SeekOrigin.Begin);
  291. data = new byte[maxCount];
  292. bytesRead = stream.Read(data, 0, maxCount);
  293. }
  294. catch (Exception ex)
  295. {
  296. NTStatus status = ToNTStatus(ex);
  297. Log(Severity.Debug, "ReadFile: Cannot read '{0}'. {1}.", path, status);
  298. return status;
  299. }
  300. if (bytesRead < maxCount)
  301. {
  302. // EOF, we must trim the response data array
  303. data = ByteReader.ReadBytes(data, 0, bytesRead);
  304. }
  305. return NTStatus.STATUS_SUCCESS;
  306. }
  307. public NTStatus WriteFile(out int numberOfBytesWritten, object handle, long offset, byte[] data)
  308. {
  309. numberOfBytesWritten = 0;
  310. FileHandle fileHandle = (FileHandle)handle;
  311. string path = fileHandle.Path;
  312. Stream stream = fileHandle.Stream;
  313. if (stream == null || !stream.CanWrite)
  314. {
  315. Log(Severity.Debug, "WriteFile: Cannot write '{0}'. Invalid Operation.", path);
  316. return NTStatus.STATUS_ACCESS_DENIED;
  317. }
  318. try
  319. {
  320. stream.Seek(offset, SeekOrigin.Begin);
  321. stream.Write(data, 0, data.Length);
  322. }
  323. catch (Exception ex)
  324. {
  325. NTStatus status = ToNTStatus(ex);
  326. Log(Severity.Debug, "WriteFile: Cannot write '{0}'. {1}.", path, status);
  327. return status;
  328. }
  329. numberOfBytesWritten = data.Length;
  330. return NTStatus.STATUS_SUCCESS;
  331. }
  332. public NTStatus FlushFileBuffers(object handle)
  333. {
  334. FileHandle fileHandle = (FileHandle)handle;
  335. if (fileHandle.Stream != null)
  336. {
  337. fileHandle.Stream.Flush();
  338. }
  339. return NTStatus.STATUS_SUCCESS;
  340. }
  341. public NTStatus DeviceIOControl(object handle, uint ctlCode, byte[] input, out byte[] output, int maxOutputLength)
  342. {
  343. output = null;
  344. return NTStatus.STATUS_NOT_SUPPORTED;
  345. }
  346. public void Log(Severity severity, string message)
  347. {
  348. // To be thread-safe we must capture the delegate reference first
  349. EventHandler<LogEntry> handler = OnLogEntry;
  350. if (handler != null)
  351. {
  352. handler(this, new LogEntry(DateTime.Now, severity, "NT FileSystem", message));
  353. }
  354. }
  355. public void Log(Severity severity, string message, params object[] args)
  356. {
  357. Log(severity, String.Format(message, args));
  358. }
  359. /// <param name="exception">IFileSystem exception</param>
  360. private static NTStatus ToNTStatus(Exception exception)
  361. {
  362. if (exception is ArgumentException)
  363. {
  364. return NTStatus.STATUS_OBJECT_PATH_SYNTAX_BAD;
  365. }
  366. else if (exception is DirectoryNotFoundException)
  367. {
  368. return NTStatus.STATUS_OBJECT_PATH_NOT_FOUND;
  369. }
  370. else if (exception is FileNotFoundException)
  371. {
  372. return NTStatus.STATUS_OBJECT_PATH_NOT_FOUND;
  373. }
  374. else if (exception is IOException)
  375. {
  376. ushort errorCode = IOExceptionHelper.GetWin32ErrorCode((IOException)exception);
  377. if (errorCode == (ushort)Win32Error.ERROR_SHARING_VIOLATION)
  378. {
  379. return NTStatus.STATUS_SHARING_VIOLATION;
  380. }
  381. else if (errorCode == (ushort)Win32Error.ERROR_DISK_FULL)
  382. {
  383. return NTStatus.STATUS_DISK_FULL;
  384. }
  385. else if (errorCode == (ushort)Win32Error.ERROR_DIR_NOT_EMPTY)
  386. {
  387. // If a user tries to rename folder1 to folder2 when folder2 already exists, Windows 7 will offer to merge folder1 into folder2.
  388. // In such case, Windows 7 will delete folder 1 and will expect STATUS_DIRECTORY_NOT_EMPTY if there are files to merge.
  389. return NTStatus.STATUS_DIRECTORY_NOT_EMPTY;
  390. }
  391. else if (errorCode == (ushort)Win32Error.ERROR_ALREADY_EXISTS)
  392. {
  393. // According to [MS-FSCC], FileRenameInformation MUST return STATUS_OBJECT_NAME_COLLISION when the specified name already exists and ReplaceIfExists is zero.
  394. return NTStatus.STATUS_OBJECT_NAME_COLLISION;
  395. }
  396. else
  397. {
  398. return NTStatus.STATUS_DATA_ERROR;
  399. }
  400. }
  401. else if (exception is UnauthorizedAccessException)
  402. {
  403. return NTStatus.STATUS_ACCESS_DENIED;
  404. }
  405. else
  406. {
  407. return NTStatus.STATUS_DATA_ERROR;
  408. }
  409. }
  410. /// <summary>
  411. /// Will return a virtual allocation size, assuming 4096 bytes per cluster
  412. /// </summary>
  413. public static ulong GetAllocationSize(ulong size)
  414. {
  415. return (ulong)Math.Ceiling((double)size / ClusterSize) * ClusterSize;
  416. }
  417. public static string GetShortName(string fileName)
  418. {
  419. string fileNameWithoutExt = System.IO.Path.GetFileNameWithoutExtension(fileName);
  420. string extension = System.IO.Path.GetExtension(fileName);
  421. if (fileNameWithoutExt.Length > 8 || extension.Length > 4)
  422. {
  423. if (fileNameWithoutExt.Length > 8)
  424. {
  425. fileNameWithoutExt = fileNameWithoutExt.Substring(0, 8);
  426. }
  427. if (extension.Length > 4)
  428. {
  429. extension = extension.Substring(0, 4);
  430. }
  431. return fileNameWithoutExt + extension;
  432. }
  433. else
  434. {
  435. return fileName;
  436. }
  437. }
  438. }
  439. }