1#include "cache.h"
2#include "dir.h"
3
4static int inside_git_dir = -1;
5static int inside_work_tree = -1;
6
7const char *prefix_path(const char *prefix, int len, const char *path)
8{
9 const char *orig = path;
10 char *sanitized = xmalloc(len + strlen(path) + 1);
11 if (is_absolute_path(orig))
12 strcpy(sanitized, path);
13 else {
14 if (len)
15 memcpy(sanitized, prefix, len);
16 strcpy(sanitized + len, path);
17 }
18 if (normalize_path_copy(sanitized, sanitized))
19 goto error_out;
20 if (is_absolute_path(orig)) {
21 const char *work_tree = get_git_work_tree();
22 size_t len = strlen(work_tree);
23 size_t total = strlen(sanitized) + 1;
24 if (strncmp(sanitized, work_tree, len) ||
25 (sanitized[len] != '\0' && sanitized[len] != '/')) {
26 error_out:
27 die("'%s' is outside repository", orig);
28 }
29 if (sanitized[len] == '/')
30 len++;
31 memmove(sanitized, sanitized + len, total - len);
32 }
33 return sanitized;
34}
35
36/*
37 * Unlike prefix_path, this should be used if the named file does
38 * not have to interact with index entry; i.e. name of a random file
39 * on the filesystem.
40 */
41const char *prefix_filename(const char *pfx, int pfx_len, const char *arg)
42{
43 static char path[PATH_MAX];
44#ifndef __MINGW32__
45 if (!pfx || !*pfx || is_absolute_path(arg))
46 return arg;
47 memcpy(path, pfx, pfx_len);
48 strcpy(path + pfx_len, arg);
49#else
50 char *p;
51 /* don't add prefix to absolute paths, but still replace '\' by '/' */
52 if (is_absolute_path(arg))
53 pfx_len = 0;
54 else
55 memcpy(path, pfx, pfx_len);
56 strcpy(path + pfx_len, arg);
57 for (p = path + pfx_len; *p; p++)
58 if (*p == '\\')
59 *p = '/';
60#endif
61 return path;
62}
63
64/*
65 * Verify a filename that we got as an argument for a pathspec
66 * entry. Note that a filename that begins with "-" never verifies
67 * as true, because even if such a filename were to exist, we want
68 * it to be preceded by the "--" marker (or we want the user to
69 * use a format like "./-filename")
70 */
71void verify_filename(const char *prefix, const char *arg)
72{
73 const char *name;
74 struct stat st;
75
76 if (*arg == '-')
77 die("bad flag '%s' used after filename", arg);
78 name = prefix ? prefix_filename(prefix, strlen(prefix), arg) : arg;
79 if (!lstat(name, &st))
80 return;
81 if (errno == ENOENT)
82 die("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
83 "Use '--' to separate paths from revisions", arg);
84 die_errno("failed to stat '%s'", arg);
85}
86
87/*
88 * Opposite of the above: the command line did not have -- marker
89 * and we parsed the arg as a refname. It should not be interpretable
90 * as a filename.
91 */
92void verify_non_filename(const char *prefix, const char *arg)
93{
94 const char *name;
95 struct stat st;
96
97 if (!is_inside_work_tree() || is_inside_git_dir())
98 return;
99 if (*arg == '-')
100 return; /* flag */
101 name = prefix ? prefix_filename(prefix, strlen(prefix), arg) : arg;
102 if (!lstat(name, &st))
103 die("ambiguous argument '%s': both revision and filename\n"
104 "Use '--' to separate filenames from revisions", arg);
105 if (errno != ENOENT && errno != ENOTDIR)
106 die_errno("failed to stat '%s'", arg);
107}
108
109const char **get_pathspec(const char *prefix, const char **pathspec)
110{
111 const char *entry = *pathspec;
112 const char **src, **dst;
113 int prefixlen;
114
115 if (!prefix && !entry)
116 return NULL;
117
118 if (!entry) {
119 static const char *spec[2];
120 spec[0] = prefix;
121 spec[1] = NULL;
122 return spec;
123 }
124
125 /* Otherwise we have to re-write the entries.. */
126 src = pathspec;
127 dst = pathspec;
128 prefixlen = prefix ? strlen(prefix) : 0;
129 while (*src) {
130 const char *p = prefix_path(prefix, prefixlen, *src);
131 *(dst++) = p;
132 src++;
133 }
134 *dst = NULL;
135 if (!*pathspec)
136 return NULL;
137 return pathspec;
138}
139
140/*
141 * Test if it looks like we're at a git directory.
142 * We want to see:
143 *
144 * - either an objects/ directory _or_ the proper
145 * GIT_OBJECT_DIRECTORY environment variable
146 * - a refs/ directory
147 * - either a HEAD symlink or a HEAD file that is formatted as
148 * a proper "ref:", or a regular file HEAD that has a properly
149 * formatted sha1 object name.
150 */
151static int is_git_directory(const char *suspect)
152{
153 char path[PATH_MAX];
154 size_t len = strlen(suspect);
155
156 if (PATH_MAX <= len + strlen("/objects"))
157 die("Too long path: %.*s", 60, suspect);
158 strcpy(path, suspect);
159 if (getenv(DB_ENVIRONMENT)) {
160 if (access(getenv(DB_ENVIRONMENT), X_OK))
161 return 0;
162 }
163 else {
164 strcpy(path + len, "/objects");
165 if (access(path, X_OK))
166 return 0;
167 }
168
169 strcpy(path + len, "/refs");
170 if (access(path, X_OK))
171 return 0;
172
173 strcpy(path + len, "/HEAD");
174 if (validate_headref(path))
175 return 0;
176
177 return 1;
178}
179
180int is_inside_git_dir(void)
181{
182 if (inside_git_dir < 0)
183 inside_git_dir = is_inside_dir(get_git_dir());
184 return inside_git_dir;
185}
186
187int is_inside_work_tree(void)
188{
189 if (inside_work_tree < 0)
190 inside_work_tree = is_inside_dir(get_git_work_tree());
191 return inside_work_tree;
192}
193
194/*
195 * set_work_tree() is only ever called if you set GIT_DIR explicitely.
196 * The old behaviour (which we retain here) is to set the work tree root
197 * to the cwd, unless overridden by the config, the command line, or
198 * GIT_WORK_TREE.
199 */
200static const char *set_work_tree(const char *dir)
201{
202 char buffer[PATH_MAX + 1];
203
204 if (!getcwd(buffer, sizeof(buffer)))
205 die ("Could not get the current working directory");
206 git_work_tree_cfg = xstrdup(buffer);
207 inside_work_tree = 1;
208
209 return NULL;
210}
211
212void setup_work_tree(void)
213{
214 const char *work_tree, *git_dir;
215 static int initialized = 0;
216
217 if (initialized)
218 return;
219 work_tree = get_git_work_tree();
220 git_dir = get_git_dir();
221 if (!is_absolute_path(git_dir))
222 git_dir = make_absolute_path(git_dir);
223 if (!work_tree || chdir(work_tree))
224 die("This operation must be run in a work tree");
225 set_git_dir(make_relative_path(git_dir, work_tree));
226 initialized = 1;
227}
228
229static int check_repository_format_gently(int *nongit_ok)
230{
231 git_config(check_repository_format_version, NULL);
232 if (GIT_REPO_VERSION < repository_format_version) {
233 if (!nongit_ok)
234 die ("Expected git repo version <= %d, found %d",
235 GIT_REPO_VERSION, repository_format_version);
236 warning("Expected git repo version <= %d, found %d",
237 GIT_REPO_VERSION, repository_format_version);
238 warning("Please upgrade Git");
239 *nongit_ok = -1;
240 return -1;
241 }
242 return 0;
243}
244
245/*
246 * Try to read the location of the git directory from the .git file,
247 * return path to git directory if found.
248 */
249const char *read_gitfile_gently(const char *path)
250{
251 char *buf;
252 struct stat st;
253 int fd;
254 size_t len;
255
256 if (stat(path, &st))
257 return NULL;
258 if (!S_ISREG(st.st_mode))
259 return NULL;
260 fd = open(path, O_RDONLY);
261 if (fd < 0)
262 die_errno("Error opening '%s'", path);
263 buf = xmalloc(st.st_size + 1);
264 len = read_in_full(fd, buf, st.st_size);
265 close(fd);
266 if (len != st.st_size)
267 die("Error reading %s", path);
268 buf[len] = '\0';
269 if (prefixcmp(buf, "gitdir: "))
270 die("Invalid gitfile format: %s", path);
271 while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
272 len--;
273 if (len < 9)
274 die("No path in gitfile: %s", path);
275 buf[len] = '\0';
276 if (!is_git_directory(buf + 8))
277 die("Not a git repository: %s", buf + 8);
278 path = make_absolute_path(buf + 8);
279 free(buf);
280 return path;
281}
282
283/*
284 * We cannot decide in this function whether we are in the work tree or
285 * not, since the config can only be read _after_ this function was called.
286 */
287const char *setup_git_directory_gently(int *nongit_ok)
288{
289 const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
290 const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
291 static char cwd[PATH_MAX+1];
292 const char *gitdirenv;
293 const char *gitfile_dir;
294 int len, offset, ceil_offset;
295
296 /*
297 * Let's assume that we are in a git repository.
298 * If it turns out later that we are somewhere else, the value will be
299 * updated accordingly.
300 */
301 if (nongit_ok)
302 *nongit_ok = 0;
303
304 /*
305 * If GIT_DIR is set explicitly, we're not going
306 * to do any discovery, but we still do repository
307 * validation.
308 */
309 gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
310 if (gitdirenv) {
311 if (PATH_MAX - 40 < strlen(gitdirenv))
312 die("'$%s' too big", GIT_DIR_ENVIRONMENT);
313 if (is_git_directory(gitdirenv)) {
314 static char buffer[1024 + 1];
315 const char *retval;
316
317 if (!work_tree_env) {
318 retval = set_work_tree(gitdirenv);
319 /* config may override worktree */
320 if (check_repository_format_gently(nongit_ok))
321 return NULL;
322 return retval;
323 }
324 if (check_repository_format_gently(nongit_ok))
325 return NULL;
326 retval = get_relative_cwd(buffer, sizeof(buffer) - 1,
327 get_git_work_tree());
328 if (!retval || !*retval)
329 return NULL;
330 set_git_dir(make_absolute_path(gitdirenv));
331 if (chdir(work_tree_env) < 0)
332 die_errno ("Could not chdir to '%s'", work_tree_env);
333 strcat(buffer, "/");
334 return retval;
335 }
336 if (nongit_ok) {
337 *nongit_ok = 1;
338 return NULL;
339 }
340 die("Not a git repository: '%s'", gitdirenv);
341 }
342
343 if (!getcwd(cwd, sizeof(cwd)-1))
344 die_errno("Unable to read current working directory");
345
346 ceil_offset = longest_ancestor_length(cwd, env_ceiling_dirs);
347 if (ceil_offset < 0 && has_dos_drive_prefix(cwd))
348 ceil_offset = 1;
349
350 /*
351 * Test in the following order (relative to the cwd):
352 * - .git (file containing "gitdir: <path>")
353 * - .git/
354 * - ./ (bare)
355 * - ../.git
356 * - ../.git/
357 * - ../ (bare)
358 * - ../../.git/
359 * etc.
360 */
361 offset = len = strlen(cwd);
362 for (;;) {
363 gitfile_dir = read_gitfile_gently(DEFAULT_GIT_DIR_ENVIRONMENT);
364 if (gitfile_dir) {
365 if (set_git_dir(gitfile_dir))
366 die("Repository setup failed");
367 break;
368 }
369 if (is_git_directory(DEFAULT_GIT_DIR_ENVIRONMENT))
370 break;
371 if (is_git_directory(".")) {
372 inside_git_dir = 1;
373 if (!work_tree_env)
374 inside_work_tree = 0;
375 if (offset != len) {
376 cwd[offset] = '\0';
377 setenv(GIT_DIR_ENVIRONMENT, cwd, 1);
378 } else
379 setenv(GIT_DIR_ENVIRONMENT, ".", 1);
380 check_repository_format_gently(nongit_ok);
381 return NULL;
382 }
383 while (--offset > ceil_offset && cwd[offset] != '/');
384 if (offset <= ceil_offset) {
385 if (nongit_ok) {
386 if (chdir(cwd))
387 die_errno("Cannot come back to cwd");
388 *nongit_ok = 1;
389 return NULL;
390 }
391 die("Not a git repository (or any of the parent directories): %s", DEFAULT_GIT_DIR_ENVIRONMENT);
392 }
393 if (chdir(".."))
394 die_errno("Cannot change to '%s/..'", cwd);
395 }
396
397 inside_git_dir = 0;
398 if (!work_tree_env)
399 inside_work_tree = 1;
400 git_work_tree_cfg = xstrndup(cwd, offset);
401 if (check_repository_format_gently(nongit_ok))
402 return NULL;
403 if (offset == len)
404 return NULL;
405
406 /* Make "offset" point to past the '/', and add a '/' at the end */
407 offset++;
408 cwd[len++] = '/';
409 cwd[len] = 0;
410 return cwd + offset;
411}
412
413int git_config_perm(const char *var, const char *value)
414{
415 int i;
416 char *endptr;
417
418 if (value == NULL)
419 return PERM_GROUP;
420
421 if (!strcmp(value, "umask"))
422 return PERM_UMASK;
423 if (!strcmp(value, "group"))
424 return PERM_GROUP;
425 if (!strcmp(value, "all") ||
426 !strcmp(value, "world") ||
427 !strcmp(value, "everybody"))
428 return PERM_EVERYBODY;
429
430 /* Parse octal numbers */
431 i = strtol(value, &endptr, 8);
432
433 /* If not an octal number, maybe true/false? */
434 if (*endptr != 0)
435 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
436
437 /*
438 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
439 * a chmod value to restrict to.
440 */
441 switch (i) {
442 case PERM_UMASK: /* 0 */
443 return PERM_UMASK;
444 case OLD_PERM_GROUP: /* 1 */
445 return PERM_GROUP;
446 case OLD_PERM_EVERYBODY: /* 2 */
447 return PERM_EVERYBODY;
448 }
449
450 /* A filemode value was given: 0xxx */
451
452 if ((i & 0600) != 0600)
453 die("Problem with core.sharedRepository filemode value "
454 "(0%.3o).\nThe owner of files must always have "
455 "read and write permissions.", i);
456
457 /*
458 * Mask filemode value. Others can not get write permission.
459 * x flags for directories are handled separately.
460 */
461 return -(i & 0666);
462}
463
464int check_repository_format_version(const char *var, const char *value, void *cb)
465{
466 if (strcmp(var, "core.repositoryformatversion") == 0)
467 repository_format_version = git_config_int(var, value);
468 else if (strcmp(var, "core.sharedrepository") == 0)
469 shared_repository = git_config_perm(var, value);
470 else if (strcmp(var, "core.bare") == 0) {
471 is_bare_repository_cfg = git_config_bool(var, value);
472 if (is_bare_repository_cfg == 1)
473 inside_work_tree = -1;
474 } else if (strcmp(var, "core.worktree") == 0) {
475 if (!value)
476 return config_error_nonbool(var);
477 free(git_work_tree_cfg);
478 git_work_tree_cfg = xstrdup(value);
479 inside_work_tree = -1;
480 }
481 return 0;
482}
483
484int check_repository_format(void)
485{
486 return check_repository_format_gently(NULL);
487}
488
489const char *setup_git_directory(void)
490{
491 const char *retval = setup_git_directory_gently(NULL);
492
493 /* If the work tree is not the default one, recompute prefix */
494 if (inside_work_tree < 0) {
495 static char buffer[PATH_MAX + 1];
496 char *rel;
497 if (retval && chdir(retval))
498 die_errno ("Could not jump back into original cwd");
499 rel = get_relative_cwd(buffer, PATH_MAX, get_git_work_tree());
500 if (rel && *rel && chdir(get_git_work_tree()))
501 die_errno ("Could not jump to working directory");
502 return rel && *rel ? strcat(rel, "/") : NULL;
503 }
504
505 return retval;
506}