WindowsNameTransform.cs 7.3 KB

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