2 * I'm tired of doing "vsnprintf()" etc just to open a
3 * file, so here's a "return static buffer with printf"
6 * It's obviously not thread-safe. Sue me. But it's quite
7 * useful for doing things like
9 * f = open(mkpath("%s/%s.git", base, name), O_RDONLY);
11 * which is what it's designed for.
15 #include "string-list.h"
17 static char bad_path
[] = "/bad-path/";
19 static char *get_pathname(void)
21 static char pathname_array
[4][PATH_MAX
];
23 return pathname_array
[3 & ++index
];
26 static char *cleanup_path(char *path
)
29 if (!memcmp(path
, "./", 2)) {
37 char *mksnpath(char *buf
, size_t n
, const char *fmt
, ...)
43 len
= vsnprintf(buf
, n
, fmt
, args
);
46 strlcpy(buf
, bad_path
, n
);
49 return cleanup_path(buf
);
52 static char *vsnpath(char *buf
, size_t n
, const char *fmt
, va_list args
)
54 const char *git_dir
= get_git_dir();
57 len
= strlen(git_dir
);
60 memcpy(buf
, git_dir
, len
);
61 if (len
&& !is_dir_sep(git_dir
[len
-1]))
63 len
+= vsnprintf(buf
+ len
, n
- len
, fmt
, args
);
66 return cleanup_path(buf
);
68 strlcpy(buf
, bad_path
, n
);
72 char *git_snpath(char *buf
, size_t n
, const char *fmt
, ...)
77 ret
= vsnpath(buf
, n
, fmt
, args
);
82 char *git_pathdup(const char *fmt
, ...)
84 char path
[PATH_MAX
], *ret
;
87 ret
= vsnpath(path
, sizeof(path
), fmt
, args
);
92 char *mkpathdup(const char *fmt
, ...)
95 struct strbuf sb
= STRBUF_INIT
;
99 strbuf_vaddf(&sb
, fmt
, args
);
101 path
= xstrdup(cleanup_path(sb
.buf
));
107 char *mkpath(const char *fmt
, ...)
111 char *pathname
= get_pathname();
114 len
= vsnprintf(pathname
, PATH_MAX
, fmt
, args
);
118 return cleanup_path(pathname
);
121 char *git_path(const char *fmt
, ...)
123 char *pathname
= get_pathname();
128 ret
= vsnpath(pathname
, PATH_MAX
, fmt
, args
);
133 void home_config_paths(char **global
, char **xdg
, char *file
)
135 char *xdg_home
= getenv("XDG_CONFIG_HOME");
136 char *home
= getenv("HOME");
137 char *to_free
= NULL
;
144 to_free
= mkpathdup("%s/.config", home
);
148 *global
= mkpathdup("%s/.gitconfig", home
);
154 *xdg
= mkpathdup("%s/git/%s", xdg_home
, file
);
159 char *git_path_submodule(const char *path
, const char *fmt
, ...)
161 char *pathname
= get_pathname();
162 struct strbuf buf
= STRBUF_INIT
;
168 if (len
> PATH_MAX
-100)
171 strbuf_addstr(&buf
, path
);
172 if (len
&& path
[len
-1] != '/')
173 strbuf_addch(&buf
, '/');
174 strbuf_addstr(&buf
, ".git");
176 git_dir
= read_gitfile(buf
.buf
);
179 strbuf_addstr(&buf
, git_dir
);
181 strbuf_addch(&buf
, '/');
183 if (buf
.len
>= PATH_MAX
)
185 memcpy(pathname
, buf
.buf
, buf
.len
+ 1);
187 strbuf_release(&buf
);
188 len
= strlen(pathname
);
191 len
+= vsnprintf(pathname
+ len
, PATH_MAX
- len
, fmt
, args
);
195 return cleanup_path(pathname
);
198 int validate_headref(const char *path
)
201 char *buf
, buffer
[256];
202 unsigned char sha1
[20];
206 if (lstat(path
, &st
) < 0)
209 /* Make sure it is a "refs/.." symlink */
210 if (S_ISLNK(st
.st_mode
)) {
211 len
= readlink(path
, buffer
, sizeof(buffer
)-1);
212 if (len
>= 5 && !memcmp("refs/", buffer
, 5))
218 * Anything else, just open it and try to see if it is a symbolic ref.
220 fd
= open(path
, O_RDONLY
);
223 len
= read_in_full(fd
, buffer
, sizeof(buffer
)-1);
227 * Is it a symbolic ref?
231 if (!memcmp("ref:", buffer
, 4)) {
234 while (len
&& isspace(*buf
))
236 if (len
>= 5 && !memcmp("refs/", buf
, 5))
241 * Is this a detached HEAD?
243 if (!get_sha1_hex(buffer
, sha1
))
249 static struct passwd
*getpw_str(const char *username
, size_t len
)
252 char *username_z
= xmalloc(len
+ 1);
253 memcpy(username_z
, username
, len
);
254 username_z
[len
] = '\0';
255 pw
= getpwnam(username_z
);
261 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
262 * then it is a newly allocated string. Returns NULL on getpw failure or
265 char *expand_user_path(const char *path
)
267 struct strbuf user_path
= STRBUF_INIT
;
268 const char *first_slash
= strchrnul(path
, '/');
269 const char *to_copy
= path
;
273 if (path
[0] == '~') {
274 const char *username
= path
+ 1;
275 size_t username_len
= first_slash
- username
;
276 if (username_len
== 0) {
277 const char *home
= getenv("HOME");
280 strbuf_add(&user_path
, home
, strlen(home
));
282 struct passwd
*pw
= getpw_str(username
, username_len
);
285 strbuf_add(&user_path
, pw
->pw_dir
, strlen(pw
->pw_dir
));
287 to_copy
= first_slash
;
289 strbuf_add(&user_path
, to_copy
, strlen(to_copy
));
290 return strbuf_detach(&user_path
, NULL
);
292 strbuf_release(&user_path
);
297 * First, one directory to try is determined by the following algorithm.
299 * (0) If "strict" is given, the path is used as given and no DWIM is
301 * (1) "~/path" to mean path under the running user's home directory;
302 * (2) "~user/path" to mean path under named user's home directory;
303 * (3) "relative/path" to mean cwd relative directory; or
304 * (4) "/absolute/path" to mean absolute directory.
306 * Unless "strict" is given, we try access() for existence of "%s.git/.git",
307 * "%s/.git", "%s.git", "%s" in this order. The first one that exists is
310 * Second, we try chdir() to that. Upon failure, we return NULL.
312 * Then, we try if the current directory is a valid git repository.
313 * Upon failure, we return NULL.
315 * If all goes well, we return the directory we used to chdir() (but
316 * before ~user is expanded), avoiding getcwd() resolving symbolic
317 * links. User relative paths are also returned as they are given,
318 * except DWIM suffixing.
320 const char *enter_repo(const char *path
, int strict
)
322 static char used_path
[PATH_MAX
];
323 static char validated_path
[PATH_MAX
];
329 static const char *suffix
[] = {
330 "/.git", "", ".git/.git", ".git", NULL
,
333 int len
= strlen(path
);
335 while ((1 < len
) && (path
[len
-1] == '/'))
340 strncpy(used_path
, path
, len
); used_path
[len
] = 0 ;
341 strcpy(validated_path
, used_path
);
343 if (used_path
[0] == '~') {
344 char *newpath
= expand_user_path(used_path
);
345 if (!newpath
|| (PATH_MAX
- 10 < strlen(newpath
))) {
350 * Copy back into the static buffer. A pity
351 * since newpath was not bounded, but other
352 * branches of the if are limited by PATH_MAX
355 strcpy(used_path
, newpath
); free(newpath
);
357 else if (PATH_MAX
- 10 < len
)
359 len
= strlen(used_path
);
360 for (i
= 0; suffix
[i
]; i
++) {
362 strcpy(used_path
+ len
, suffix
[i
]);
363 if (!stat(used_path
, &st
) &&
364 (S_ISREG(st
.st_mode
) ||
365 (S_ISDIR(st
.st_mode
) && is_git_directory(used_path
)))) {
366 strcat(validated_path
, suffix
[i
]);
372 gitfile
= read_gitfile(used_path
) ;
374 strcpy(used_path
, gitfile
);
375 if (chdir(used_path
))
377 path
= validated_path
;
379 else if (chdir(path
))
382 if (access("objects", X_OK
) == 0 && access("refs", X_OK
) == 0 &&
383 validate_headref("HEAD") == 0) {
385 check_repository_format();
392 int set_shared_perm(const char *path
, int mode
)
395 int tweak
, shared
, orig_mode
;
397 if (!shared_repository
) {
399 return chmod(path
, mode
& ~S_IFMT
);
403 if (lstat(path
, &st
) < 0)
409 if (shared_repository
< 0)
410 shared
= -shared_repository
;
412 shared
= shared_repository
;
415 if (!(mode
& S_IWUSR
))
418 /* Copy read bits to execute bits */
419 tweak
|= (tweak
& 0444) >> 2;
420 if (shared_repository
< 0)
421 mode
= (mode
& ~0777) | tweak
;
426 /* Copy read bits to execute bits */
427 mode
|= (shared
& 0444) >> 2;
428 mode
|= FORCE_DIR_SET_GID
;
431 if (((shared_repository
< 0
432 ? (orig_mode
& (FORCE_DIR_SET_GID
| 0777))
433 : (orig_mode
& mode
)) != mode
) &&
434 chmod(path
, (mode
& ~S_IFMT
)) < 0)
439 const char *relative_path(const char *abs
, const char *base
)
441 static char buf
[PATH_MAX
+ 1];
444 if (!base
|| !base
[0])
447 if (is_dir_sep(base
[i
])) {
448 if (!is_dir_sep(abs
[j
]))
450 while (is_dir_sep(base
[i
]))
452 while (is_dir_sep(abs
[j
]))
455 } else if (abs
[j
] != base
[i
]) {
462 /* "/foo" is a prefix of "/foo" */
464 /* "/foo" is not a prefix of "/foobar" */
465 !is_dir_sep(base
[i
-1]) && !is_dir_sep(abs
[j
])
468 while (is_dir_sep(abs
[j
]))
473 strcpy(buf
, abs
+ j
);
478 * It is okay if dst == src, but they should not overlap otherwise.
480 * Performs the following normalizations on src, storing the result in dst:
481 * - Ensures that components are separated by '/' (Windows only)
482 * - Squashes sequences of '/'.
483 * - Removes "." components.
484 * - Removes ".." components, and the components the precede them.
485 * Returns failure (non-zero) if a ".." component appears as first path
486 * component anytime during the normalization. Otherwise, returns success (0).
488 * Note that this function is purely textual. It does not follow symlinks,
489 * verify the existence of the path, or make any system calls.
491 int normalize_path_copy(char *dst
, const char *src
)
495 if (has_dos_drive_prefix(src
)) {
501 if (is_dir_sep(*src
)) {
503 while (is_dir_sep(*src
))
511 * A path component that begins with . could be
513 * (1) "." and ends -- ignore and terminate.
514 * (2) "./" -- ignore them, eat slash and continue.
515 * (3) ".." and ends -- strip one and terminate.
516 * (4) "../" -- strip one, eat slash and continue.
522 } else if (is_dir_sep(src
[1])) {
525 while (is_dir_sep(*src
))
528 } else if (src
[1] == '.') {
533 } else if (is_dir_sep(src
[2])) {
536 while (is_dir_sep(*src
))
543 /* copy up to the next '/', and eat all '/' */
544 while ((c
= *src
++) != '\0' && !is_dir_sep(c
))
548 while (is_dir_sep(c
))
557 * dst0..dst is prefix portion, and dst[-1] is '/';
560 dst
--; /* go to trailing '/' */
563 /* Windows: dst[-1] cannot be backslash anymore */
564 while (dst0
< dst
&& dst
[-1] != '/')
572 * path = Canonical absolute path
573 * prefixes = string_list containing normalized, absolute paths without
574 * trailing slashes (except for the root directory, which is denoted by "/").
576 * Determines, for each path in prefixes, whether the "prefix"
577 * is an ancestor directory of path. Returns the length of the longest
578 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
579 * is an ancestor. (Note that this means 0 is returned if prefixes is
580 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
581 * are not considered to be their own ancestors. path must be in a
582 * canonical form: empty components, or "." or ".." components are not
585 int longest_ancestor_length(const char *path
, struct string_list
*prefixes
)
589 if (!strcmp(path
, "/"))
592 for (i
= 0; i
< prefixes
->nr
; i
++) {
593 const char *ceil
= prefixes
->items
[i
].string
;
594 int len
= strlen(ceil
);
596 if (len
== 1 && ceil
[0] == '/')
597 len
= 0; /* root matches anything, with length 0 */
598 else if (!strncmp(path
, ceil
, len
) && path
[len
] == '/')
599 ; /* match of length len */
601 continue; /* no match */
610 /* strip arbitrary amount of directory separators at end of path */
611 static inline int chomp_trailing_dir_sep(const char *path
, int len
)
613 while (len
&& is_dir_sep(path
[len
- 1]))
619 * If path ends with suffix (complete path components), returns the
620 * part before suffix (sans trailing directory separators).
621 * Otherwise returns NULL.
623 char *strip_path_suffix(const char *path
, const char *suffix
)
625 int path_len
= strlen(path
), suffix_len
= strlen(suffix
);
631 if (is_dir_sep(path
[path_len
- 1])) {
632 if (!is_dir_sep(suffix
[suffix_len
- 1]))
634 path_len
= chomp_trailing_dir_sep(path
, path_len
);
635 suffix_len
= chomp_trailing_dir_sep(suffix
, suffix_len
);
637 else if (path
[--path_len
] != suffix
[--suffix_len
])
641 if (path_len
&& !is_dir_sep(path
[path_len
- 1]))
643 return xstrndup(path
, chomp_trailing_dir_sep(path
, path_len
));
646 int daemon_avoid_alias(const char *p
)
651 * This resurrects the belts and suspenders paranoia check by HPA
652 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
653 * does not do getcwd() based path canonicalization.
655 * sl becomes true immediately after seeing '/' and continues to
656 * be true as long as dots continue after that without intervening
659 if (!p
|| (*p
!= '/' && *p
!= '~'))
669 else if (ch
== '/') {
671 /* reject //, /./ and /../ */
676 if (0 < ndot
&& ndot
< 3)
677 /* reject /.$ and /..$ */
686 else if (ch
== '/') {
693 int offset_1st_component(const char *path
)
695 if (has_dos_drive_prefix(path
))
696 return 2 + is_dir_sep(path
[2]);
697 return is_dir_sep(path
[0]);