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.
16 static char bad_path
[] = "/bad-path/";
18 static char *get_pathname(void)
20 static char pathname_array
[4][PATH_MAX
];
22 return pathname_array
[3 & ++index
];
25 static char *cleanup_path(char *path
)
28 if (!memcmp(path
, "./", 2)) {
36 char *mksnpath(char *buf
, size_t n
, const char *fmt
, ...)
42 len
= vsnprintf(buf
, n
, fmt
, args
);
45 strlcpy(buf
, bad_path
, n
);
48 return cleanup_path(buf
);
51 static char *git_vsnpath(char *buf
, size_t n
, const char *fmt
, va_list args
)
53 const char *git_dir
= get_git_dir();
56 len
= strlen(git_dir
);
59 memcpy(buf
, git_dir
, len
);
60 if (len
&& !is_dir_sep(git_dir
[len
-1]))
62 len
+= vsnprintf(buf
+ len
, n
- len
, fmt
, args
);
65 return cleanup_path(buf
);
67 strlcpy(buf
, bad_path
, n
);
71 char *git_snpath(char *buf
, size_t n
, const char *fmt
, ...)
75 (void)git_vsnpath(buf
, n
, fmt
, args
);
80 char *git_pathdup(const char *fmt
, ...)
85 (void)git_vsnpath(path
, sizeof(path
), fmt
, args
);
90 char *mkpathdup(const char *fmt
, ...)
93 struct strbuf sb
= STRBUF_INIT
;
97 strbuf_vaddf(&sb
, fmt
, args
);
99 path
= xstrdup(cleanup_path(sb
.buf
));
105 char *mkpath(const char *fmt
, ...)
109 char *pathname
= get_pathname();
112 len
= vsnprintf(pathname
, PATH_MAX
, fmt
, args
);
116 return cleanup_path(pathname
);
119 char *git_path(const char *fmt
, ...)
121 const char *git_dir
= get_git_dir();
122 char *pathname
= get_pathname();
126 len
= strlen(git_dir
);
127 if (len
> PATH_MAX
-100)
129 memcpy(pathname
, git_dir
, len
);
130 if (len
&& git_dir
[len
-1] != '/')
131 pathname
[len
++] = '/';
133 len
+= vsnprintf(pathname
+ len
, PATH_MAX
- len
, fmt
, args
);
137 return cleanup_path(pathname
);
140 void home_config_paths(char **global
, char **xdg
, char *file
)
142 char *xdg_home
= getenv("XDG_CONFIG_HOME");
143 char *home
= getenv("HOME");
144 char *to_free
= NULL
;
151 to_free
= mkpathdup("%s/.config", home
);
155 *global
= mkpathdup("%s/.gitconfig", home
);
161 *xdg
= mkpathdup("%s/git/%s", xdg_home
, file
);
166 char *git_path_submodule(const char *path
, const char *fmt
, ...)
168 char *pathname
= get_pathname();
169 struct strbuf buf
= STRBUF_INIT
;
175 if (len
> PATH_MAX
-100)
178 strbuf_addstr(&buf
, path
);
179 if (len
&& path
[len
-1] != '/')
180 strbuf_addch(&buf
, '/');
181 strbuf_addstr(&buf
, ".git");
183 git_dir
= read_gitfile(buf
.buf
);
186 strbuf_addstr(&buf
, git_dir
);
188 strbuf_addch(&buf
, '/');
190 if (buf
.len
>= PATH_MAX
)
192 memcpy(pathname
, buf
.buf
, buf
.len
+ 1);
194 strbuf_release(&buf
);
195 len
= strlen(pathname
);
198 len
+= vsnprintf(pathname
+ len
, PATH_MAX
- len
, fmt
, args
);
202 return cleanup_path(pathname
);
205 int validate_headref(const char *path
)
208 char *buf
, buffer
[256];
209 unsigned char sha1
[20];
213 if (lstat(path
, &st
) < 0)
216 /* Make sure it is a "refs/.." symlink */
217 if (S_ISLNK(st
.st_mode
)) {
218 len
= readlink(path
, buffer
, sizeof(buffer
)-1);
219 if (len
>= 5 && !memcmp("refs/", buffer
, 5))
225 * Anything else, just open it and try to see if it is a symbolic ref.
227 fd
= open(path
, O_RDONLY
);
230 len
= read_in_full(fd
, buffer
, sizeof(buffer
)-1);
234 * Is it a symbolic ref?
238 if (!memcmp("ref:", buffer
, 4)) {
241 while (len
&& isspace(*buf
))
243 if (len
>= 5 && !memcmp("refs/", buf
, 5))
248 * Is this a detached HEAD?
250 if (!get_sha1_hex(buffer
, sha1
))
256 static struct passwd
*getpw_str(const char *username
, size_t len
)
259 char *username_z
= xmalloc(len
+ 1);
260 memcpy(username_z
, username
, len
);
261 username_z
[len
] = '\0';
262 pw
= getpwnam(username_z
);
268 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
269 * then it is a newly allocated string. Returns NULL on getpw failure or
272 char *expand_user_path(const char *path
)
274 struct strbuf user_path
= STRBUF_INIT
;
275 const char *first_slash
= strchrnul(path
, '/');
276 const char *to_copy
= path
;
280 if (path
[0] == '~') {
281 const char *username
= path
+ 1;
282 size_t username_len
= first_slash
- username
;
283 if (username_len
== 0) {
284 const char *home
= getenv("HOME");
287 strbuf_add(&user_path
, home
, strlen(home
));
289 struct passwd
*pw
= getpw_str(username
, username_len
);
292 strbuf_add(&user_path
, pw
->pw_dir
, strlen(pw
->pw_dir
));
294 to_copy
= first_slash
;
296 strbuf_add(&user_path
, to_copy
, strlen(to_copy
));
297 return strbuf_detach(&user_path
, NULL
);
299 strbuf_release(&user_path
);
304 * First, one directory to try is determined by the following algorithm.
306 * (0) If "strict" is given, the path is used as given and no DWIM is
308 * (1) "~/path" to mean path under the running user's home directory;
309 * (2) "~user/path" to mean path under named user's home directory;
310 * (3) "relative/path" to mean cwd relative directory; or
311 * (4) "/absolute/path" to mean absolute directory.
313 * Unless "strict" is given, we try access() for existence of "%s.git/.git",
314 * "%s/.git", "%s.git", "%s" in this order. The first one that exists is
317 * Second, we try chdir() to that. Upon failure, we return NULL.
319 * Then, we try if the current directory is a valid git repository.
320 * Upon failure, we return NULL.
322 * If all goes well, we return the directory we used to chdir() (but
323 * before ~user is expanded), avoiding getcwd() resolving symbolic
324 * links. User relative paths are also returned as they are given,
325 * except DWIM suffixing.
327 const char *enter_repo(const char *path
, int strict
)
329 static char used_path
[PATH_MAX
];
330 static char validated_path
[PATH_MAX
];
336 static const char *suffix
[] = {
337 "/.git", "", ".git/.git", ".git", NULL
,
340 int len
= strlen(path
);
342 while ((1 < len
) && (path
[len
-1] == '/'))
347 strncpy(used_path
, path
, len
); used_path
[len
] = 0 ;
348 strcpy(validated_path
, used_path
);
350 if (used_path
[0] == '~') {
351 char *newpath
= expand_user_path(used_path
);
352 if (!newpath
|| (PATH_MAX
- 10 < strlen(newpath
))) {
357 * Copy back into the static buffer. A pity
358 * since newpath was not bounded, but other
359 * branches of the if are limited by PATH_MAX
362 strcpy(used_path
, newpath
); free(newpath
);
364 else if (PATH_MAX
- 10 < len
)
366 len
= strlen(used_path
);
367 for (i
= 0; suffix
[i
]; i
++) {
369 strcpy(used_path
+ len
, suffix
[i
]);
370 if (!stat(used_path
, &st
) &&
371 (S_ISREG(st
.st_mode
) ||
372 (S_ISDIR(st
.st_mode
) && is_git_directory(used_path
)))) {
373 strcat(validated_path
, suffix
[i
]);
379 gitfile
= read_gitfile(used_path
) ;
381 strcpy(used_path
, gitfile
);
382 if (chdir(used_path
))
384 path
= validated_path
;
386 else if (chdir(path
))
389 if (access("objects", X_OK
) == 0 && access("refs", X_OK
) == 0 &&
390 validate_headref("HEAD") == 0) {
392 check_repository_format();
399 int set_shared_perm(const char *path
, int mode
)
402 int tweak
, shared
, orig_mode
;
404 if (!shared_repository
) {
406 return chmod(path
, mode
& ~S_IFMT
);
410 if (lstat(path
, &st
) < 0)
416 if (shared_repository
< 0)
417 shared
= -shared_repository
;
419 shared
= shared_repository
;
422 if (!(mode
& S_IWUSR
))
425 /* Copy read bits to execute bits */
426 tweak
|= (tweak
& 0444) >> 2;
427 if (shared_repository
< 0)
428 mode
= (mode
& ~0777) | tweak
;
433 /* Copy read bits to execute bits */
434 mode
|= (shared
& 0444) >> 2;
435 mode
|= FORCE_DIR_SET_GID
;
438 if (((shared_repository
< 0
439 ? (orig_mode
& (FORCE_DIR_SET_GID
| 0777))
440 : (orig_mode
& mode
)) != mode
) &&
441 chmod(path
, (mode
& ~S_IFMT
)) < 0)
446 const char *relative_path(const char *abs
, const char *base
)
448 static char buf
[PATH_MAX
+ 1];
451 if (!base
|| !base
[0])
454 if (is_dir_sep(base
[i
])) {
455 if (!is_dir_sep(abs
[j
]))
457 while (is_dir_sep(base
[i
]))
459 while (is_dir_sep(abs
[j
]))
462 } else if (abs
[j
] != base
[i
]) {
469 /* "/foo" is a prefix of "/foo" */
471 /* "/foo" is not a prefix of "/foobar" */
472 !is_dir_sep(base
[i
-1]) && !is_dir_sep(abs
[j
])
475 while (is_dir_sep(abs
[j
]))
480 strcpy(buf
, abs
+ j
);
485 * It is okay if dst == src, but they should not overlap otherwise.
487 * Performs the following normalizations on src, storing the result in dst:
488 * - Ensures that components are separated by '/' (Windows only)
489 * - Squashes sequences of '/'.
490 * - Removes "." components.
491 * - Removes ".." components, and the components the precede them.
492 * Returns failure (non-zero) if a ".." component appears as first path
493 * component anytime during the normalization. Otherwise, returns success (0).
495 * Note that this function is purely textual. It does not follow symlinks,
496 * verify the existence of the path, or make any system calls.
498 int normalize_path_copy(char *dst
, const char *src
)
502 if (has_dos_drive_prefix(src
)) {
508 if (is_dir_sep(*src
)) {
510 while (is_dir_sep(*src
))
518 * A path component that begins with . could be
520 * (1) "." and ends -- ignore and terminate.
521 * (2) "./" -- ignore them, eat slash and continue.
522 * (3) ".." and ends -- strip one and terminate.
523 * (4) "../" -- strip one, eat slash and continue.
529 } else if (is_dir_sep(src
[1])) {
532 while (is_dir_sep(*src
))
535 } else if (src
[1] == '.') {
540 } else if (is_dir_sep(src
[2])) {
543 while (is_dir_sep(*src
))
550 /* copy up to the next '/', and eat all '/' */
551 while ((c
= *src
++) != '\0' && !is_dir_sep(c
))
555 while (is_dir_sep(c
))
564 * dst0..dst is prefix portion, and dst[-1] is '/';
567 dst
--; /* go to trailing '/' */
570 /* Windows: dst[-1] cannot be backslash anymore */
571 while (dst0
< dst
&& dst
[-1] != '/')
579 * path = Canonical absolute path
580 * prefix_list = Colon-separated list of absolute paths
582 * Determines, for each path in prefix_list, whether the "prefix" really
583 * is an ancestor directory of path. Returns the length of the longest
584 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
585 * is an ancestor. (Note that this means 0 is returned if prefix_list is
586 * "/".) "/foo" is not considered an ancestor of "/foobar". Directories
587 * are not considered to be their own ancestors. path must be in a
588 * canonical form: empty components, or "." or ".." components are not
589 * allowed. prefix_list may be null, which is like "".
591 int longest_ancestor_length(const char *path
, const char *prefix_list
)
593 char buf
[PATH_MAX
+1];
594 const char *ceil
, *colon
;
595 int len
, max_len
= -1;
597 if (prefix_list
== NULL
|| !strcmp(path
, "/"))
600 for (colon
= ceil
= prefix_list
; *colon
; ceil
= colon
+1) {
601 for (colon
= ceil
; *colon
&& *colon
!= PATH_SEP
; colon
++);
603 if (len
== 0 || len
> PATH_MAX
|| !is_absolute_path(ceil
))
605 strlcpy(buf
, ceil
, len
+1);
606 if (normalize_path_copy(buf
, buf
) < 0)
609 if (len
> 0 && buf
[len
-1] == '/')
612 if (!strncmp(path
, buf
, len
) &&
622 /* strip arbitrary amount of directory separators at end of path */
623 static inline int chomp_trailing_dir_sep(const char *path
, int len
)
625 while (len
&& is_dir_sep(path
[len
- 1]))
631 * If path ends with suffix (complete path components), returns the
632 * part before suffix (sans trailing directory separators).
633 * Otherwise returns NULL.
635 char *strip_path_suffix(const char *path
, const char *suffix
)
637 int path_len
= strlen(path
), suffix_len
= strlen(suffix
);
643 if (is_dir_sep(path
[path_len
- 1])) {
644 if (!is_dir_sep(suffix
[suffix_len
- 1]))
646 path_len
= chomp_trailing_dir_sep(path
, path_len
);
647 suffix_len
= chomp_trailing_dir_sep(suffix
, suffix_len
);
649 else if (path
[--path_len
] != suffix
[--suffix_len
])
653 if (path_len
&& !is_dir_sep(path
[path_len
- 1]))
655 return xstrndup(path
, chomp_trailing_dir_sep(path
, path_len
));
658 int daemon_avoid_alias(const char *p
)
663 * This resurrects the belts and suspenders paranoia check by HPA
664 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
665 * does not do getcwd() based path canonicalization.
667 * sl becomes true immediately after seeing '/' and continues to
668 * be true as long as dots continue after that without intervening
671 if (!p
|| (*p
!= '/' && *p
!= '~'))
681 else if (ch
== '/') {
683 /* reject //, /./ and /../ */
688 if (0 < ndot
&& ndot
< 3)
689 /* reject /.$ and /..$ */
698 else if (ch
== '/') {
705 int offset_1st_component(const char *path
)
707 if (has_dos_drive_prefix(path
))
708 return 2 + is_dir_sep(path
[2]);
709 return is_dir_sep(path
[0]);