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 #ifndef get_st_mode_bits
19 * The replacement lstat(2) we use on Cygwin is incomplete and
20 * may return wrong permission bits. Most of the time we do not care,
21 * but the callsites of this wrapper do care.
23 int get_st_mode_bits(const char *path
, int *mode
)
26 if (lstat(path
, &st
) < 0)
33 static char bad_path
[] = "/bad-path/";
35 static char *get_pathname(void)
37 static char pathname_array
[4][PATH_MAX
];
39 return pathname_array
[3 & ++index
];
42 static char *cleanup_path(char *path
)
45 if (!memcmp(path
, "./", 2)) {
53 char *mksnpath(char *buf
, size_t n
, const char *fmt
, ...)
59 len
= vsnprintf(buf
, n
, fmt
, args
);
62 strlcpy(buf
, bad_path
, n
);
65 return cleanup_path(buf
);
68 static char *vsnpath(char *buf
, size_t n
, const char *fmt
, va_list args
)
70 const char *git_dir
= get_git_dir();
73 len
= strlen(git_dir
);
76 memcpy(buf
, git_dir
, len
);
77 if (len
&& !is_dir_sep(git_dir
[len
-1]))
79 len
+= vsnprintf(buf
+ len
, n
- len
, fmt
, args
);
82 return cleanup_path(buf
);
84 strlcpy(buf
, bad_path
, n
);
88 char *git_snpath(char *buf
, size_t n
, const char *fmt
, ...)
93 ret
= vsnpath(buf
, n
, fmt
, args
);
98 char *git_pathdup(const char *fmt
, ...)
100 char path
[PATH_MAX
], *ret
;
103 ret
= vsnpath(path
, sizeof(path
), fmt
, args
);
108 char *mkpathdup(const char *fmt
, ...)
111 struct strbuf sb
= STRBUF_INIT
;
115 strbuf_vaddf(&sb
, fmt
, args
);
117 path
= xstrdup(cleanup_path(sb
.buf
));
123 char *mkpath(const char *fmt
, ...)
127 char *pathname
= get_pathname();
130 len
= vsnprintf(pathname
, PATH_MAX
, fmt
, args
);
134 return cleanup_path(pathname
);
137 char *git_path(const char *fmt
, ...)
139 char *pathname
= get_pathname();
144 ret
= vsnpath(pathname
, PATH_MAX
, fmt
, args
);
149 void home_config_paths(char **global
, char **xdg
, char *file
)
151 char *xdg_home
= getenv("XDG_CONFIG_HOME");
152 char *home
= getenv("HOME");
153 char *to_free
= NULL
;
160 to_free
= mkpathdup("%s/.config", home
);
164 *global
= mkpathdup("%s/.gitconfig", home
);
170 *xdg
= mkpathdup("%s/git/%s", xdg_home
, file
);
175 char *git_path_submodule(const char *path
, const char *fmt
, ...)
177 char *pathname
= get_pathname();
178 struct strbuf buf
= STRBUF_INIT
;
184 if (len
> PATH_MAX
-100)
187 strbuf_addstr(&buf
, path
);
188 if (len
&& path
[len
-1] != '/')
189 strbuf_addch(&buf
, '/');
190 strbuf_addstr(&buf
, ".git");
192 git_dir
= read_gitfile(buf
.buf
);
195 strbuf_addstr(&buf
, git_dir
);
197 strbuf_addch(&buf
, '/');
199 if (buf
.len
>= PATH_MAX
)
201 memcpy(pathname
, buf
.buf
, buf
.len
+ 1);
203 strbuf_release(&buf
);
204 len
= strlen(pathname
);
207 len
+= vsnprintf(pathname
+ len
, PATH_MAX
- len
, fmt
, args
);
211 return cleanup_path(pathname
);
214 int validate_headref(const char *path
)
217 char *buf
, buffer
[256];
218 unsigned char sha1
[20];
222 if (lstat(path
, &st
) < 0)
225 /* Make sure it is a "refs/.." symlink */
226 if (S_ISLNK(st
.st_mode
)) {
227 len
= readlink(path
, buffer
, sizeof(buffer
)-1);
228 if (len
>= 5 && !memcmp("refs/", buffer
, 5))
234 * Anything else, just open it and try to see if it is a symbolic ref.
236 fd
= open(path
, O_RDONLY
);
239 len
= read_in_full(fd
, buffer
, sizeof(buffer
)-1);
243 * Is it a symbolic ref?
247 if (!memcmp("ref:", buffer
, 4)) {
250 while (len
&& isspace(*buf
))
252 if (len
>= 5 && !memcmp("refs/", buf
, 5))
257 * Is this a detached HEAD?
259 if (!get_sha1_hex(buffer
, sha1
))
265 static struct passwd
*getpw_str(const char *username
, size_t len
)
268 char *username_z
= xmalloc(len
+ 1);
269 memcpy(username_z
, username
, len
);
270 username_z
[len
] = '\0';
271 pw
= getpwnam(username_z
);
277 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
278 * then it is a newly allocated string. Returns NULL on getpw failure or
281 char *expand_user_path(const char *path
)
283 struct strbuf user_path
= STRBUF_INIT
;
284 const char *first_slash
= strchrnul(path
, '/');
285 const char *to_copy
= path
;
289 if (path
[0] == '~') {
290 const char *username
= path
+ 1;
291 size_t username_len
= first_slash
- username
;
292 if (username_len
== 0) {
293 const char *home
= getenv("HOME");
296 strbuf_add(&user_path
, home
, strlen(home
));
298 struct passwd
*pw
= getpw_str(username
, username_len
);
301 strbuf_add(&user_path
, pw
->pw_dir
, strlen(pw
->pw_dir
));
303 to_copy
= first_slash
;
305 strbuf_add(&user_path
, to_copy
, strlen(to_copy
));
306 return strbuf_detach(&user_path
, NULL
);
308 strbuf_release(&user_path
);
313 * First, one directory to try is determined by the following algorithm.
315 * (0) If "strict" is given, the path is used as given and no DWIM is
317 * (1) "~/path" to mean path under the running user's home directory;
318 * (2) "~user/path" to mean path under named user's home directory;
319 * (3) "relative/path" to mean cwd relative directory; or
320 * (4) "/absolute/path" to mean absolute directory.
322 * Unless "strict" is given, we try access() for existence of "%s.git/.git",
323 * "%s/.git", "%s.git", "%s" in this order. The first one that exists is
326 * Second, we try chdir() to that. Upon failure, we return NULL.
328 * Then, we try if the current directory is a valid git repository.
329 * Upon failure, we return NULL.
331 * If all goes well, we return the directory we used to chdir() (but
332 * before ~user is expanded), avoiding getcwd() resolving symbolic
333 * links. User relative paths are also returned as they are given,
334 * except DWIM suffixing.
336 const char *enter_repo(const char *path
, int strict
)
338 static char used_path
[PATH_MAX
];
339 static char validated_path
[PATH_MAX
];
345 static const char *suffix
[] = {
346 "/.git", "", ".git/.git", ".git", NULL
,
349 int len
= strlen(path
);
351 while ((1 < len
) && (path
[len
-1] == '/'))
356 strncpy(used_path
, path
, len
); used_path
[len
] = 0 ;
357 strcpy(validated_path
, used_path
);
359 if (used_path
[0] == '~') {
360 char *newpath
= expand_user_path(used_path
);
361 if (!newpath
|| (PATH_MAX
- 10 < strlen(newpath
))) {
366 * Copy back into the static buffer. A pity
367 * since newpath was not bounded, but other
368 * branches of the if are limited by PATH_MAX
371 strcpy(used_path
, newpath
); free(newpath
);
373 else if (PATH_MAX
- 10 < len
)
375 len
= strlen(used_path
);
376 for (i
= 0; suffix
[i
]; i
++) {
378 strcpy(used_path
+ len
, suffix
[i
]);
379 if (!stat(used_path
, &st
) &&
380 (S_ISREG(st
.st_mode
) ||
381 (S_ISDIR(st
.st_mode
) && is_git_directory(used_path
)))) {
382 strcat(validated_path
, suffix
[i
]);
388 gitfile
= read_gitfile(used_path
) ;
390 strcpy(used_path
, gitfile
);
391 if (chdir(used_path
))
393 path
= validated_path
;
395 else if (chdir(path
))
398 if (access("objects", X_OK
) == 0 && access("refs", X_OK
) == 0 &&
399 validate_headref("HEAD") == 0) {
401 check_repository_format();
408 int set_shared_perm(const char *path
, int mode
)
410 int tweak
, shared
, orig_mode
;
412 if (!shared_repository
) {
414 return chmod(path
, mode
& ~S_IFMT
);
418 if (get_st_mode_bits(path
, &mode
) < 0)
423 if (shared_repository
< 0)
424 shared
= -shared_repository
;
426 shared
= shared_repository
;
429 if (!(mode
& S_IWUSR
))
432 /* Copy read bits to execute bits */
433 tweak
|= (tweak
& 0444) >> 2;
434 if (shared_repository
< 0)
435 mode
= (mode
& ~0777) | tweak
;
440 /* Copy read bits to execute bits */
441 mode
|= (shared
& 0444) >> 2;
442 mode
|= FORCE_DIR_SET_GID
;
445 if (((shared_repository
< 0
446 ? (orig_mode
& (FORCE_DIR_SET_GID
| 0777))
447 : (orig_mode
& mode
)) != mode
) &&
448 chmod(path
, (mode
& ~S_IFMT
)) < 0)
453 const char *relative_path(const char *abs
, const char *base
)
455 static char buf
[PATH_MAX
+ 1];
458 if (!base
|| !base
[0])
461 if (is_dir_sep(base
[i
])) {
462 if (!is_dir_sep(abs
[j
]))
464 while (is_dir_sep(base
[i
]))
466 while (is_dir_sep(abs
[j
]))
469 } else if (abs
[j
] != base
[i
]) {
476 /* "/foo" is a prefix of "/foo" */
478 /* "/foo" is not a prefix of "/foobar" */
479 !is_dir_sep(base
[i
-1]) && !is_dir_sep(abs
[j
])
482 while (is_dir_sep(abs
[j
]))
487 strcpy(buf
, abs
+ j
);
492 * It is okay if dst == src, but they should not overlap otherwise.
494 * Performs the following normalizations on src, storing the result in dst:
495 * - Ensures that components are separated by '/' (Windows only)
496 * - Squashes sequences of '/'.
497 * - Removes "." components.
498 * - Removes ".." components, and the components the precede them.
499 * Returns failure (non-zero) if a ".." component appears as first path
500 * component anytime during the normalization. Otherwise, returns success (0).
502 * Note that this function is purely textual. It does not follow symlinks,
503 * verify the existence of the path, or make any system calls.
505 int normalize_path_copy(char *dst
, const char *src
)
509 if (has_dos_drive_prefix(src
)) {
515 if (is_dir_sep(*src
)) {
517 while (is_dir_sep(*src
))
525 * A path component that begins with . could be
527 * (1) "." and ends -- ignore and terminate.
528 * (2) "./" -- ignore them, eat slash and continue.
529 * (3) ".." and ends -- strip one and terminate.
530 * (4) "../" -- strip one, eat slash and continue.
536 } else if (is_dir_sep(src
[1])) {
539 while (is_dir_sep(*src
))
542 } else if (src
[1] == '.') {
547 } else if (is_dir_sep(src
[2])) {
550 while (is_dir_sep(*src
))
557 /* copy up to the next '/', and eat all '/' */
558 while ((c
= *src
++) != '\0' && !is_dir_sep(c
))
562 while (is_dir_sep(c
))
571 * dst0..dst is prefix portion, and dst[-1] is '/';
574 dst
--; /* go to trailing '/' */
577 /* Windows: dst[-1] cannot be backslash anymore */
578 while (dst0
< dst
&& dst
[-1] != '/')
586 * path = Canonical absolute path
587 * prefixes = string_list containing normalized, absolute paths without
588 * trailing slashes (except for the root directory, which is denoted by "/").
590 * Determines, for each path in prefixes, whether the "prefix"
591 * is an ancestor directory of path. Returns the length of the longest
592 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
593 * is an ancestor. (Note that this means 0 is returned if prefixes is
594 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
595 * are not considered to be their own ancestors. path must be in a
596 * canonical form: empty components, or "." or ".." components are not
599 int longest_ancestor_length(const char *path
, struct string_list
*prefixes
)
603 if (!strcmp(path
, "/"))
606 for (i
= 0; i
< prefixes
->nr
; i
++) {
607 const char *ceil
= prefixes
->items
[i
].string
;
608 int len
= strlen(ceil
);
610 if (len
== 1 && ceil
[0] == '/')
611 len
= 0; /* root matches anything, with length 0 */
612 else if (!strncmp(path
, ceil
, len
) && path
[len
] == '/')
613 ; /* match of length len */
615 continue; /* no match */
624 /* strip arbitrary amount of directory separators at end of path */
625 static inline int chomp_trailing_dir_sep(const char *path
, int len
)
627 while (len
&& is_dir_sep(path
[len
- 1]))
633 * If path ends with suffix (complete path components), returns the
634 * part before suffix (sans trailing directory separators).
635 * Otherwise returns NULL.
637 char *strip_path_suffix(const char *path
, const char *suffix
)
639 int path_len
= strlen(path
), suffix_len
= strlen(suffix
);
645 if (is_dir_sep(path
[path_len
- 1])) {
646 if (!is_dir_sep(suffix
[suffix_len
- 1]))
648 path_len
= chomp_trailing_dir_sep(path
, path_len
);
649 suffix_len
= chomp_trailing_dir_sep(suffix
, suffix_len
);
651 else if (path
[--path_len
] != suffix
[--suffix_len
])
655 if (path_len
&& !is_dir_sep(path
[path_len
- 1]))
657 return xstrndup(path
, chomp_trailing_dir_sep(path
, path_len
));
660 int daemon_avoid_alias(const char *p
)
665 * This resurrects the belts and suspenders paranoia check by HPA
666 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
667 * does not do getcwd() based path canonicalization.
669 * sl becomes true immediately after seeing '/' and continues to
670 * be true as long as dots continue after that without intervening
673 if (!p
|| (*p
!= '/' && *p
!= '~'))
683 else if (ch
== '/') {
685 /* reject //, /./ and /../ */
690 if (0 < ndot
&& ndot
< 3)
691 /* reject /.$ and /..$ */
700 else if (ch
== '/') {
707 int offset_1st_component(const char *path
)
709 if (has_dos_drive_prefix(path
))
710 return 2 + is_dir_sep(path
[2]);
711 return is_dir_sep(path
[0]);