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 *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
, ...)
76 ret
= vsnpath(buf
, n
, fmt
, args
);
81 char *git_pathdup(const char *fmt
, ...)
83 char path
[PATH_MAX
], *ret
;
86 ret
= vsnpath(path
, sizeof(path
), fmt
, args
);
91 char *mkpathdup(const char *fmt
, ...)
94 struct strbuf sb
= STRBUF_INIT
;
98 strbuf_vaddf(&sb
, fmt
, args
);
100 path
= xstrdup(cleanup_path(sb
.buf
));
106 char *mkpath(const char *fmt
, ...)
110 char *pathname
= get_pathname();
113 len
= vsnprintf(pathname
, PATH_MAX
, fmt
, args
);
117 return cleanup_path(pathname
);
120 char *git_path(const char *fmt
, ...)
122 const char *git_dir
= get_git_dir();
123 char *pathname
= get_pathname();
127 len
= strlen(git_dir
);
128 if (len
> PATH_MAX
-100)
130 memcpy(pathname
, git_dir
, len
);
131 if (len
&& git_dir
[len
-1] != '/')
132 pathname
[len
++] = '/';
134 len
+= vsnprintf(pathname
+ len
, PATH_MAX
- len
, fmt
, args
);
138 return cleanup_path(pathname
);
141 void home_config_paths(char **global
, char **xdg
, char *file
)
143 char *xdg_home
= getenv("XDG_CONFIG_HOME");
144 char *home
= getenv("HOME");
145 char *to_free
= NULL
;
152 to_free
= mkpathdup("%s/.config", home
);
156 *global
= mkpathdup("%s/.gitconfig", home
);
162 *xdg
= mkpathdup("%s/git/%s", xdg_home
, file
);
167 char *git_path_submodule(const char *path
, const char *fmt
, ...)
169 char *pathname
= get_pathname();
170 struct strbuf buf
= STRBUF_INIT
;
176 if (len
> PATH_MAX
-100)
179 strbuf_addstr(&buf
, path
);
180 if (len
&& path
[len
-1] != '/')
181 strbuf_addch(&buf
, '/');
182 strbuf_addstr(&buf
, ".git");
184 git_dir
= read_gitfile(buf
.buf
);
187 strbuf_addstr(&buf
, git_dir
);
189 strbuf_addch(&buf
, '/');
191 if (buf
.len
>= PATH_MAX
)
193 memcpy(pathname
, buf
.buf
, buf
.len
+ 1);
195 strbuf_release(&buf
);
196 len
= strlen(pathname
);
199 len
+= vsnprintf(pathname
+ len
, PATH_MAX
- len
, fmt
, args
);
203 return cleanup_path(pathname
);
206 int validate_headref(const char *path
)
209 char *buf
, buffer
[256];
210 unsigned char sha1
[20];
214 if (lstat(path
, &st
) < 0)
217 /* Make sure it is a "refs/.." symlink */
218 if (S_ISLNK(st
.st_mode
)) {
219 len
= readlink(path
, buffer
, sizeof(buffer
)-1);
220 if (len
>= 5 && !memcmp("refs/", buffer
, 5))
226 * Anything else, just open it and try to see if it is a symbolic ref.
228 fd
= open(path
, O_RDONLY
);
231 len
= read_in_full(fd
, buffer
, sizeof(buffer
)-1);
235 * Is it a symbolic ref?
239 if (!memcmp("ref:", buffer
, 4)) {
242 while (len
&& isspace(*buf
))
244 if (len
>= 5 && !memcmp("refs/", buf
, 5))
249 * Is this a detached HEAD?
251 if (!get_sha1_hex(buffer
, sha1
))
257 static struct passwd
*getpw_str(const char *username
, size_t len
)
260 char *username_z
= xmalloc(len
+ 1);
261 memcpy(username_z
, username
, len
);
262 username_z
[len
] = '\0';
263 pw
= getpwnam(username_z
);
269 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
270 * then it is a newly allocated string. Returns NULL on getpw failure or
273 char *expand_user_path(const char *path
)
275 struct strbuf user_path
= STRBUF_INIT
;
276 const char *first_slash
= strchrnul(path
, '/');
277 const char *to_copy
= path
;
281 if (path
[0] == '~') {
282 const char *username
= path
+ 1;
283 size_t username_len
= first_slash
- username
;
284 if (username_len
== 0) {
285 const char *home
= getenv("HOME");
288 strbuf_add(&user_path
, home
, strlen(home
));
290 struct passwd
*pw
= getpw_str(username
, username_len
);
293 strbuf_add(&user_path
, pw
->pw_dir
, strlen(pw
->pw_dir
));
295 to_copy
= first_slash
;
297 strbuf_add(&user_path
, to_copy
, strlen(to_copy
));
298 return strbuf_detach(&user_path
, NULL
);
300 strbuf_release(&user_path
);
305 * First, one directory to try is determined by the following algorithm.
307 * (0) If "strict" is given, the path is used as given and no DWIM is
309 * (1) "~/path" to mean path under the running user's home directory;
310 * (2) "~user/path" to mean path under named user's home directory;
311 * (3) "relative/path" to mean cwd relative directory; or
312 * (4) "/absolute/path" to mean absolute directory.
314 * Unless "strict" is given, we try access() for existence of "%s.git/.git",
315 * "%s/.git", "%s.git", "%s" in this order. The first one that exists is
318 * Second, we try chdir() to that. Upon failure, we return NULL.
320 * Then, we try if the current directory is a valid git repository.
321 * Upon failure, we return NULL.
323 * If all goes well, we return the directory we used to chdir() (but
324 * before ~user is expanded), avoiding getcwd() resolving symbolic
325 * links. User relative paths are also returned as they are given,
326 * except DWIM suffixing.
328 const char *enter_repo(const char *path
, int strict
)
330 static char used_path
[PATH_MAX
];
331 static char validated_path
[PATH_MAX
];
337 static const char *suffix
[] = {
338 "/.git", "", ".git/.git", ".git", NULL
,
341 int len
= strlen(path
);
343 while ((1 < len
) && (path
[len
-1] == '/'))
348 strncpy(used_path
, path
, len
); used_path
[len
] = 0 ;
349 strcpy(validated_path
, used_path
);
351 if (used_path
[0] == '~') {
352 char *newpath
= expand_user_path(used_path
);
353 if (!newpath
|| (PATH_MAX
- 10 < strlen(newpath
))) {
358 * Copy back into the static buffer. A pity
359 * since newpath was not bounded, but other
360 * branches of the if are limited by PATH_MAX
363 strcpy(used_path
, newpath
); free(newpath
);
365 else if (PATH_MAX
- 10 < len
)
367 len
= strlen(used_path
);
368 for (i
= 0; suffix
[i
]; i
++) {
370 strcpy(used_path
+ len
, suffix
[i
]);
371 if (!stat(used_path
, &st
) &&
372 (S_ISREG(st
.st_mode
) ||
373 (S_ISDIR(st
.st_mode
) && is_git_directory(used_path
)))) {
374 strcat(validated_path
, suffix
[i
]);
380 gitfile
= read_gitfile(used_path
) ;
382 strcpy(used_path
, gitfile
);
383 if (chdir(used_path
))
385 path
= validated_path
;
387 else if (chdir(path
))
390 if (access("objects", X_OK
) == 0 && access("refs", X_OK
) == 0 &&
391 validate_headref("HEAD") == 0) {
393 check_repository_format();
400 int set_shared_perm(const char *path
, int mode
)
403 int tweak
, shared
, orig_mode
;
405 if (!shared_repository
) {
407 return chmod(path
, mode
& ~S_IFMT
);
411 if (lstat(path
, &st
) < 0)
417 if (shared_repository
< 0)
418 shared
= -shared_repository
;
420 shared
= shared_repository
;
423 if (!(mode
& S_IWUSR
))
426 /* Copy read bits to execute bits */
427 tweak
|= (tweak
& 0444) >> 2;
428 if (shared_repository
< 0)
429 mode
= (mode
& ~0777) | tweak
;
434 /* Copy read bits to execute bits */
435 mode
|= (shared
& 0444) >> 2;
436 mode
|= FORCE_DIR_SET_GID
;
439 if (((shared_repository
< 0
440 ? (orig_mode
& (FORCE_DIR_SET_GID
| 0777))
441 : (orig_mode
& mode
)) != mode
) &&
442 chmod(path
, (mode
& ~S_IFMT
)) < 0)
447 const char *relative_path(const char *abs
, const char *base
)
449 static char buf
[PATH_MAX
+ 1];
452 if (!base
|| !base
[0])
455 if (is_dir_sep(base
[i
])) {
456 if (!is_dir_sep(abs
[j
]))
458 while (is_dir_sep(base
[i
]))
460 while (is_dir_sep(abs
[j
]))
463 } else if (abs
[j
] != base
[i
]) {
470 /* "/foo" is a prefix of "/foo" */
472 /* "/foo" is not a prefix of "/foobar" */
473 !is_dir_sep(base
[i
-1]) && !is_dir_sep(abs
[j
])
476 while (is_dir_sep(abs
[j
]))
481 strcpy(buf
, abs
+ j
);
486 * It is okay if dst == src, but they should not overlap otherwise.
488 * Performs the following normalizations on src, storing the result in dst:
489 * - Ensures that components are separated by '/' (Windows only)
490 * - Squashes sequences of '/'.
491 * - Removes "." components.
492 * - Removes ".." components, and the components the precede them.
493 * Returns failure (non-zero) if a ".." component appears as first path
494 * component anytime during the normalization. Otherwise, returns success (0).
496 * Note that this function is purely textual. It does not follow symlinks,
497 * verify the existence of the path, or make any system calls.
499 int normalize_path_copy(char *dst
, const char *src
)
503 if (has_dos_drive_prefix(src
)) {
509 if (is_dir_sep(*src
)) {
511 while (is_dir_sep(*src
))
519 * A path component that begins with . could be
521 * (1) "." and ends -- ignore and terminate.
522 * (2) "./" -- ignore them, eat slash and continue.
523 * (3) ".." and ends -- strip one and terminate.
524 * (4) "../" -- strip one, eat slash and continue.
530 } else if (is_dir_sep(src
[1])) {
533 while (is_dir_sep(*src
))
536 } else if (src
[1] == '.') {
541 } else if (is_dir_sep(src
[2])) {
544 while (is_dir_sep(*src
))
551 /* copy up to the next '/', and eat all '/' */
552 while ((c
= *src
++) != '\0' && !is_dir_sep(c
))
556 while (is_dir_sep(c
))
565 * dst0..dst is prefix portion, and dst[-1] is '/';
568 dst
--; /* go to trailing '/' */
571 /* Windows: dst[-1] cannot be backslash anymore */
572 while (dst0
< dst
&& dst
[-1] != '/')
580 * path = Canonical absolute path
581 * prefix_list = Colon-separated list of absolute paths
583 * Determines, for each path in prefix_list, whether the "prefix" really
584 * is an ancestor directory of path. Returns the length of the longest
585 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
586 * is an ancestor. (Note that this means 0 is returned if prefix_list is
587 * "/".) "/foo" is not considered an ancestor of "/foobar". Directories
588 * are not considered to be their own ancestors. path must be in a
589 * canonical form: empty components, or "." or ".." components are not
590 * allowed. prefix_list may be null, which is like "".
592 int longest_ancestor_length(const char *path
, const char *prefix_list
)
594 char buf
[PATH_MAX
+1];
595 const char *ceil
, *colon
;
596 int len
, max_len
= -1;
598 if (prefix_list
== NULL
|| !strcmp(path
, "/"))
601 for (colon
= ceil
= prefix_list
; *colon
; ceil
= colon
+1) {
602 for (colon
= ceil
; *colon
&& *colon
!= PATH_SEP
; colon
++);
604 if (len
== 0 || len
> PATH_MAX
|| !is_absolute_path(ceil
))
606 strlcpy(buf
, ceil
, len
+1);
607 if (normalize_path_copy(buf
, buf
) < 0)
610 if (len
> 0 && buf
[len
-1] == '/')
613 if (!strncmp(path
, buf
, len
) &&
623 /* strip arbitrary amount of directory separators at end of path */
624 static inline int chomp_trailing_dir_sep(const char *path
, int len
)
626 while (len
&& is_dir_sep(path
[len
- 1]))
632 * If path ends with suffix (complete path components), returns the
633 * part before suffix (sans trailing directory separators).
634 * Otherwise returns NULL.
636 char *strip_path_suffix(const char *path
, const char *suffix
)
638 int path_len
= strlen(path
), suffix_len
= strlen(suffix
);
644 if (is_dir_sep(path
[path_len
- 1])) {
645 if (!is_dir_sep(suffix
[suffix_len
- 1]))
647 path_len
= chomp_trailing_dir_sep(path
, path_len
);
648 suffix_len
= chomp_trailing_dir_sep(suffix
, suffix_len
);
650 else if (path
[--path_len
] != suffix
[--suffix_len
])
654 if (path_len
&& !is_dir_sep(path
[path_len
- 1]))
656 return xstrndup(path
, chomp_trailing_dir_sep(path
, path_len
));
659 int daemon_avoid_alias(const char *p
)
664 * This resurrects the belts and suspenders paranoia check by HPA
665 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
666 * does not do getcwd() based path canonicalization.
668 * sl becomes true immediately after seeing '/' and continues to
669 * be true as long as dots continue after that without intervening
672 if (!p
|| (*p
!= '/' && *p
!= '~'))
682 else if (ch
== '/') {
684 /* reject //, /./ and /../ */
689 if (0 < ndot
&& ndot
< 3)
690 /* reject /.$ and /..$ */
699 else if (ch
== '/') {
706 int offset_1st_component(const char *path
)
708 if (has_dos_drive_prefix(path
))
709 return 2 + is_dir_sep(path
[2]);
710 return is_dir_sep(path
[0]);