WindowsNameTransform.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. using System.Net.ApiService.Compression.Core;
  2. using System;
  3. using System.IO;
  4. using System.Text;
  5. namespace System.Net.ApiService.Compression.Zip {
  6. /// <summary>
  7. /// WindowsNameTransform transforms <see cref="ZipFile"/> names to windows compatible ones.
  8. /// </summary>
  9. public class WindowsNameTransform : INameTransform
  10. {
  11. /// <summary>
  12. /// The maximum windows path name permitted.
  13. /// </summary>
  14. /// <remarks>This may not valid for all windows systems - CE?, etc but I cant find the equivalent in the CLR.</remarks>
  15. private const int MaxPath = 260;
  16. private string _baseDirectory;
  17. private bool _trimIncomingPaths;
  18. private char _replacementChar = '_';
  19. private bool _allowParentTraversal;
  20. /// <summary>
  21. /// In this case we need Windows' invalid path characters.
  22. /// Path.GetInvalidPathChars() only returns a subset invalid on all platforms.
  23. /// </summary>
  24. private static readonly char[] InvalidEntryChars = new char[] {
  25. '"', '<', '>', '|', '\0', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005',
  26. '\u0006', '\a', '\b', '\t', '\n', '\v', '\f', '\r', '\u000e', '\u000f',
  27. '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016',
  28. '\u0017', '\u0018', '\u0019', '\u001a', '\u001b', '\u001c', '\u001d',
  29. '\u001e', '\u001f',
  30. // extra characters for masks, etc.
  31. '*', '?', ':'
  32. };
  33. /// <summary>
  34. /// Initialises a new instance of <see cref="WindowsNameTransform"/>
  35. /// </summary>
  36. /// <param name="baseDirectory"></param>
  37. /// <param name="allowParentTraversal">Allow parent directory traversal in file paths (e.g. ../file)</param>
  38. public WindowsNameTransform(string baseDirectory, bool allowParentTraversal = false)
  39. {
  40. BaseDirectory = baseDirectory ?? throw new ArgumentNullException(nameof(baseDirectory), "Directory name is invalid");
  41. AllowParentTraversal = allowParentTraversal;
  42. }
  43. /// <summary>
  44. /// Initialise a default instance of <see cref="WindowsNameTransform"/>
  45. /// </summary>
  46. public WindowsNameTransform()
  47. {
  48. // Do nothing.
  49. }
  50. /// <summary>
  51. /// Gets or sets a value containing the target directory to prefix values with.
  52. /// </summary>
  53. public string BaseDirectory
  54. {
  55. get { return _baseDirectory; }
  56. set
  57. {
  58. if (value == null)
  59. {
  60. throw new ArgumentNullException(nameof(value));
  61. }
  62. _baseDirectory = Path.GetFullPath(value);
  63. }
  64. }
  65. /// <summary>
  66. /// Allow parent directory traversal in file paths (e.g. ../file)
  67. /// </summary>
  68. public bool AllowParentTraversal
  69. {
  70. get => _allowParentTraversal;
  71. set => _allowParentTraversal = value;
  72. }
  73. /// <summary>
  74. /// Gets or sets a value indicating wether paths on incoming values should be removed.
  75. /// </summary>
  76. public bool TrimIncomingPaths
  77. {
  78. get { return _trimIncomingPaths; }
  79. set { _trimIncomingPaths = value; }
  80. }
  81. /// <summary>
  82. /// Transform a Zip directory name to a windows directory name.
  83. /// </summary>
  84. /// <param name="name">The directory name to transform.</param>
  85. /// <returns>The transformed name.</returns>
  86. public string TransformDirectory(string name)
  87. {
  88. name = TransformFile(name);
  89. if (name.Length > 0)
  90. {
  91. while (name.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
  92. {
  93. name = name.Remove(name.Length - 1, 1);
  94. }
  95. }
  96. else
  97. {
  98. throw new InvalidNameException("Cannot have an empty directory name");
  99. }
  100. return name;
  101. }
  102. /// <summary>
  103. /// Transform a Zip format file name to a windows style one.
  104. /// </summary>
  105. /// <param name="name">The file name to transform.</param>
  106. /// <returns>The transformed name.</returns>
  107. public string TransformFile(string name)
  108. {
  109. if (name != null)
  110. {
  111. name = MakeValidName(name, _replacementChar);
  112. if (_trimIncomingPaths)
  113. {
  114. name = Path.GetFileName(name);
  115. }
  116. // This may exceed windows length restrictions.
  117. // Combine will throw a PathTooLongException in that case.
  118. if (_baseDirectory != null)
  119. {
  120. name = Path.Combine(_baseDirectory, name);
  121. if (!_allowParentTraversal && !Path.GetFullPath(name).StartsWith(_baseDirectory, StringComparison.InvariantCultureIgnoreCase))
  122. {
  123. throw new InvalidNameException("Parent traversal in paths is not allowed");
  124. }
  125. }
  126. }
  127. else
  128. {
  129. name = string.Empty;
  130. }
  131. return name;
  132. }
  133. /// <summary>
  134. /// Test a name to see if it is a valid name for a windows filename as extracted from a Zip archive.
  135. /// </summary>
  136. /// <param name="name">The name to test.</param>
  137. /// <returns>Returns true if the name is a valid zip name; false otherwise.</returns>
  138. /// <remarks>The filename isnt a true windows path in some fundamental ways like no absolute paths, no rooted paths etc.</remarks>
  139. public static bool IsValidName(string name)
  140. {
  141. bool result =
  142. (name != null) &&
  143. (name.Length <= MaxPath) &&
  144. (string.Compare(name, MakeValidName(name, '_'), StringComparison.Ordinal) == 0)
  145. ;
  146. return result;
  147. }
  148. /// <summary>
  149. /// Force a name to be valid by replacing invalid characters with a fixed value
  150. /// </summary>
  151. /// <param name="name">The name to make valid</param>
  152. /// <param name="replacement">The replacement character to use for any invalid characters.</param>
  153. /// <returns>Returns a valid name</returns>
  154. public static string MakeValidName(string name, char replacement)
  155. {
  156. if (name == null)
  157. {
  158. throw new ArgumentNullException(nameof(name));
  159. }
  160. name = WindowsPathUtils.DropPathRoot(name.Replace("/", Path.DirectorySeparatorChar.ToString()));
  161. // Drop any leading slashes.
  162. while ((name.Length > 0) && (name[0] == Path.DirectorySeparatorChar))
  163. {
  164. name = name.Remove(0, 1);
  165. }
  166. // Drop any trailing slashes.
  167. while ((name.Length > 0) && (name[name.Length - 1] == Path.DirectorySeparatorChar))
  168. {
  169. name = name.Remove(name.Length - 1, 1);
  170. }
  171. // Convert consecutive \\ characters to \
  172. int index = name.IndexOf(string.Format("{0}{0}", Path.DirectorySeparatorChar), StringComparison.Ordinal);
  173. while (index >= 0)
  174. {
  175. name = name.Remove(index, 1);
  176. index = name.IndexOf(string.Format("{0}{0}", Path.DirectorySeparatorChar), StringComparison.Ordinal);
  177. }
  178. // Convert any invalid characters using the replacement one.
  179. index = name.IndexOfAny(InvalidEntryChars);
  180. if (index >= 0)
  181. {
  182. var builder = new StringBuilder(name);
  183. while (index >= 0)
  184. {
  185. builder[index] = replacement;
  186. if (index >= name.Length)
  187. {
  188. index = -1;
  189. }
  190. else
  191. {
  192. index = name.IndexOfAny(InvalidEntryChars, index + 1);
  193. }
  194. }
  195. name = builder.ToString();
  196. }
  197. // Check for names greater than MaxPath characters.
  198. // TODO: Were is CLR version of MaxPath defined? Can't find it in Environment.
  199. if (name.Length > MaxPath)
  200. {
  201. throw new PathTooLongException();
  202. }
  203. return name;
  204. }
  205. /// <summary>
  206. /// Gets or set the character to replace invalid characters during transformations.
  207. /// </summary>
  208. public char Replacement
  209. {
  210. get { return _replacementChar; }
  211. set
  212. {
  213. for (int i = 0; i < InvalidEntryChars.Length; ++i)
  214. {
  215. if (InvalidEntryChars[i] == value)
  216. {
  217. throw new ArgumentException("invalid path character");
  218. }
  219. }
  220. if ((value == Path.DirectorySeparatorChar) || (value == Path.AltDirectorySeparatorChar))
  221. {
  222. throw new ArgumentException("invalid replacement character");
  223. }
  224. _replacementChar = value;
  225. }
  226. }
  227. }
  228. }