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
);
126 /* git_mkstemp() - create tmp file honoring TMPDIR variable */
127 int git_mkstemp(char *path
, size_t len
, const char *template)
132 tmp
= getenv("TMPDIR");
135 n
= snprintf(path
, len
, "%s/%s", tmp
, template);
137 errno
= ENAMETOOLONG
;
140 return mkstemp(path
);
143 /* git_mkstemps() - create tmp file with suffix honoring TMPDIR variable. */
144 int git_mkstemps(char *path
, size_t len
, const char *template, int suffix_len
)
149 tmp
= getenv("TMPDIR");
152 n
= snprintf(path
, len
, "%s/%s", tmp
, template);
154 errno
= ENAMETOOLONG
;
157 return mkstemps(path
, suffix_len
);
160 /* Adapted from libiberty's mkstemp.c. */
163 #define TMP_MAX 16384
165 int gitmkstemps(char *pattern
, int suffix_len
)
167 static const char letters
[] =
168 "abcdefghijklmnopqrstuvwxyz"
169 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
171 static const int num_letters
= 62;
178 len
= strlen(pattern
);
180 if (len
< 6 + suffix_len
) {
185 if (strncmp(&pattern
[len
- 6 - suffix_len
], "XXXXXX", 6)) {
191 * Replace pattern's XXXXXX characters with randomness.
192 * Try TMP_MAX different filenames.
194 gettimeofday(&tv
, NULL
);
195 value
= ((size_t)(tv
.tv_usec
<< 16)) ^ tv
.tv_sec
^ getpid();
196 template = &pattern
[len
- 6 - suffix_len
];
197 for (count
= 0; count
< TMP_MAX
; ++count
) {
199 /* Fill in the random bits. */
200 template[0] = letters
[v
% num_letters
]; v
/= num_letters
;
201 template[1] = letters
[v
% num_letters
]; v
/= num_letters
;
202 template[2] = letters
[v
% num_letters
]; v
/= num_letters
;
203 template[3] = letters
[v
% num_letters
]; v
/= num_letters
;
204 template[4] = letters
[v
% num_letters
]; v
/= num_letters
;
205 template[5] = letters
[v
% num_letters
]; v
/= num_letters
;
207 fd
= open(pattern
, O_CREAT
| O_EXCL
| O_RDWR
, 0600);
211 * Fatal error (EPERM, ENOSPC etc).
212 * It doesn't make sense to loop.
217 * This is a random value. It is only necessary that
218 * the next TMP_MAX values generated by adding 7777 to
219 * VALUE are different with (module 2^32).
223 /* We return the null string if we can't find a unique file name. */
229 int validate_headref(const char *path
)
232 char *buf
, buffer
[256];
233 unsigned char sha1
[20];
237 if (lstat(path
, &st
) < 0)
240 /* Make sure it is a "refs/.." symlink */
241 if (S_ISLNK(st
.st_mode
)) {
242 len
= readlink(path
, buffer
, sizeof(buffer
)-1);
243 if (len
>= 5 && !memcmp("refs/", buffer
, 5))
249 * Anything else, just open it and try to see if it is a symbolic ref.
251 fd
= open(path
, O_RDONLY
);
254 len
= read_in_full(fd
, buffer
, sizeof(buffer
)-1);
258 * Is it a symbolic ref?
262 if (!memcmp("ref:", buffer
, 4)) {
265 while (len
&& isspace(*buf
))
267 if (len
>= 5 && !memcmp("refs/", buf
, 5))
272 * Is this a detached HEAD?
274 if (!get_sha1_hex(buffer
, sha1
))
280 static struct passwd
*getpw_str(const char *username
, size_t len
)
283 char *username_z
= xmalloc(len
+ 1);
284 memcpy(username_z
, username
, len
);
285 username_z
[len
] = '\0';
286 pw
= getpwnam(username_z
);
292 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
293 * then it is a newly allocated string. Returns NULL on getpw failure or
296 char *expand_user_path(const char *path
)
298 struct strbuf user_path
= STRBUF_INIT
;
299 const char *first_slash
= strchrnul(path
, '/');
300 const char *to_copy
= path
;
304 if (path
[0] == '~') {
305 const char *username
= path
+ 1;
306 size_t username_len
= first_slash
- username
;
307 if (username_len
== 0) {
308 const char *home
= getenv("HOME");
309 strbuf_add(&user_path
, home
, strlen(home
));
311 struct passwd
*pw
= getpw_str(username
, username_len
);
314 strbuf_add(&user_path
, pw
->pw_dir
, strlen(pw
->pw_dir
));
316 to_copy
= first_slash
;
318 strbuf_add(&user_path
, to_copy
, strlen(to_copy
));
319 return strbuf_detach(&user_path
, NULL
);
321 strbuf_release(&user_path
);
326 * First, one directory to try is determined by the following algorithm.
328 * (0) If "strict" is given, the path is used as given and no DWIM is
330 * (1) "~/path" to mean path under the running user's home directory;
331 * (2) "~user/path" to mean path under named user's home directory;
332 * (3) "relative/path" to mean cwd relative directory; or
333 * (4) "/absolute/path" to mean absolute directory.
335 * Unless "strict" is given, we try access() for existence of "%s.git/.git",
336 * "%s/.git", "%s.git", "%s" in this order. The first one that exists is
339 * Second, we try chdir() to that. Upon failure, we return NULL.
341 * Then, we try if the current directory is a valid git repository.
342 * Upon failure, we return NULL.
344 * If all goes well, we return the directory we used to chdir() (but
345 * before ~user is expanded), avoiding getcwd() resolving symbolic
346 * links. User relative paths are also returned as they are given,
347 * except DWIM suffixing.
349 char *enter_repo(char *path
, int strict
)
351 static char used_path
[PATH_MAX
];
352 static char validated_path
[PATH_MAX
];
358 static const char *suffix
[] = {
359 ".git/.git", "/.git", ".git", "", NULL
,
361 int len
= strlen(path
);
363 while ((1 < len
) && (path
[len
-1] == '/')) {
369 if (path
[0] == '~') {
370 char *newpath
= expand_user_path(path
);
371 if (!newpath
|| (PATH_MAX
- 10 < strlen(newpath
))) {
376 * Copy back into the static buffer. A pity
377 * since newpath was not bounded, but other
378 * branches of the if are limited by PATH_MAX
381 strcpy(used_path
, newpath
); free(newpath
);
382 strcpy(validated_path
, path
);
385 else if (PATH_MAX
- 10 < len
)
388 path
= strcpy(used_path
, path
);
389 strcpy(validated_path
, path
);
392 for (i
= 0; suffix
[i
]; i
++) {
393 strcpy(path
+ len
, suffix
[i
]);
394 if (!access(path
, F_OK
)) {
395 strcat(validated_path
, suffix
[i
]);
399 if (!suffix
[i
] || chdir(path
))
401 path
= validated_path
;
403 else if (chdir(path
))
406 if (access("objects", X_OK
) == 0 && access("refs", X_OK
) == 0 &&
407 validate_headref("HEAD") == 0) {
408 setenv(GIT_DIR_ENVIRONMENT
, ".", 1);
409 check_repository_format();
416 int set_shared_perm(const char *path
, int mode
)
419 int tweak
, shared
, orig_mode
;
421 if (!shared_repository
) {
423 return chmod(path
, mode
& ~S_IFMT
);
427 if (lstat(path
, &st
) < 0)
433 if (shared_repository
< 0)
434 shared
= -shared_repository
;
436 shared
= shared_repository
;
439 if (!(mode
& S_IWUSR
))
442 /* Copy read bits to execute bits */
443 tweak
|= (tweak
& 0444) >> 2;
444 if (shared_repository
< 0)
445 mode
= (mode
& ~0777) | tweak
;
450 /* Copy read bits to execute bits */
451 mode
|= (shared
& 0444) >> 2;
452 mode
|= FORCE_DIR_SET_GID
;
455 if (((shared_repository
< 0
456 ? (orig_mode
& (FORCE_DIR_SET_GID
| 0777))
457 : (orig_mode
& mode
)) != mode
) &&
458 chmod(path
, (mode
& ~S_IFMT
)) < 0)
463 const char *make_relative_path(const char *abs
, const char *base
)
465 static char buf
[PATH_MAX
+ 1];
468 if (!base
|| !base
[0])
471 if (is_dir_sep(base
[i
])) {
472 if (!is_dir_sep(abs
[j
]))
474 while (is_dir_sep(base
[i
]))
476 while (is_dir_sep(abs
[j
]))
479 } else if (abs
[j
] != base
[i
]) {
486 /* "/foo" is a prefix of "/foo" */
488 /* "/foo" is not a prefix of "/foobar" */
489 !is_dir_sep(base
[i
-1]) && !is_dir_sep(abs
[j
])
492 while (is_dir_sep(abs
[j
]))
497 strcpy(buf
, abs
+ j
);
502 * It is okay if dst == src, but they should not overlap otherwise.
504 * Performs the following normalizations on src, storing the result in dst:
505 * - Ensures that components are separated by '/' (Windows only)
506 * - Squashes sequences of '/'.
507 * - Removes "." components.
508 * - Removes ".." components, and the components the precede them.
509 * Returns failure (non-zero) if a ".." component appears as first path
510 * component anytime during the normalization. Otherwise, returns success (0).
512 * Note that this function is purely textual. It does not follow symlinks,
513 * verify the existence of the path, or make any system calls.
515 int normalize_path_copy(char *dst
, const char *src
)
519 if (has_dos_drive_prefix(src
)) {
525 if (is_dir_sep(*src
)) {
527 while (is_dir_sep(*src
))
535 * A path component that begins with . could be
537 * (1) "." and ends -- ignore and terminate.
538 * (2) "./" -- ignore them, eat slash and continue.
539 * (3) ".." and ends -- strip one and terminate.
540 * (4) "../" -- strip one, eat slash and continue.
546 } else if (is_dir_sep(src
[1])) {
549 while (is_dir_sep(*src
))
552 } else if (src
[1] == '.') {
557 } else if (is_dir_sep(src
[2])) {
560 while (is_dir_sep(*src
))
567 /* copy up to the next '/', and eat all '/' */
568 while ((c
= *src
++) != '\0' && !is_dir_sep(c
))
572 while (is_dir_sep(c
))
581 * dst0..dst is prefix portion, and dst[-1] is '/';
584 dst
--; /* go to trailing '/' */
587 /* Windows: dst[-1] cannot be backslash anymore */
588 while (dst0
< dst
&& dst
[-1] != '/')
596 * path = Canonical absolute path
597 * prefix_list = Colon-separated list of absolute paths
599 * Determines, for each path in prefix_list, whether the "prefix" really
600 * is an ancestor directory of path. Returns the length of the longest
601 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
602 * is an ancestor. (Note that this means 0 is returned if prefix_list is
603 * "/".) "/foo" is not considered an ancestor of "/foobar". Directories
604 * are not considered to be their own ancestors. path must be in a
605 * canonical form: empty components, or "." or ".." components are not
606 * allowed. prefix_list may be null, which is like "".
608 int longest_ancestor_length(const char *path
, const char *prefix_list
)
610 char buf
[PATH_MAX
+1];
611 const char *ceil
, *colon
;
612 int len
, max_len
= -1;
614 if (prefix_list
== NULL
|| !strcmp(path
, "/"))
617 for (colon
= ceil
= prefix_list
; *colon
; ceil
= colon
+1) {
618 for (colon
= ceil
; *colon
&& *colon
!= PATH_SEP
; colon
++);
620 if (len
== 0 || len
> PATH_MAX
|| !is_absolute_path(ceil
))
622 strlcpy(buf
, ceil
, len
+1);
623 if (normalize_path_copy(buf
, buf
) < 0)
626 if (len
> 0 && buf
[len
-1] == '/')
629 if (!strncmp(path
, buf
, len
) &&
639 /* strip arbitrary amount of directory separators at end of path */
640 static inline int chomp_trailing_dir_sep(const char *path
, int len
)
642 while (len
&& is_dir_sep(path
[len
- 1]))
648 * If path ends with suffix (complete path components), returns the
649 * part before suffix (sans trailing directory separators).
650 * Otherwise returns NULL.
652 char *strip_path_suffix(const char *path
, const char *suffix
)
654 int path_len
= strlen(path
), suffix_len
= strlen(suffix
);
660 if (is_dir_sep(path
[path_len
- 1])) {
661 if (!is_dir_sep(suffix
[suffix_len
- 1]))
663 path_len
= chomp_trailing_dir_sep(path
, path_len
);
664 suffix_len
= chomp_trailing_dir_sep(suffix
, suffix_len
);
666 else if (path
[--path_len
] != suffix
[--suffix_len
])
670 if (path_len
&& !is_dir_sep(path
[path_len
- 1]))
672 return xstrndup(path
, chomp_trailing_dir_sep(path
, path_len
));
675 int daemon_avoid_alias(const char *p
)
680 * This resurrects the belts and suspenders paranoia check by HPA
681 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
682 * does not do getcwd() based path canonicalizations.
684 * sl becomes true immediately after seeing '/' and continues to
685 * be true as long as dots continue after that without intervening
688 if (!p
|| (*p
!= '/' && *p
!= '~'))
698 else if (ch
== '/') {
700 /* reject //, /./ and /../ */
705 if (0 < ndot
&& ndot
< 3)
706 /* reject /.$ and /..$ */
715 else if (ch
== '/') {