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_gently(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 /* git_mkstemp() - create tmp file honoring TMPDIR variable */
165 int git_mkstemp(char *path
, size_t len
, const char *template)
170 tmp
= getenv("TMPDIR");
173 n
= snprintf(path
, len
, "%s/%s", tmp
, template);
175 errno
= ENAMETOOLONG
;
178 return mkstemp(path
);
181 /* git_mkstemps() - create tmp file with suffix honoring TMPDIR variable. */
182 int git_mkstemps(char *path
, size_t len
, const char *template, int suffix_len
)
187 tmp
= getenv("TMPDIR");
190 n
= snprintf(path
, len
, "%s/%s", tmp
, template);
192 errno
= ENAMETOOLONG
;
195 return mkstemps(path
, suffix_len
);
198 /* Adapted from libiberty's mkstemp.c. */
201 #define TMP_MAX 16384
203 int git_mkstemps_mode(char *pattern
, int suffix_len
, int mode
)
205 static const char letters
[] =
206 "abcdefghijklmnopqrstuvwxyz"
207 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
209 static const int num_letters
= 62;
216 len
= strlen(pattern
);
218 if (len
< 6 + suffix_len
) {
223 if (strncmp(&pattern
[len
- 6 - suffix_len
], "XXXXXX", 6)) {
229 * Replace pattern's XXXXXX characters with randomness.
230 * Try TMP_MAX different filenames.
232 gettimeofday(&tv
, NULL
);
233 value
= ((size_t)(tv
.tv_usec
<< 16)) ^ tv
.tv_sec
^ getpid();
234 template = &pattern
[len
- 6 - suffix_len
];
235 for (count
= 0; count
< TMP_MAX
; ++count
) {
237 /* Fill in the random bits. */
238 template[0] = letters
[v
% num_letters
]; v
/= num_letters
;
239 template[1] = letters
[v
% num_letters
]; v
/= num_letters
;
240 template[2] = letters
[v
% num_letters
]; v
/= num_letters
;
241 template[3] = letters
[v
% num_letters
]; v
/= num_letters
;
242 template[4] = letters
[v
% num_letters
]; v
/= num_letters
;
243 template[5] = letters
[v
% num_letters
]; v
/= num_letters
;
245 fd
= open(pattern
, O_CREAT
| O_EXCL
| O_RDWR
, mode
);
249 * Fatal error (EPERM, ENOSPC etc).
250 * It doesn't make sense to loop.
255 * This is a random value. It is only necessary that
256 * the next TMP_MAX values generated by adding 7777 to
257 * VALUE are different with (module 2^32).
261 /* We return the null string if we can't find a unique file name. */
266 int git_mkstemp_mode(char *pattern
, int mode
)
268 /* mkstemp is just mkstemps with no suffix */
269 return git_mkstemps_mode(pattern
, 0, mode
);
272 int gitmkstemps(char *pattern
, int suffix_len
)
274 return git_mkstemps_mode(pattern
, suffix_len
, 0600);
277 int validate_headref(const char *path
)
280 char *buf
, buffer
[256];
281 unsigned char sha1
[20];
285 if (lstat(path
, &st
) < 0)
288 /* Make sure it is a "refs/.." symlink */
289 if (S_ISLNK(st
.st_mode
)) {
290 len
= readlink(path
, buffer
, sizeof(buffer
)-1);
291 if (len
>= 5 && !memcmp("refs/", buffer
, 5))
297 * Anything else, just open it and try to see if it is a symbolic ref.
299 fd
= open(path
, O_RDONLY
);
302 len
= read_in_full(fd
, buffer
, sizeof(buffer
)-1);
306 * Is it a symbolic ref?
310 if (!memcmp("ref:", buffer
, 4)) {
313 while (len
&& isspace(*buf
))
315 if (len
>= 5 && !memcmp("refs/", buf
, 5))
320 * Is this a detached HEAD?
322 if (!get_sha1_hex(buffer
, sha1
))
328 static struct passwd
*getpw_str(const char *username
, size_t len
)
331 char *username_z
= xmalloc(len
+ 1);
332 memcpy(username_z
, username
, len
);
333 username_z
[len
] = '\0';
334 pw
= getpwnam(username_z
);
340 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
341 * then it is a newly allocated string. Returns NULL on getpw failure or
344 char *expand_user_path(const char *path
)
346 struct strbuf user_path
= STRBUF_INIT
;
347 const char *first_slash
= strchrnul(path
, '/');
348 const char *to_copy
= path
;
352 if (path
[0] == '~') {
353 const char *username
= path
+ 1;
354 size_t username_len
= first_slash
- username
;
355 if (username_len
== 0) {
356 const char *home
= get_home_directory();
359 strbuf_add(&user_path
, home
, strlen(home
));
361 struct passwd
*pw
= getpw_str(username
, username_len
);
364 strbuf_add(&user_path
, pw
->pw_dir
, strlen(pw
->pw_dir
));
366 to_copy
= first_slash
;
368 strbuf_add(&user_path
, to_copy
, strlen(to_copy
));
369 return strbuf_detach(&user_path
, NULL
);
371 strbuf_release(&user_path
);
376 * First, one directory to try is determined by the following algorithm.
378 * (0) If "strict" is given, the path is used as given and no DWIM is
380 * (1) "~/path" to mean path under the running user's home directory;
381 * (2) "~user/path" to mean path under named user's home directory;
382 * (3) "relative/path" to mean cwd relative directory; or
383 * (4) "/absolute/path" to mean absolute directory.
385 * Unless "strict" is given, we try access() for existence of "%s.git/.git",
386 * "%s/.git", "%s.git", "%s" in this order. The first one that exists is
389 * Second, we try chdir() to that. Upon failure, we return NULL.
391 * Then, we try if the current directory is a valid git repository.
392 * Upon failure, we return NULL.
394 * If all goes well, we return the directory we used to chdir() (but
395 * before ~user is expanded), avoiding getcwd() resolving symbolic
396 * links. User relative paths are also returned as they are given,
397 * except DWIM suffixing.
399 char *enter_repo(char *path
, int strict
)
401 static char used_path
[PATH_MAX
];
402 static char validated_path
[PATH_MAX
];
408 static const char *suffix
[] = {
409 ".git/.git", "/.git", ".git", "", NULL
,
411 int len
= strlen(path
);
413 while ((1 < len
) && (path
[len
-1] == '/')) {
419 if (path
[0] == '~') {
420 char *newpath
= expand_user_path(path
);
421 if (!newpath
|| (PATH_MAX
- 10 < strlen(newpath
))) {
426 * Copy back into the static buffer. A pity
427 * since newpath was not bounded, but other
428 * branches of the if are limited by PATH_MAX
431 strcpy(used_path
, newpath
); free(newpath
);
432 strcpy(validated_path
, path
);
435 else if (PATH_MAX
- 10 < len
)
438 path
= strcpy(used_path
, path
);
439 strcpy(validated_path
, path
);
442 for (i
= 0; suffix
[i
]; i
++) {
443 strcpy(path
+ len
, suffix
[i
]);
444 if (!access(path
, F_OK
)) {
445 strcat(validated_path
, suffix
[i
]);
449 if (!suffix
[i
] || chdir(path
))
451 path
= validated_path
;
453 else if (chdir(path
))
456 if (access("objects", X_OK
) == 0 && access("refs", X_OK
) == 0 &&
457 validate_headref("HEAD") == 0) {
459 check_repository_format();
466 int set_shared_perm(const char *path
, int mode
)
469 int tweak
, shared
, orig_mode
;
471 if (!shared_repository
) {
473 return chmod(path
, mode
& ~S_IFMT
);
477 if (lstat(path
, &st
) < 0)
483 if (shared_repository
< 0)
484 shared
= -shared_repository
;
486 shared
= shared_repository
;
489 if (!(mode
& S_IWUSR
))
492 /* Copy read bits to execute bits */
493 tweak
|= (tweak
& 0444) >> 2;
494 if (shared_repository
< 0)
495 mode
= (mode
& ~0777) | tweak
;
500 /* Copy read bits to execute bits */
501 mode
|= (shared
& 0444) >> 2;
502 mode
|= FORCE_DIR_SET_GID
;
505 if (((shared_repository
< 0
506 ? (orig_mode
& (FORCE_DIR_SET_GID
| 0777))
507 : (orig_mode
& mode
)) != mode
) &&
508 chmod(path
, (mode
& ~S_IFMT
)) < 0)
513 const char *make_relative_path(const char *abs
, const char *base
)
515 static char buf
[PATH_MAX
+ 1];
518 if (!base
|| !base
[0])
521 if (is_dir_sep(base
[i
])) {
522 if (!is_dir_sep(abs
[j
]))
524 while (is_dir_sep(base
[i
]))
526 while (is_dir_sep(abs
[j
]))
529 } else if (abs
[j
] != base
[i
]) {
536 /* "/foo" is a prefix of "/foo" */
538 /* "/foo" is not a prefix of "/foobar" */
539 !is_dir_sep(base
[i
-1]) && !is_dir_sep(abs
[j
])
542 while (is_dir_sep(abs
[j
]))
547 strcpy(buf
, abs
+ j
);
552 * It is okay if dst == src, but they should not overlap otherwise.
554 * Performs the following normalizations on src, storing the result in dst:
555 * - Ensures that components are separated by '/' (Windows only)
556 * - Squashes sequences of '/'.
557 * - Removes "." components.
558 * - Removes ".." components, and the components the precede them.
559 * Returns failure (non-zero) if a ".." component appears as first path
560 * component anytime during the normalization. Otherwise, returns success (0).
562 * Note that this function is purely textual. It does not follow symlinks,
563 * verify the existence of the path, or make any system calls.
565 int normalize_path_copy(char *dst
, const char *src
)
569 if (has_dos_drive_prefix(src
)) {
575 if (is_dir_sep(*src
)) {
577 while (is_dir_sep(*src
))
585 * A path component that begins with . could be
587 * (1) "." and ends -- ignore and terminate.
588 * (2) "./" -- ignore them, eat slash and continue.
589 * (3) ".." and ends -- strip one and terminate.
590 * (4) "../" -- strip one, eat slash and continue.
596 } else if (is_dir_sep(src
[1])) {
599 while (is_dir_sep(*src
))
602 } else if (src
[1] == '.') {
607 } else if (is_dir_sep(src
[2])) {
610 while (is_dir_sep(*src
))
617 /* copy up to the next '/', and eat all '/' */
618 while ((c
= *src
++) != '\0' && !is_dir_sep(c
))
622 while (is_dir_sep(c
))
631 * dst0..dst is prefix portion, and dst[-1] is '/';
634 dst
--; /* go to trailing '/' */
637 /* Windows: dst[-1] cannot be backslash anymore */
638 while (dst0
< dst
&& dst
[-1] != '/')
646 * path = Canonical absolute path
647 * prefix_list = Colon-separated list of absolute paths
649 * Determines, for each path in prefix_list, whether the "prefix" really
650 * is an ancestor directory of path. Returns the length of the longest
651 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
652 * is an ancestor. (Note that this means 0 is returned if prefix_list is
653 * "/".) "/foo" is not considered an ancestor of "/foobar". Directories
654 * are not considered to be their own ancestors. path must be in a
655 * canonical form: empty components, or "." or ".." components are not
656 * allowed. prefix_list may be null, which is like "".
658 int longest_ancestor_length(const char *path
, const char *prefix_list
)
660 char buf
[PATH_MAX
+1];
661 const char *ceil
, *colon
;
662 int len
, max_len
= -1;
664 if (prefix_list
== NULL
|| !strcmp(path
, "/"))
667 for (colon
= ceil
= prefix_list
; *colon
; ceil
= colon
+1) {
668 for (colon
= ceil
; *colon
&& *colon
!= PATH_SEP
; colon
++);
670 if (len
== 0 || len
> PATH_MAX
|| !is_absolute_path(ceil
))
672 strlcpy(buf
, ceil
, len
+1);
673 if (normalize_path_copy(buf
, buf
) < 0)
676 if (len
> 0 && buf
[len
-1] == '/')
679 if (!strncmp(path
, buf
, len
) &&
689 /* strip arbitrary amount of directory separators at end of path */
690 static inline int chomp_trailing_dir_sep(const char *path
, int len
)
692 while (len
&& is_dir_sep(path
[len
- 1]))
698 * If path ends with suffix (complete path components), returns the
699 * part before suffix (sans trailing directory separators).
700 * Otherwise returns NULL.
702 char *strip_path_suffix(const char *path
, const char *suffix
)
704 int path_len
= strlen(path
), suffix_len
= strlen(suffix
);
710 if (is_dir_sep(path
[path_len
- 1])) {
711 if (!is_dir_sep(suffix
[suffix_len
- 1]))
713 path_len
= chomp_trailing_dir_sep(path
, path_len
);
714 suffix_len
= chomp_trailing_dir_sep(suffix
, suffix_len
);
716 else if (path
[--path_len
] != suffix
[--suffix_len
])
720 if (path_len
&& !is_dir_sep(path
[path_len
- 1]))
722 return xstrndup(path
, chomp_trailing_dir_sep(path
, path_len
));
725 int daemon_avoid_alias(const char *p
)
730 * This resurrects the belts and suspenders paranoia check by HPA
731 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
732 * does not do getcwd() based path canonicalization.
734 * sl becomes true immediately after seeing '/' and continues to
735 * be true as long as dots continue after that without intervening
738 if (!p
|| (*p
!= '/' && *p
!= '~'))
748 else if (ch
== '/') {
750 /* reject //, /./ and /../ */
755 if (0 < ndot
&& ndot
< 3)
756 /* reject /.$ and /..$ */
765 else if (ch
== '/') {
772 int offset_1st_component(const char *path
)
774 if (has_dos_drive_prefix(path
))
775 return 2 + is_dir_sep(path
[2]);
776 return is_dir_sep(path
[0]);