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 *mkpath(const char *fmt
, ...)
94 char *pathname
= get_pathname();
97 len
= vsnprintf(pathname
, PATH_MAX
, fmt
, args
);
101 return cleanup_path(pathname
);
104 char *git_path(const char *fmt
, ...)
106 const char *git_dir
= get_git_dir();
107 char *pathname
= get_pathname();
111 len
= strlen(git_dir
);
112 if (len
> PATH_MAX
-100)
114 memcpy(pathname
, git_dir
, len
);
115 if (len
&& git_dir
[len
-1] != '/')
116 pathname
[len
++] = '/';
118 len
+= vsnprintf(pathname
+ len
, PATH_MAX
- len
, fmt
, args
);
122 return cleanup_path(pathname
);
125 char *git_path_submodule(const char *path
, const char *fmt
, ...)
127 char *pathname
= get_pathname();
128 struct strbuf buf
= STRBUF_INIT
;
134 if (len
> PATH_MAX
-100)
137 strbuf_addstr(&buf
, path
);
138 if (len
&& path
[len
-1] != '/')
139 strbuf_addch(&buf
, '/');
140 strbuf_addstr(&buf
, ".git");
142 git_dir
= read_gitfile(buf
.buf
);
145 strbuf_addstr(&buf
, git_dir
);
147 strbuf_addch(&buf
, '/');
149 if (buf
.len
>= PATH_MAX
)
151 memcpy(pathname
, buf
.buf
, buf
.len
+ 1);
153 strbuf_release(&buf
);
154 len
= strlen(pathname
);
157 len
+= vsnprintf(pathname
+ len
, PATH_MAX
- len
, fmt
, args
);
161 return cleanup_path(pathname
);
164 int validate_headref(const char *path
)
167 char *buf
, buffer
[256];
168 unsigned char sha1
[20];
172 if (lstat(path
, &st
) < 0)
175 /* Make sure it is a "refs/.." symlink */
176 if (S_ISLNK(st
.st_mode
)) {
177 len
= readlink(path
, buffer
, sizeof(buffer
)-1);
178 if (len
>= 5 && !memcmp("refs/", buffer
, 5))
184 * Anything else, just open it and try to see if it is a symbolic ref.
186 fd
= open(path
, O_RDONLY
);
189 len
= read_in_full(fd
, buffer
, sizeof(buffer
)-1);
193 * Is it a symbolic ref?
197 if (!memcmp("ref:", buffer
, 4)) {
200 while (len
&& isspace(*buf
))
202 if (len
>= 5 && !memcmp("refs/", buf
, 5))
207 * Is this a detached HEAD?
209 if (!get_sha1_hex(buffer
, sha1
))
215 static struct passwd
*getpw_str(const char *username
, size_t len
)
218 char *username_z
= xmalloc(len
+ 1);
219 memcpy(username_z
, username
, len
);
220 username_z
[len
] = '\0';
221 pw
= getpwnam(username_z
);
227 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
228 * then it is a newly allocated string. Returns NULL on getpw failure or
231 char *expand_user_path(const char *path
)
233 struct strbuf user_path
= STRBUF_INIT
;
234 const char *first_slash
= strchrnul(path
, '/');
235 const char *to_copy
= path
;
239 if (path
[0] == '~') {
240 const char *username
= path
+ 1;
241 size_t username_len
= first_slash
- username
;
242 if (username_len
== 0) {
243 const char *home
= getenv("HOME");
246 strbuf_add(&user_path
, home
, strlen(home
));
248 struct passwd
*pw
= getpw_str(username
, username_len
);
251 strbuf_add(&user_path
, pw
->pw_dir
, strlen(pw
->pw_dir
));
253 to_copy
= first_slash
;
255 strbuf_add(&user_path
, to_copy
, strlen(to_copy
));
256 return strbuf_detach(&user_path
, NULL
);
258 strbuf_release(&user_path
);
263 * First, one directory to try is determined by the following algorithm.
265 * (0) If "strict" is given, the path is used as given and no DWIM is
267 * (1) "~/path" to mean path under the running user's home directory;
268 * (2) "~user/path" to mean path under named user's home directory;
269 * (3) "relative/path" to mean cwd relative directory; or
270 * (4) "/absolute/path" to mean absolute directory.
272 * Unless "strict" is given, we try access() for existence of "%s.git/.git",
273 * "%s/.git", "%s.git", "%s" in this order. The first one that exists is
276 * Second, we try chdir() to that. Upon failure, we return NULL.
278 * Then, we try if the current directory is a valid git repository.
279 * Upon failure, we return NULL.
281 * If all goes well, we return the directory we used to chdir() (but
282 * before ~user is expanded), avoiding getcwd() resolving symbolic
283 * links. User relative paths are also returned as they are given,
284 * except DWIM suffixing.
286 const char *enter_repo(const char *path
, int strict
)
288 static char used_path
[PATH_MAX
];
289 static char validated_path
[PATH_MAX
];
295 static const char *suffix
[] = {
296 ".git/.git", "/.git", ".git", "", NULL
,
299 int len
= strlen(path
);
301 while ((1 < len
) && (path
[len
-1] == '/'))
306 strncpy(used_path
, path
, len
); used_path
[len
] = 0 ;
307 strcpy(validated_path
, used_path
);
309 if (used_path
[0] == '~') {
310 char *newpath
= expand_user_path(used_path
);
311 if (!newpath
|| (PATH_MAX
- 10 < strlen(newpath
))) {
316 * Copy back into the static buffer. A pity
317 * since newpath was not bounded, but other
318 * branches of the if are limited by PATH_MAX
321 strcpy(used_path
, newpath
); free(newpath
);
323 else if (PATH_MAX
- 10 < len
)
325 len
= strlen(used_path
);
326 for (i
= 0; suffix
[i
]; i
++) {
327 strcpy(used_path
+ len
, suffix
[i
]);
328 if (!access(used_path
, F_OK
)) {
329 strcat(validated_path
, suffix
[i
]);
335 gitfile
= read_gitfile(used_path
) ;
337 strcpy(used_path
, gitfile
);
338 if (chdir(used_path
))
340 path
= validated_path
;
342 else if (chdir(path
))
345 if (access("objects", X_OK
) == 0 && access("refs", X_OK
) == 0 &&
346 validate_headref("HEAD") == 0) {
348 check_repository_format();
355 int set_shared_perm(const char *path
, int mode
)
358 int tweak
, shared
, orig_mode
;
360 if (!shared_repository
) {
362 return chmod(path
, mode
& ~S_IFMT
);
366 if (lstat(path
, &st
) < 0)
372 if (shared_repository
< 0)
373 shared
= -shared_repository
;
375 shared
= shared_repository
;
378 if (!(mode
& S_IWUSR
))
381 /* Copy read bits to execute bits */
382 tweak
|= (tweak
& 0444) >> 2;
383 if (shared_repository
< 0)
384 mode
= (mode
& ~0777) | tweak
;
389 /* Copy read bits to execute bits */
390 mode
|= (shared
& 0444) >> 2;
391 mode
|= FORCE_DIR_SET_GID
;
394 if (((shared_repository
< 0
395 ? (orig_mode
& (FORCE_DIR_SET_GID
| 0777))
396 : (orig_mode
& mode
)) != mode
) &&
397 chmod(path
, (mode
& ~S_IFMT
)) < 0)
402 const char *relative_path(const char *abs
, const char *base
)
404 static char buf
[PATH_MAX
+ 1];
407 if (!base
|| !base
[0])
410 if (is_dir_sep(base
[i
])) {
411 if (!is_dir_sep(abs
[j
]))
413 while (is_dir_sep(base
[i
]))
415 while (is_dir_sep(abs
[j
]))
418 } else if (abs
[j
] != base
[i
]) {
425 /* "/foo" is a prefix of "/foo" */
427 /* "/foo" is not a prefix of "/foobar" */
428 !is_dir_sep(base
[i
-1]) && !is_dir_sep(abs
[j
])
431 while (is_dir_sep(abs
[j
]))
436 strcpy(buf
, abs
+ j
);
441 * It is okay if dst == src, but they should not overlap otherwise.
443 * Performs the following normalizations on src, storing the result in dst:
444 * - Ensures that components are separated by '/' (Windows only)
445 * - Squashes sequences of '/'.
446 * - Removes "." components.
447 * - Removes ".." components, and the components the precede them.
448 * Returns failure (non-zero) if a ".." component appears as first path
449 * component anytime during the normalization. Otherwise, returns success (0).
451 * Note that this function is purely textual. It does not follow symlinks,
452 * verify the existence of the path, or make any system calls.
454 int normalize_path_copy(char *dst
, const char *src
)
458 if (has_dos_drive_prefix(src
)) {
464 if (is_dir_sep(*src
)) {
466 while (is_dir_sep(*src
))
474 * A path component that begins with . could be
476 * (1) "." and ends -- ignore and terminate.
477 * (2) "./" -- ignore them, eat slash and continue.
478 * (3) ".." and ends -- strip one and terminate.
479 * (4) "../" -- strip one, eat slash and continue.
485 } else if (is_dir_sep(src
[1])) {
488 while (is_dir_sep(*src
))
491 } else if (src
[1] == '.') {
496 } else if (is_dir_sep(src
[2])) {
499 while (is_dir_sep(*src
))
506 /* copy up to the next '/', and eat all '/' */
507 while ((c
= *src
++) != '\0' && !is_dir_sep(c
))
511 while (is_dir_sep(c
))
520 * dst0..dst is prefix portion, and dst[-1] is '/';
523 dst
--; /* go to trailing '/' */
526 /* Windows: dst[-1] cannot be backslash anymore */
527 while (dst0
< dst
&& dst
[-1] != '/')
535 * path = Canonical absolute path
536 * prefix_list = Colon-separated list of absolute paths
538 * Determines, for each path in prefix_list, whether the "prefix" really
539 * is an ancestor directory of path. Returns the length of the longest
540 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
541 * is an ancestor. (Note that this means 0 is returned if prefix_list is
542 * "/".) "/foo" is not considered an ancestor of "/foobar". Directories
543 * are not considered to be their own ancestors. path must be in a
544 * canonical form: empty components, or "." or ".." components are not
545 * allowed. prefix_list may be null, which is like "".
547 int longest_ancestor_length(const char *path
, const char *prefix_list
)
549 char buf
[PATH_MAX
+1];
550 const char *ceil
, *colon
;
551 int len
, max_len
= -1;
553 if (prefix_list
== NULL
|| !strcmp(path
, "/"))
556 for (colon
= ceil
= prefix_list
; *colon
; ceil
= colon
+1) {
557 for (colon
= ceil
; *colon
&& *colon
!= PATH_SEP
; colon
++);
559 if (len
== 0 || len
> PATH_MAX
|| !is_absolute_path(ceil
))
561 strlcpy(buf
, ceil
, len
+1);
562 if (normalize_path_copy(buf
, buf
) < 0)
565 if (len
> 0 && buf
[len
-1] == '/')
568 if (!strncmp(path
, buf
, len
) &&
578 /* strip arbitrary amount of directory separators at end of path */
579 static inline int chomp_trailing_dir_sep(const char *path
, int len
)
581 while (len
&& is_dir_sep(path
[len
- 1]))
587 * If path ends with suffix (complete path components), returns the
588 * part before suffix (sans trailing directory separators).
589 * Otherwise returns NULL.
591 char *strip_path_suffix(const char *path
, const char *suffix
)
593 int path_len
= strlen(path
), suffix_len
= strlen(suffix
);
599 if (is_dir_sep(path
[path_len
- 1])) {
600 if (!is_dir_sep(suffix
[suffix_len
- 1]))
602 path_len
= chomp_trailing_dir_sep(path
, path_len
);
603 suffix_len
= chomp_trailing_dir_sep(suffix
, suffix_len
);
605 else if (path
[--path_len
] != suffix
[--suffix_len
])
609 if (path_len
&& !is_dir_sep(path
[path_len
- 1]))
611 return xstrndup(path
, chomp_trailing_dir_sep(path
, path_len
));
614 int daemon_avoid_alias(const char *p
)
619 * This resurrects the belts and suspenders paranoia check by HPA
620 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
621 * does not do getcwd() based path canonicalization.
623 * sl becomes true immediately after seeing '/' and continues to
624 * be true as long as dots continue after that without intervening
627 if (!p
|| (*p
!= '/' && *p
!= '~'))
637 else if (ch
== '/') {
639 /* reject //, /./ and /../ */
644 if (0 < ndot
&& ndot
< 3)
645 /* reject /.$ and /..$ */
654 else if (ch
== '/') {
661 int offset_1st_component(const char *path
)
663 if (has_dos_drive_prefix(path
))
664 return 2 + is_dir_sep(path
[2]);
665 return is_dir_sep(path
[0]);