1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // FilePath is a container for pathnames stored in a platform's native string
6 // type, providing containers for manipulation in according with the
7 // platform's conventions for pathnames.  It supports the following path
8 // types:
9 //
10 //                   POSIX            Windows
11 //                   ---------------  ----------------------------------
12 // Fundamental type  char[]           wchar_t[]
13 // Encoding          unspecified*     UTF-16
14 // Separator         /                \, tolerant of /
15 // Drive letters     no               case-insensitive A-Z followed by :
16 // Alternate root    // (surprise!)   \\, for UNC paths
17 //
18 // * The encoding need not be specified on POSIX systems, although some
19 //   POSIX-compliant systems do specify an encoding.  Mac OS X uses UTF-8.
20 //   Chrome OS also uses UTF-8.
21 //   Linux does not specify an encoding, but in practice, the locale's
22 //   character set may be used.
23 //
24 // For more arcane bits of path trivia, see below.
25 //
26 // FilePath objects are intended to be used anywhere paths are.  An
27 // application may pass FilePath objects around internally, masking the
28 // underlying differences between systems, only differing in implementation
29 // where interfacing directly with the system.  For example, a single
30 // OpenFile(const FilePath &) function may be made available, allowing all
31 // callers to operate without regard to the underlying implementation.  On
32 // POSIX-like platforms, OpenFile might wrap fopen, and on Windows, it might
33 // wrap _wfopen_s, perhaps both by calling file_path.value().c_str().  This
34 // allows each platform to pass pathnames around without requiring conversions
35 // between encodings, which has an impact on performance, but more imporantly,
36 // has an impact on correctness on platforms that do not have well-defined
37 // encodings for pathnames.
38 //
39 // Several methods are available to perform common operations on a FilePath
40 // object, such as determining the parent directory (DirName), isolating the
41 // final path component (BaseName), and appending a relative pathname string
42 // to an existing FilePath object (Append).  These methods are highly
43 // recommended over attempting to split and concatenate strings directly.
44 // These methods are based purely on string manipulation and knowledge of
45 // platform-specific pathname conventions, and do not consult the filesystem
46 // at all, making them safe to use without fear of blocking on I/O operations.
47 // These methods do not function as mutators but instead return distinct
48 // instances of FilePath objects, and are therefore safe to use on const
49 // objects.  The objects themselves are safe to share between threads.
50 //
51 // To aid in initialization of FilePath objects from string literals, a
52 // FILE_PATH_LITERAL macro is provided, which accounts for the difference
53 // between char[]-based pathnames on POSIX systems and wchar_t[]-based
54 // pathnames on Windows.
55 //
56 // As a precaution against premature truncation, paths can't contain NULs.
57 //
58 // Because a FilePath object should not be instantiated at the global scope,
59 // instead, use a FilePath::CharType[] and initialize it with
60 // FILE_PATH_LITERAL.  At runtime, a FilePath object can be created from the
61 // character array.  Example:
62 //
63 // | const FilePath::CharType kLogFileName[] = FILE_PATH_LITERAL("log.txt");
64 // |
65 // | void Function() {
66 // |   FilePath log_file_path(kLogFileName);
67 // |   [...]
68 // | }
69 //
70 // WARNING: FilePaths should ALWAYS be displayed with LTR directionality, even
71 // when the UI language is RTL. This means you always need to pass filepaths
72 // through base::i18n::WrapPathWithLTRFormatting() before displaying it in the
73 // RTL UI.
74 //
75 // This is a very common source of bugs, please try to keep this in mind.
76 //
77 // ARCANE BITS OF PATH TRIVIA
78 //
79 //  - A double leading slash is actually part of the POSIX standard.  Systems
80 //    are allowed to treat // as an alternate root, as Windows does for UNC
81 //    (network share) paths.  Most POSIX systems don't do anything special
82 //    with two leading slashes, but FilePath handles this case properly
83 //    in case it ever comes across such a system.  FilePath needs this support
84 //    for Windows UNC paths, anyway.
85 //    References:
86 //    The Open Group Base Specifications Issue 7, sections 3.267 ("Pathname")
87 //    and 4.12 ("Pathname Resolution"), available at:
88 //    http://www.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_267
89 //    http://www.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_12
90 //
91 //  - Windows treats c:\\ the same way it treats \\.  This was intended to
92 //    allow older applications that require drive letters to support UNC paths
93 //    like \\server\share\path, by permitting c:\\server\share\path as an
94 //    equivalent.  Since the OS treats these paths specially, FilePath needs
95 //    to do the same.  Since Windows can use either / or \ as the separator,
96 //    FilePath treats c://, c:\\, //, and \\ all equivalently.
97 //    Reference:
98 //    The Old New Thing, "Why is a drive letter permitted in front of UNC
99 //    paths (sometimes)?", available at:
100 //    http://blogs.msdn.com/oldnewthing/archive/2005/11/22/495740.aspx
101 
102 #ifndef BASE_FILES_FILE_PATH_H_
103 #define BASE_FILES_FILE_PATH_H_
104 
105 #include <stddef.h>
106 
107 #include <functional>
108 #include <iosfwd>
109 #include <string>
110 #include <vector>
111 
112 #include "base/base_export.h"
113 #include "base/compiler_specific.h"
114 #include "base/stl_util.h"
115 #include "base/strings/string16.h"
116 #include "base/strings/string_piece.h"
117 #include "build/build_config.h"
118 
119 // Windows-style drive letter support and pathname separator characters can be
120 // enabled and disabled independently, to aid testing.  These #defines are
121 // here so that the same setting can be used in both the implementation and
122 // in the unit test.
123 #if defined(OS_WIN)
124 #define FILE_PATH_USES_DRIVE_LETTERS
125 #define FILE_PATH_USES_WIN_SEPARATORS
126 #endif  // OS_WIN
127 
128 // To print path names portably use PRFilePath (based on PRIuS and friends from
129 // C99 and format_macros.h) like this:
130 // base::StringPrintf("Path is %" PRFilePath ".\n", path.value().c_str());
131 #if defined(OS_WIN)
132 #define PRFilePath "ls"
133 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
134 #define PRFilePath "s"
135 #endif  // OS_WIN
136 
137 // Macros for string literal initialization of FilePath::CharType[].
138 #if defined(OS_WIN)
139 #define FILE_PATH_LITERAL(x) L##x
140 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
141 #define FILE_PATH_LITERAL(x) x
142 #endif  // OS_WIN
143 
144 namespace base {
145 
146 class Pickle;
147 class PickleIterator;
148 
149 // An abstraction to isolate users from the differences between native
150 // pathnames on different platforms.
151 class BASE_EXPORT FilePath {
152  public:
153 #if defined(OS_WIN)
154   // On Windows, for Unicode-aware applications, native pathnames are wchar_t
155   // arrays encoded in UTF-16.
156   typedef std::wstring StringType;
157 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
158   // On most platforms, native pathnames are char arrays, and the encoding
159   // may or may not be specified.  On Mac OS X, native pathnames are encoded
160   // in UTF-8.
161   typedef std::string StringType;
162 #endif  // OS_WIN
163 
164   typedef BasicStringPiece<StringType> StringPieceType;
165   typedef StringType::value_type CharType;
166 
167   // Null-terminated array of separators used to separate components in
168   // hierarchical paths.  Each character in this array is a valid separator,
169   // but kSeparators[0] is treated as the canonical separator and will be used
170   // when composing pathnames.
171   static const CharType kSeparators[];
172 
173   // base::size(kSeparators).
174   static const size_t kSeparatorsLength;
175 
176   // A special path component meaning "this directory."
177   static const CharType kCurrentDirectory[];
178 
179   // A special path component meaning "the parent directory."
180   static const CharType kParentDirectory[];
181 
182   // The character used to identify a file extension.
183   static const CharType kExtensionSeparator;
184 
185   FilePath();
186   FilePath(const FilePath& that);
187   explicit FilePath(StringPieceType path);
188   ~FilePath();
189   FilePath& operator=(const FilePath& that);
190 
191   // Constructs FilePath with the contents of |that|, which is left in valid but
192   // unspecified state.
193   FilePath(FilePath&& that) noexcept;
194   // Replaces the contents with those of |that|, which is left in valid but
195   // unspecified state.
196   FilePath& operator=(FilePath&& that);
197 
198   bool operator==(const FilePath& that) const;
199 
200   bool operator!=(const FilePath& that) const;
201 
202   // Required for some STL containers and operations
203   bool operator<(const FilePath& that) const {
204     return path_ < that.path_;
205   }
206 
value()207   const StringType& value() const { return path_; }
208 
empty()209   bool empty() const { return path_.empty(); }
210 
clear()211   void clear() { path_.clear(); }
212 
213   // Returns true if |character| is in kSeparators.
214   static bool IsSeparator(CharType character);
215 
216   // Returns a vector of all of the components of the provided path. It is
217   // equivalent to calling DirName().value() on the path's root component,
218   // and BaseName().value() on each child component.
219   //
220   // To make sure this is lossless so we can differentiate absolute and
221   // relative paths, the root slash will be included even though no other
222   // slashes will be. The precise behavior is:
223   //
224   // Posix:  "/foo/bar"  ->  [ "/", "foo", "bar" ]
225   // Windows:  "C:\foo\bar"  ->  [ "C:", "\\", "foo", "bar" ]
226   void GetComponents(std::vector<FilePath::StringType>* components) const;
227 
228   // Returns true if this FilePath is a parent or ancestor of the |child|.
229   // Absolute and relative paths are accepted i.e. /foo is a parent to /foo/bar,
230   // and foo is a parent to foo/bar. Any ancestor is considered a parent i.e. /a
231   // is a parent to both /a/b and /a/b/c.  Does not convert paths to absolute,
232   // follow symlinks or directory navigation (e.g. ".."). A path is *NOT* its
233   // own parent.
234   bool IsParent(const FilePath& child) const;
235 
236   // If IsParent(child) holds, appends to path (if non-NULL) the
237   // relative path to child and returns true.  For example, if parent
238   // holds "/Users/johndoe/Library/Application Support", child holds
239   // "/Users/johndoe/Library/Application Support/Google/Chrome/Default", and
240   // *path holds "/Users/johndoe/Library/Caches", then after
241   // parent.AppendRelativePath(child, path) is called *path will hold
242   // "/Users/johndoe/Library/Caches/Google/Chrome/Default".  Otherwise,
243   // returns false.
244   bool AppendRelativePath(const FilePath& child, FilePath* path) const;
245 
246   // Returns a FilePath corresponding to the directory containing the path
247   // named by this object, stripping away the file component.  If this object
248   // only contains one component, returns a FilePath identifying
249   // kCurrentDirectory.  If this object already refers to the root directory,
250   // returns a FilePath identifying the root directory. Please note that this
251   // doesn't resolve directory navigation, e.g. the result for "../a" is "..".
252   FilePath DirName() const WARN_UNUSED_RESULT;
253 
254   // Returns a FilePath corresponding to the last path component of this
255   // object, either a file or a directory.  If this object already refers to
256   // the root directory, returns a FilePath identifying the root directory;
257   // this is the only situation in which BaseName will return an absolute path.
258   FilePath BaseName() const WARN_UNUSED_RESULT;
259 
260   // Returns ".jpg" for path "C:\pics\jojo.jpg", or an empty string if
261   // the file has no extension.  If non-empty, Extension() will always start
262   // with precisely one ".".  The following code should always work regardless
263   // of the value of path.  For common double-extensions like .tar.gz and
264   // .user.js, this method returns the combined extension.  For a single
265   // component, use FinalExtension().
266   // new_path = path.RemoveExtension().value().append(path.Extension());
267   // ASSERT(new_path == path.value());
268   // NOTE: this is different from the original file_util implementation which
269   // returned the extension without a leading "." ("jpg" instead of ".jpg")
270   StringType Extension() const WARN_UNUSED_RESULT;
271 
272   // Returns the path's file extension, as in Extension(), but will
273   // never return a double extension.
274   //
275   // TODO(davidben): Check all our extension-sensitive code to see if
276   // we can rename this to Extension() and the other to something like
277   // LongExtension(), defaulting to short extensions and leaving the
278   // long "extensions" to logic like base::GetUniquePathNumber().
279   StringType FinalExtension() const WARN_UNUSED_RESULT;
280 
281   // Returns "C:\pics\jojo" for path "C:\pics\jojo.jpg"
282   // NOTE: this is slightly different from the similar file_util implementation
283   // which returned simply 'jojo'.
284   FilePath RemoveExtension() const WARN_UNUSED_RESULT;
285 
286   // Removes the path's file extension, as in RemoveExtension(), but
287   // ignores double extensions.
288   FilePath RemoveFinalExtension() const WARN_UNUSED_RESULT;
289 
290   // Inserts |suffix| after the file name portion of |path| but before the
291   // extension.  Returns "" if BaseName() == "." or "..".
292   // Examples:
293   // path == "C:\pics\jojo.jpg" suffix == " (1)", returns "C:\pics\jojo (1).jpg"
294   // path == "jojo.jpg"         suffix == " (1)", returns "jojo (1).jpg"
295   // path == "C:\pics\jojo"     suffix == " (1)", returns "C:\pics\jojo (1)"
296   // path == "C:\pics.old\jojo" suffix == " (1)", returns "C:\pics.old\jojo (1)"
297   FilePath InsertBeforeExtension(
298       StringPieceType suffix) const WARN_UNUSED_RESULT;
299   FilePath InsertBeforeExtensionASCII(
300       StringPiece suffix) const WARN_UNUSED_RESULT;
301 
302   // Adds |extension| to |file_name|. Returns the current FilePath if
303   // |extension| is empty. Returns "" if BaseName() == "." or "..".
304   FilePath AddExtension(StringPieceType extension) const WARN_UNUSED_RESULT;
305 
306   // Like above, but takes the extension as an ASCII string. See AppendASCII for
307   // details on how this is handled.
308   FilePath AddExtensionASCII(StringPiece extension) const WARN_UNUSED_RESULT;
309 
310   // Replaces the extension of |file_name| with |extension|.  If |file_name|
311   // does not have an extension, then |extension| is added.  If |extension| is
312   // empty, then the extension is removed from |file_name|.
313   // Returns "" if BaseName() == "." or "..".
314   FilePath ReplaceExtension(StringPieceType extension) const WARN_UNUSED_RESULT;
315 
316   // Returns true if the file path matches the specified extension. The test is
317   // case insensitive. Don't forget the leading period if appropriate.
318   bool MatchesExtension(StringPieceType extension) const;
319 
320   // Returns a FilePath by appending a separator and the supplied path
321   // component to this object's path.  Append takes care to avoid adding
322   // excessive separators if this object's path already ends with a separator.
323   // If this object's path is kCurrentDirectory, a new FilePath corresponding
324   // only to |component| is returned.  |component| must be a relative path;
325   // it is an error to pass an absolute path.
326   FilePath Append(StringPieceType component) const WARN_UNUSED_RESULT;
327   FilePath Append(const FilePath& component) const WARN_UNUSED_RESULT;
328 
329   // Although Windows StringType is std::wstring, since the encoding it uses for
330   // paths is well defined, it can handle ASCII path components as well.
331   // Mac uses UTF8, and since ASCII is a subset of that, it works there as well.
332   // On Linux, although it can use any 8-bit encoding for paths, we assume that
333   // ASCII is a valid subset, regardless of the encoding, since many operating
334   // system paths will always be ASCII.
335   FilePath AppendASCII(StringPiece component) const WARN_UNUSED_RESULT;
336 
337   // Returns true if this FilePath contains an absolute path.  On Windows, an
338   // absolute path begins with either a drive letter specification followed by
339   // a separator character, or with two separator characters.  On POSIX
340   // platforms, an absolute path begins with a separator character.
341   bool IsAbsolute() const;
342 
343   // Returns true if the patch ends with a path separator character.
344   bool EndsWithSeparator() const WARN_UNUSED_RESULT;
345 
346   // Returns a copy of this FilePath that ends with a trailing separator. If
347   // the input path is empty, an empty FilePath will be returned.
348   FilePath AsEndingWithSeparator() const WARN_UNUSED_RESULT;
349 
350   // Returns a copy of this FilePath that does not end with a trailing
351   // separator.
352   FilePath StripTrailingSeparators() const WARN_UNUSED_RESULT;
353 
354   // Returns true if this FilePath contains an attempt to reference a parent
355   // directory (e.g. has a path component that is "..").
356   bool ReferencesParent() const;
357 
358   // Return a Unicode human-readable version of this path.
359   // Warning: you can *not*, in general, go from a display name back to a real
360   // path.  Only use this when displaying paths to users, not just when you
361   // want to stuff a string16 into some other API.
362   string16 LossyDisplayName() const;
363 
364   // Return the path as ASCII, or the empty string if the path is not ASCII.
365   // This should only be used for cases where the FilePath is representing a
366   // known-ASCII filename.
367   std::string MaybeAsASCII() const;
368 
369   // Return the path as UTF-8.
370   //
371   // This function is *unsafe* as there is no way to tell what encoding is
372   // used in file names on POSIX systems other than Mac and Chrome OS,
373   // although UTF-8 is practically used everywhere these days. To mitigate
374   // the encoding issue, this function internally calls
375   // SysNativeMBToWide() on POSIX systems other than Mac and Chrome OS,
376   // per assumption that the current locale's encoding is used in file
377   // names, but this isn't a perfect solution.
378   //
379   // Once it becomes safe to to stop caring about non-UTF-8 file names,
380   // the SysNativeMBToWide() hack will be removed from the code, along
381   // with "Unsafe" in the function name.
382   std::string AsUTF8Unsafe() const;
383 
384   // Similar to AsUTF8Unsafe, but returns UTF-16 instead.
385   string16 AsUTF16Unsafe() const;
386 
387   // Returns a FilePath object from a path name in UTF-8. This function
388   // should only be used for cases where you are sure that the input
389   // string is UTF-8.
390   //
391   // Like AsUTF8Unsafe(), this function is unsafe. This function
392   // internally calls SysWideToNativeMB() on POSIX systems other than Mac
393   // and Chrome OS, to mitigate the encoding issue. See the comment at
394   // AsUTF8Unsafe() for details.
395   static FilePath FromUTF8Unsafe(StringPiece utf8);
396 
397   // Similar to FromUTF8Unsafe, but accepts UTF-16 instead.
398   static FilePath FromUTF16Unsafe(StringPiece16 utf16);
399 
400   void WriteToPickle(Pickle* pickle) const;
401   bool ReadFromPickle(PickleIterator* iter);
402 
403   // Normalize all path separators to backslash on Windows
404   // (if FILE_PATH_USES_WIN_SEPARATORS is true), or do nothing on POSIX systems.
405   FilePath NormalizePathSeparators() const;
406 
407   // Normalize all path separattors to given type on Windows
408   // (if FILE_PATH_USES_WIN_SEPARATORS is true), or do nothing on POSIX systems.
409   FilePath NormalizePathSeparatorsTo(CharType separator) const;
410 
411   // Compare two strings in the same way the file system does.
412   // Note that these always ignore case, even on file systems that are case-
413   // sensitive. If case-sensitive comparison is ever needed, add corresponding
414   // methods here.
415   // The methods are written as a static method so that they can also be used
416   // on parts of a file path, e.g., just the extension.
417   // CompareIgnoreCase() returns -1, 0 or 1 for less-than, equal-to and
418   // greater-than respectively.
419   static int CompareIgnoreCase(StringPieceType string1,
420                                StringPieceType string2);
CompareEqualIgnoreCase(StringPieceType string1,StringPieceType string2)421   static bool CompareEqualIgnoreCase(StringPieceType string1,
422                                      StringPieceType string2) {
423     return CompareIgnoreCase(string1, string2) == 0;
424   }
CompareLessIgnoreCase(StringPieceType string1,StringPieceType string2)425   static bool CompareLessIgnoreCase(StringPieceType string1,
426                                     StringPieceType string2) {
427     return CompareIgnoreCase(string1, string2) < 0;
428   }
429 
430 #if defined(OS_MACOSX)
431   // Returns the string in the special canonical decomposed form as defined for
432   // HFS, which is close to, but not quite, decomposition form D. See
433   // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#UnicodeSubtleties
434   // for further comments.
435   // Returns the epmty string if the conversion failed.
436   static StringType GetHFSDecomposedForm(StringPieceType string);
437 
438   // Special UTF-8 version of FastUnicodeCompare. Cf:
439   // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#StringComparisonAlgorithm
440   // IMPORTANT: The input strings must be in the special HFS decomposed form!
441   // (cf. above GetHFSDecomposedForm method)
442   static int HFSFastUnicodeCompare(StringPieceType string1,
443                                    StringPieceType string2);
444 #endif
445 
446 #if defined(OS_ANDROID)
447   // On android, file selection dialog can return a file with content uri
448   // scheme(starting with content://). Content uri needs to be opened with
449   // ContentResolver to guarantee that the app has appropriate permissions
450   // to access it.
451   // Returns true if the path is a content uri, or false otherwise.
452   bool IsContentUri() const;
453 #endif
454 
455  private:
456   // Remove trailing separators from this object.  If the path is absolute, it
457   // will never be stripped any more than to refer to the absolute root
458   // directory, so "////" will become "/", not "".  A leading pair of
459   // separators is never stripped, to support alternate roots.  This is used to
460   // support UNC paths on Windows.
461   void StripTrailingSeparatorsInternal();
462 
463   StringType path_;
464 };
465 
466 BASE_EXPORT std::ostream& operator<<(std::ostream& out,
467                                      const FilePath& file_path);
468 
469 }  // namespace base
470 
471 namespace std {
472 
473 template <>
474 struct hash<base::FilePath> {
475   typedef base::FilePath argument_type;
476   typedef std::size_t result_type;
477   result_type operator()(argument_type const& f) const {
478     return hash<base::FilePath::StringType>()(f.value());
479   }
480 };
481 
482 }  // namespace std
483 
484 #endif  // BASE_FILES_FILE_PATH_H_
485