File Coverage

deps/libgit2/src/path.h
Criterion Covered Total %
statement 2 2 100.0
branch 1 8 12.5
condition n/a
subroutine n/a
pod n/a
total 3 10 30.0


line stmt bran cond sub pod time code
1             /*
2             * Copyright (C) the libgit2 contributors. All rights reserved.
3             *
4             * This file is part of libgit2, distributed under the GNU GPL v2 with
5             * a Linking Exception. For full terms see the included COPYING file.
6             */
7             #ifndef INCLUDE_path_h__
8             #define INCLUDE_path_h__
9              
10             #include "common.h"
11              
12             #include "posix.h"
13             #include "buffer.h"
14             #include "vector.h"
15              
16             #include "git2/sys/path.h"
17              
18             /**
19             * Path manipulation utils
20             *
21             * These are path utilities that munge paths without actually
22             * looking at the real filesystem.
23             */
24              
25             /*
26             * The dirname() function shall take a pointer to a character string
27             * that contains a pathname, and return a pointer to a string that is a
28             * pathname of the parent directory of that file. Trailing '/' characters
29             * in the path are not counted as part of the path.
30             *
31             * If path does not contain a '/', then dirname() shall return a pointer to
32             * the string ".". If path is a null pointer or points to an empty string,
33             * dirname() shall return a pointer to the string "." .
34             *
35             * The `git_path_dirname` implementation is thread safe. The returned
36             * string must be manually free'd.
37             *
38             * The `git_path_dirname_r` implementation writes the dirname to a `git_buf`
39             * if the buffer pointer is not NULL.
40             * It returns an error code < 0 if there is an allocation error, otherwise
41             * the length of the dirname (which will be > 0).
42             */
43             extern char *git_path_dirname(const char *path);
44             extern int git_path_dirname_r(git_buf *buffer, const char *path);
45              
46             /*
47             * This function returns the basename of the file, which is the last
48             * part of its full name given by fname, with the drive letter and
49             * leading directories stripped off. For example, the basename of
50             * c:/foo/bar/file.ext is file.ext, and the basename of a:foo is foo.
51             *
52             * Trailing slashes and backslashes are significant: the basename of
53             * c:/foo/bar/ is an empty string after the rightmost slash.
54             *
55             * The `git_path_basename` implementation is thread safe. The returned
56             * string must be manually free'd.
57             *
58             * The `git_path_basename_r` implementation writes the basename to a `git_buf`.
59             * It returns an error code < 0 if there is an allocation error, otherwise
60             * the length of the basename (which will be >= 0).
61             */
62             extern char *git_path_basename(const char *path);
63             extern int git_path_basename_r(git_buf *buffer, const char *path);
64              
65             /* Return the offset of the start of the basename. Unlike the other
66             * basename functions, this returns 0 if the path is empty.
67             */
68             extern size_t git_path_basename_offset(git_buf *buffer);
69              
70             extern const char *git_path_topdir(const char *path);
71              
72             /**
73             * Find offset to root of path if path has one.
74             *
75             * This will return a number >= 0 which is the offset to the start of the
76             * path, if the path is rooted (i.e. "/rooted/path" returns 0 and
77             * "c:/windows/rooted/path" returns 2). If the path is not rooted, this
78             * returns -1.
79             */
80             extern int git_path_root(const char *path);
81              
82             /**
83             * Ensure path has a trailing '/'.
84             */
85             extern int git_path_to_dir(git_buf *path);
86              
87             /**
88             * Ensure string has a trailing '/' if there is space for it.
89             */
90             extern void git_path_string_to_dir(char* path, size_t size);
91              
92             /**
93             * Taken from git.git; returns nonzero if the given path is "." or "..".
94             */
95             GIT_INLINE(int) git_path_is_dot_or_dotdot(const char *name)
96             {
97             return (name[0] == '.' &&
98             (name[1] == '\0' ||
99             (name[1] == '.' && name[2] == '\0')));
100             }
101              
102             #ifdef GIT_WIN32
103             GIT_INLINE(int) git_path_is_dot_or_dotdotW(const wchar_t *name)
104             {
105             return (name[0] == L'.' &&
106             (name[1] == L'\0' ||
107             (name[1] == L'.' && name[2] == L'\0')));
108             }
109              
110             #define git_path_is_absolute(p) \
111             (git__isalpha((p)[0]) && (p)[1] == ':' && ((p)[2] == '\\' || (p)[2] == '/'))
112              
113             #define git_path_is_dirsep(p) \
114             ((p) == '/' || (p) == '\\')
115              
116             /**
117             * Convert backslashes in path to forward slashes.
118             */
119             GIT_INLINE(void) git_path_mkposix(char *path)
120             {
121             while (*path) {
122             if (*path == '\\')
123             *path = '/';
124              
125             path++;
126             }
127             }
128             #else
129             # define git_path_mkposix(p) /* blank */
130              
131             #define git_path_is_absolute(p) \
132             ((p)[0] == '/')
133              
134             #define git_path_is_dirsep(p) \
135             ((p) == '/')
136              
137             #endif
138              
139             /**
140             * Check if string is a relative path (i.e. starts with "./" or "../")
141             */
142 4           GIT_INLINE(int) git_path_is_relative(const char *p)
143             {
144 4 50         return (p[0] == '.' && (p[1] == '/' || (p[1] == '.' && p[2] == '/')));
    0          
    0          
    0          
145             }
146              
147             /**
148             * Check if string is at end of path segment (i.e. looking at '/' or '\0')
149             */
150             GIT_INLINE(int) git_path_at_end_of_segment(const char *p)
151             {
152             return !*p || *p == '/';
153             }
154              
155             extern int git__percent_decode(git_buf *decoded_out, const char *input);
156              
157             /**
158             * Extract path from file:// URL.
159             */
160             extern int git_path_fromurl(git_buf *local_path_out, const char *file_url);
161              
162              
163             /**
164             * Path filesystem utils
165             *
166             * These are path utilities that actually access the filesystem.
167             */
168              
169             /**
170             * Check if a file exists and can be accessed.
171             * @return true or false
172             */
173             extern bool git_path_exists(const char *path);
174              
175             /**
176             * Check if the given path points to a directory.
177             * @return true or false
178             */
179             extern bool git_path_isdir(const char *path);
180              
181             /**
182             * Check if the given path points to a regular file.
183             * @return true or false
184             */
185             extern bool git_path_isfile(const char *path);
186              
187             /**
188             * Check if the given path points to a symbolic link.
189             * @return true or false
190             */
191             extern bool git_path_islink(const char *path);
192              
193             /**
194             * Check if the given path is a directory, and is empty.
195             */
196             extern bool git_path_is_empty_dir(const char *path);
197              
198             /**
199             * Stat a file and/or link and set error if needed.
200             */
201             extern int git_path_lstat(const char *path, struct stat *st);
202              
203             /**
204             * Check if the parent directory contains the item.
205             *
206             * @param dir Directory to check.
207             * @param item Item that might be in the directory.
208             * @return 0 if item exists in directory, <0 otherwise.
209             */
210             extern bool git_path_contains(git_buf *dir, const char *item);
211              
212             /**
213             * Check if the given path contains the given subdirectory.
214             *
215             * @param parent Directory path that might contain subdir
216             * @param subdir Subdirectory name to look for in parent
217             * @return true if subdirectory exists, false otherwise.
218             */
219             extern bool git_path_contains_dir(git_buf *parent, const char *subdir);
220              
221             /**
222             * Determine the common directory length between two paths, including
223             * the final path separator. For example, given paths 'a/b/c/1.txt
224             * and 'a/b/c/d/2.txt', the common directory is 'a/b/c/', and this
225             * will return the length of the string 'a/b/c/', which is 6.
226             *
227             * @param one The first path
228             * @param two The second path
229             * @return The length of the common directory
230             */
231             extern size_t git_path_common_dirlen(const char *one, const char *two);
232              
233             /**
234             * Make the path relative to the given parent path.
235             *
236             * @param path The path to make relative
237             * @param parent The parent path to make path relative to
238             * @return 0 if path was made relative, GIT_ENOTFOUND
239             * if there was not common root between the paths,
240             * or <0.
241             */
242             extern int git_path_make_relative(git_buf *path, const char *parent);
243              
244             /**
245             * Check if the given path contains the given file.
246             *
247             * @param dir Directory path that might contain file
248             * @param file File name to look for in parent
249             * @return true if file exists, false otherwise.
250             */
251             extern bool git_path_contains_file(git_buf *dir, const char *file);
252              
253             /**
254             * Prepend base to unrooted path or just copy path over.
255             *
256             * This will optionally return the index into the path where the "root"
257             * is, either the end of the base directory prefix or the path root.
258             */
259             extern int git_path_join_unrooted(
260             git_buf *path_out, const char *path, const char *base, ssize_t *root_at);
261              
262             /**
263             * Removes multiple occurrences of '/' in a row, squashing them into a
264             * single '/'.
265             */
266             extern void git_path_squash_slashes(git_buf *path);
267              
268             /**
269             * Clean up path, prepending base if it is not already rooted.
270             */
271             extern int git_path_prettify(git_buf *path_out, const char *path, const char *base);
272              
273             /**
274             * Clean up path, prepending base if it is not already rooted and
275             * appending a slash.
276             */
277             extern int git_path_prettify_dir(git_buf *path_out, const char *path, const char *base);
278              
279             /**
280             * Get a directory from a path.
281             *
282             * If path is a directory, this acts like `git_path_prettify_dir`
283             * (cleaning up path and appending a '/'). If path is a normal file,
284             * this prettifies it, then removed the filename a la dirname and
285             * appends the trailing '/'. If the path does not exist, it is
286             * treated like a regular filename.
287             */
288             extern int git_path_find_dir(git_buf *dir, const char *path, const char *base);
289              
290             /**
291             * Resolve relative references within a path.
292             *
293             * This eliminates "./" and "../" relative references inside a path,
294             * as well as condensing multiple slashes into single ones. It will
295             * not touch the path before the "ceiling" length.
296             *
297             * Additionally, this will recognize an "c:/" drive prefix or a "xyz://" URL
298             * prefix and not touch that part of the path.
299             */
300             extern int git_path_resolve_relative(git_buf *path, size_t ceiling);
301              
302             /**
303             * Apply a relative path to base path.
304             *
305             * Note that the base path could be a filename or a URL and this
306             * should still work. The relative path is walked segment by segment
307             * with three rules: series of slashes will be condensed to a single
308             * slash, "." will be eaten with no change, and ".." will remove a
309             * segment from the base path.
310             */
311             extern int git_path_apply_relative(git_buf *target, const char *relpath);
312              
313             enum {
314             GIT_PATH_DIR_IGNORE_CASE = (1u << 0),
315             GIT_PATH_DIR_PRECOMPOSE_UNICODE = (1u << 1),
316             GIT_PATH_DIR_INCLUDE_DOT_AND_DOTDOT = (1u << 2),
317             };
318              
319             /**
320             * Walk each directory entry, except '.' and '..', calling fn(state).
321             *
322             * @param pathbuf Buffer the function reads the initial directory
323             * path from, and updates with each successive entry's name.
324             * @param flags Combination of GIT_PATH_DIR flags.
325             * @param callback Callback for each entry. Passed the `payload` and each
326             * successive path inside the directory as a full path. This may
327             * safely append text to the pathbuf if needed. Return non-zero to
328             * cancel iteration (and return value will be propagated back).
329             * @param payload Passed to callback as first argument.
330             * @return 0 on success or error code from OS error or from callback
331             */
332             extern int git_path_direach(
333             git_buf *pathbuf,
334             uint32_t flags,
335             int (*callback)(void *payload, git_buf *path),
336             void *payload);
337              
338             /**
339             * Sort function to order two paths
340             */
341             extern int git_path_cmp(
342             const char *name1, size_t len1, int isdir1,
343             const char *name2, size_t len2, int isdir2,
344             int (*compare)(const char *, const char *, size_t));
345              
346             /**
347             * Invoke callback up path directory by directory until the ceiling is
348             * reached (inclusive of a final call at the root_path).
349             *
350             * Returning anything other than 0 from the callback function
351             * will stop the iteration and propagate the error to the caller.
352             *
353             * @param pathbuf Buffer the function reads the directory from and
354             * and updates with each successive name.
355             * @param ceiling Prefix of path at which to stop walking up. If NULL,
356             * this will walk all the way up to the root. If not a prefix of
357             * pathbuf, the callback will be invoked a single time on the
358             * original input path.
359             * @param callback Function to invoke on each path. Passed the `payload`
360             * and the buffer containing the current path. The path should not
361             * be modified in any way. Return non-zero to stop iteration.
362             * @param payload Passed to fn as the first ath.
363             */
364             extern int git_path_walk_up(
365             git_buf *pathbuf,
366             const char *ceiling,
367             int (*callback)(void *payload, const char *path),
368             void *payload);
369              
370              
371             enum { GIT_PATH_NOTEQUAL = 0, GIT_PATH_EQUAL = 1, GIT_PATH_PREFIX = 2 };
372              
373             /*
374             * Determines if a path is equal to or potentially a child of another.
375             * @param parent The possible parent
376             * @param child The possible child
377             */
378             GIT_INLINE(int) git_path_equal_or_prefixed(
379             const char *parent,
380             const char *child,
381             ssize_t *prefixlen)
382             {
383             const char *p = parent, *c = child;
384             int lastslash = 0;
385              
386             while (*p && *c) {
387             lastslash = (*p == '/');
388              
389             if (*p++ != *c++)
390             return GIT_PATH_NOTEQUAL;
391             }
392              
393             if (*p != '\0')
394             return GIT_PATH_NOTEQUAL;
395              
396             if (*c == '\0') {
397             if (prefixlen)
398             *prefixlen = p - parent;
399              
400             return GIT_PATH_EQUAL;
401             }
402              
403             if (*c == '/' || lastslash) {
404             if (prefixlen)
405             *prefixlen = (p - parent) - lastslash;
406              
407             return GIT_PATH_PREFIX;
408             }
409              
410             return GIT_PATH_NOTEQUAL;
411             }
412              
413             /* translate errno to libgit2 error code and set error message */
414             extern int git_path_set_error(
415             int errno_value, const char *path, const char *action);
416              
417             /* check if non-ascii characters are present in filename */
418             extern bool git_path_has_non_ascii(const char *path, size_t pathlen);
419              
420             #define GIT_PATH_REPO_ENCODING "UTF-8"
421              
422             #ifdef __APPLE__
423             #define GIT_PATH_NATIVE_ENCODING "UTF-8-MAC"
424             #else
425             #define GIT_PATH_NATIVE_ENCODING "UTF-8"
426             #endif
427              
428             #ifdef GIT_USE_ICONV
429              
430             #include
431              
432             typedef struct {
433             iconv_t map;
434             git_buf buf;
435             } git_path_iconv_t;
436              
437             #define GIT_PATH_ICONV_INIT { (iconv_t)-1, GIT_BUF_INIT }
438              
439             /* Init iconv data for converting decomposed UTF-8 to precomposed */
440             extern int git_path_iconv_init_precompose(git_path_iconv_t *ic);
441              
442             /* Clear allocated iconv data */
443             extern void git_path_iconv_clear(git_path_iconv_t *ic);
444              
445             /*
446             * Rewrite `in` buffer using iconv map if necessary, replacing `in`
447             * pointer internal iconv buffer if rewrite happened. The `in` pointer
448             * will be left unchanged if no rewrite was needed.
449             */
450             extern int git_path_iconv(git_path_iconv_t *ic, const char **in, size_t *inlen);
451              
452             #endif /* GIT_USE_ICONV */
453              
454             extern bool git_path_does_fs_decompose_unicode(const char *root);
455              
456              
457             typedef struct git_path_diriter git_path_diriter;
458              
459             #if defined(GIT_WIN32) && !defined(__MINGW32__)
460              
461             struct git_path_diriter
462             {
463             git_win32_path path;
464             size_t parent_len;
465              
466             git_buf path_utf8;
467             size_t parent_utf8_len;
468              
469             HANDLE handle;
470              
471             unsigned int flags;
472              
473             WIN32_FIND_DATAW current;
474             unsigned int needs_next;
475             };
476              
477             #define GIT_PATH_DIRITER_INIT { {0}, 0, GIT_BUF_INIT, 0, INVALID_HANDLE_VALUE }
478              
479             #else
480              
481             struct git_path_diriter
482             {
483             git_buf path;
484             size_t parent_len;
485              
486             unsigned int flags;
487              
488             DIR *dir;
489              
490             #ifdef GIT_USE_ICONV
491             git_path_iconv_t ic;
492             #endif
493             };
494              
495             #define GIT_PATH_DIRITER_INIT { GIT_BUF_INIT }
496              
497             #endif
498              
499             /**
500             * Initialize a directory iterator.
501             *
502             * @param diriter Pointer to a diriter structure that will be setup.
503             * @param path The path that will be iterated over
504             * @param flags Directory reader flags
505             * @return 0 or an error code
506             */
507             extern int git_path_diriter_init(
508             git_path_diriter *diriter,
509             const char *path,
510             unsigned int flags);
511              
512             /**
513             * Advance the directory iterator. Will return GIT_ITEROVER when
514             * the iteration has completed successfully.
515             *
516             * @param diriter The directory iterator
517             * @return 0, GIT_ITEROVER, or an error code
518             */
519             extern int git_path_diriter_next(git_path_diriter *diriter);
520              
521             /**
522             * Returns the file name of the current item in the iterator.
523             *
524             * @param out Pointer to store the path in
525             * @param out_len Pointer to store the length of the path in
526             * @param diriter The directory iterator
527             * @return 0 or an error code
528             */
529             extern int git_path_diriter_filename(
530             const char **out,
531             size_t *out_len,
532             git_path_diriter *diriter);
533              
534             /**
535             * Returns the full path of the current item in the iterator; that
536             * is the current filename plus the path of the directory that the
537             * iterator was constructed with.
538             *
539             * @param out Pointer to store the path in
540             * @param out_len Pointer to store the length of the path in
541             * @param diriter The directory iterator
542             * @return 0 or an error code
543             */
544             extern int git_path_diriter_fullpath(
545             const char **out,
546             size_t *out_len,
547             git_path_diriter *diriter);
548              
549             /**
550             * Performs an `lstat` on the current item in the iterator.
551             *
552             * @param out Pointer to store the stat data in
553             * @param diriter The directory iterator
554             * @return 0 or an error code
555             */
556             extern int git_path_diriter_stat(struct stat *out, git_path_diriter *diriter);
557              
558             /**
559             * Closes the directory iterator.
560             *
561             * @param diriter The directory iterator
562             */
563             extern void git_path_diriter_free(git_path_diriter *diriter);
564              
565             /**
566             * Load all directory entries (except '.' and '..') into a vector.
567             *
568             * For cases where `git_path_direach()` is not appropriate, this
569             * allows you to load the filenames in a directory into a vector
570             * of strings. That vector can then be sorted, iterated, or whatever.
571             * Remember to free alloc of the allocated strings when you are done.
572             *
573             * @param contents Vector to fill with directory entry names.
574             * @param path The directory to read from.
575             * @param prefix_len When inserting entries, the trailing part of path
576             * will be prefixed after this length. I.e. given path "/a/b" and
577             * prefix_len 3, the entries will look like "b/e1", "b/e2", etc.
578             * @param flags Combination of GIT_PATH_DIR flags.
579             */
580             extern int git_path_dirload(
581             git_vector *contents,
582             const char *path,
583             size_t prefix_len,
584             uint32_t flags);
585              
586              
587             /* Used for paths to repositories on the filesystem */
588             extern bool git_path_is_local_file_url(const char *file_url);
589             extern int git_path_from_url_or_path(git_buf *local_path_out, const char *url_or_path);
590              
591             /* Flags to determine path validity in `git_path_isvalid` */
592             #define GIT_PATH_REJECT_TRAVERSAL (1 << 0)
593             #define GIT_PATH_REJECT_DOT_GIT (1 << 1)
594             #define GIT_PATH_REJECT_SLASH (1 << 2)
595             #define GIT_PATH_REJECT_BACKSLASH (1 << 3)
596             #define GIT_PATH_REJECT_TRAILING_DOT (1 << 4)
597             #define GIT_PATH_REJECT_TRAILING_SPACE (1 << 5)
598             #define GIT_PATH_REJECT_TRAILING_COLON (1 << 6)
599             #define GIT_PATH_REJECT_DOS_PATHS (1 << 7)
600             #define GIT_PATH_REJECT_NT_CHARS (1 << 8)
601             #define GIT_PATH_REJECT_DOT_GIT_LITERAL (1 << 9)
602             #define GIT_PATH_REJECT_DOT_GIT_HFS (1 << 10)
603             #define GIT_PATH_REJECT_DOT_GIT_NTFS (1 << 11)
604              
605             /* Default path safety for writing files to disk: since we use the
606             * Win32 "File Namespace" APIs ("\\?\") we need to protect from
607             * paths that the normal Win32 APIs would not write.
608             */
609             #ifdef GIT_WIN32
610             # define GIT_PATH_REJECT_FILESYSTEM_DEFAULTS \
611             GIT_PATH_REJECT_TRAVERSAL | \
612             GIT_PATH_REJECT_BACKSLASH | \
613             GIT_PATH_REJECT_TRAILING_DOT | \
614             GIT_PATH_REJECT_TRAILING_SPACE | \
615             GIT_PATH_REJECT_TRAILING_COLON | \
616             GIT_PATH_REJECT_DOS_PATHS | \
617             GIT_PATH_REJECT_NT_CHARS
618             #else
619             # define GIT_PATH_REJECT_FILESYSTEM_DEFAULTS \
620             GIT_PATH_REJECT_TRAVERSAL
621             #endif
622              
623             /* Paths that should never be written into the working directory. */
624             #define GIT_PATH_REJECT_WORKDIR_DEFAULTS \
625             GIT_PATH_REJECT_FILESYSTEM_DEFAULTS | GIT_PATH_REJECT_DOT_GIT
626              
627             /* Paths that should never be written to the index. */
628             #define GIT_PATH_REJECT_INDEX_DEFAULTS \
629             GIT_PATH_REJECT_TRAVERSAL | GIT_PATH_REJECT_DOT_GIT
630              
631             /*
632             * Determine whether a path is a valid git path or not - this must not contain
633             * a '.' or '..' component, or a component that is ".git" (in any case).
634             *
635             * `repo` is optional. If specified, it will be used to determine the short
636             * path name to reject (if `GIT_PATH_REJECT_DOS_SHORTNAME` is specified),
637             * in addition to the default of "git~1".
638             */
639             extern bool git_path_isvalid(
640             git_repository *repo,
641             const char *path,
642             uint16_t mode,
643             unsigned int flags);
644              
645             /**
646             * Convert any backslashes into slashes
647             */
648             int git_path_normalize_slashes(git_buf *out, const char *path);
649              
650             bool git_path_supports_symlinks(const char *dir);
651              
652             /**
653             * Validate a system file's ownership
654             *
655             * Verify that the file in question is owned by an administrator or system
656             * account, or at least by the current user.
657             *
658             * This function returns 0 if successful. If the file is not owned by any of
659             * these, or any other if there have been problems determining the file
660             * ownership, it returns -1.
661             */
662             int git_path_validate_system_file_ownership(const char *path);
663              
664             #endif