Coverage Report

Created: 2026-03-31 06:24

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/git/setup.c
Line
Count
Source
1
#define USE_THE_REPOSITORY_VARIABLE
2
#define DISABLE_SIGN_COMPARE_WARNINGS
3
4
#include "git-compat-util.h"
5
#include "abspath.h"
6
#include "copy.h"
7
#include "environment.h"
8
#include "exec-cmd.h"
9
#include "gettext.h"
10
#include "hex.h"
11
#include "object-file.h"
12
#include "object-name.h"
13
#include "refs.h"
14
#include "replace-object.h"
15
#include "repository.h"
16
#include "config.h"
17
#include "dir.h"
18
#include "setup.h"
19
#include "shallow.h"
20
#include "string-list.h"
21
#include "strvec.h"
22
#include "chdir-notify.h"
23
#include "path.h"
24
#include "quote.h"
25
#include "trace.h"
26
#include "trace2.h"
27
#include "worktree.h"
28
29
static int inside_git_dir = -1;
30
static int inside_work_tree = -1;
31
static int work_tree_config_is_bogus;
32
enum allowed_bare_repo {
33
  ALLOWED_BARE_REPO_EXPLICIT = 0,
34
  ALLOWED_BARE_REPO_ALL,
35
};
36
37
static struct startup_info the_startup_info;
38
struct startup_info *startup_info = &the_startup_info;
39
const char *tmp_original_cwd;
40
41
/*
42
 * The input parameter must contain an absolute path, and it must already be
43
 * normalized.
44
 *
45
 * Find the part of an absolute path that lies inside the work tree by
46
 * dereferencing symlinks outside the work tree, for example:
47
 * /dir1/repo/dir2/file   (work tree is /dir1/repo)      -> dir2/file
48
 * /dir/file              (work tree is /)               -> dir/file
49
 * /dir/symlink1/symlink2 (symlink1 points to work tree) -> symlink2
50
 * /dir/repolink/file     (repolink points to /dir/repo) -> file
51
 * /dir/repo              (exactly equal to work tree)   -> (empty string)
52
 */
53
static int abspath_part_inside_repo(char *path)
54
0
{
55
0
  size_t len;
56
0
  size_t wtlen;
57
0
  char *path0;
58
0
  int off;
59
0
  const char *work_tree = precompose_string_if_needed(repo_get_work_tree(the_repository));
60
0
  struct strbuf realpath = STRBUF_INIT;
61
62
0
  if (!work_tree)
63
0
    return -1;
64
0
  wtlen = strlen(work_tree);
65
0
  len = strlen(path);
66
0
  off = offset_1st_component(path);
67
68
  /* check if work tree is already the prefix */
69
0
  if (wtlen <= len && !fspathncmp(path, work_tree, wtlen)) {
70
0
    if (path[wtlen] == '/') {
71
0
      memmove(path, path + wtlen + 1, len - wtlen);
72
0
      return 0;
73
0
    } else if (path[wtlen - 1] == '/' || path[wtlen] == '\0') {
74
      /* work tree is the root, or the whole path */
75
0
      memmove(path, path + wtlen, len - wtlen + 1);
76
0
      return 0;
77
0
    }
78
    /* work tree might match beginning of a symlink to work tree */
79
0
    off = wtlen;
80
0
  }
81
0
  path0 = path;
82
0
  path += off;
83
84
  /* check each '/'-terminated level */
85
0
  while (*path) {
86
0
    path++;
87
0
    if (*path == '/') {
88
0
      *path = '\0';
89
0
      strbuf_realpath(&realpath, path0, 1);
90
0
      if (fspathcmp(realpath.buf, work_tree) == 0) {
91
0
        memmove(path0, path + 1, len - (path - path0));
92
0
        strbuf_release(&realpath);
93
0
        return 0;
94
0
      }
95
0
      *path = '/';
96
0
    }
97
0
  }
98
99
  /* check whole path */
100
0
  strbuf_realpath(&realpath, path0, 1);
101
0
  if (fspathcmp(realpath.buf, work_tree) == 0) {
102
0
    *path0 = '\0';
103
0
    strbuf_release(&realpath);
104
0
    return 0;
105
0
  }
106
107
0
  strbuf_release(&realpath);
108
0
  return -1;
109
0
}
110
111
/*
112
 * Normalize "path", prepending the "prefix" for relative paths. If
113
 * remaining_prefix is not NULL, return the actual prefix still
114
 * remains in the path. For example, prefix = sub1/sub2/ and path is
115
 *
116
 *  foo          -> sub1/sub2/foo  (full prefix)
117
 *  ../foo       -> sub1/foo       (remaining prefix is sub1/)
118
 *  ../../bar    -> bar            (no remaining prefix)
119
 *  ../../sub1/sub2/foo -> sub1/sub2/foo (but no remaining prefix)
120
 *  `pwd`/../bar -> sub1/bar       (no remaining prefix)
121
 */
122
char *prefix_path_gently(const char *prefix, int len,
123
       int *remaining_prefix, const char *path)
124
0
{
125
0
  const char *orig = path;
126
0
  char *sanitized;
127
0
  if (is_absolute_path(orig)) {
128
0
    sanitized = xmallocz(strlen(path));
129
0
    if (remaining_prefix)
130
0
      *remaining_prefix = 0;
131
0
    if (normalize_path_copy_len(sanitized, path, remaining_prefix)) {
132
0
      free(sanitized);
133
0
      return NULL;
134
0
    }
135
0
    if (abspath_part_inside_repo(sanitized)) {
136
0
      free(sanitized);
137
0
      return NULL;
138
0
    }
139
0
  } else {
140
0
    sanitized = xstrfmt("%.*s%s", len, len ? prefix : "", path);
141
0
    if (remaining_prefix)
142
0
      *remaining_prefix = len;
143
0
    if (normalize_path_copy_len(sanitized, sanitized, remaining_prefix)) {
144
0
      free(sanitized);
145
0
      return NULL;
146
0
    }
147
0
  }
148
0
  return sanitized;
149
0
}
150
151
char *prefix_path(const char *prefix, int len, const char *path)
152
0
{
153
0
  char *r = prefix_path_gently(prefix, len, NULL, path);
154
0
  if (!r) {
155
0
    const char *hint_path = repo_get_work_tree(the_repository);
156
0
    if (!hint_path)
157
0
      hint_path = repo_get_git_dir(the_repository);
158
0
    die(_("'%s' is outside repository at '%s'"), path,
159
0
        absolute_path(hint_path));
160
0
  }
161
0
  return r;
162
0
}
163
164
int path_inside_repo(const char *prefix, const char *path)
165
0
{
166
0
  int len = prefix ? strlen(prefix) : 0;
167
0
  char *r = prefix_path_gently(prefix, len, NULL, path);
168
0
  if (r) {
169
0
    free(r);
170
0
    return 1;
171
0
  }
172
0
  return 0;
173
0
}
174
175
int check_filename(const char *prefix, const char *arg)
176
0
{
177
0
  char *to_free = NULL;
178
0
  struct stat st;
179
180
0
  if (skip_prefix(arg, ":/", &arg)) {
181
0
    if (!*arg) /* ":/" is root dir, always exists */
182
0
      return 1;
183
0
    prefix = NULL;
184
0
  } else if (skip_prefix(arg, ":!", &arg) ||
185
0
       skip_prefix(arg, ":^", &arg)) {
186
0
    if (!*arg) /* excluding everything is silly, but allowed */
187
0
      return 1;
188
0
  }
189
190
0
  if (prefix)
191
0
    arg = to_free = prefix_filename(prefix, arg);
192
193
0
  if (!lstat(arg, &st)) {
194
0
    free(to_free);
195
0
    return 1; /* file exists */
196
0
  }
197
0
  if (is_missing_file_error(errno)) {
198
0
    free(to_free);
199
0
    return 0; /* file does not exist */
200
0
  }
201
0
  die_errno(_("failed to stat '%s'"), arg);
202
0
}
203
204
static void NORETURN die_verify_filename(struct repository *r,
205
           const char *prefix,
206
           const char *arg,
207
           int diagnose_misspelt_rev)
208
0
{
209
0
  if (!diagnose_misspelt_rev)
210
0
    die(_("%s: no such path in the working tree.\n"
211
0
          "Use 'git <command> -- <path>...' to specify paths that do not exist locally."),
212
0
        arg);
213
  /*
214
   * Saying "'(icase)foo' does not exist in the index" when the
215
   * user gave us ":(icase)foo" is just stupid.  A magic pathspec
216
   * begins with a colon and is followed by a non-alnum; do not
217
   * let maybe_die_on_misspelt_object_name() even trigger.
218
   */
219
0
  if (!(arg[0] == ':' && !isalnum(arg[1])))
220
0
    maybe_die_on_misspelt_object_name(r, arg, prefix);
221
222
  /* ... or fall back the most general message. */
223
0
  die(_("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
224
0
        "Use '--' to separate paths from revisions, like this:\n"
225
0
        "'git <command> [<revision>...] -- [<file>...]'"), arg);
226
227
0
}
228
229
/*
230
 * Check for arguments that don't resolve as actual files,
231
 * but which look sufficiently like pathspecs that we'll consider
232
 * them such for the purposes of rev/pathspec DWIM parsing.
233
 */
234
static int looks_like_pathspec(const char *arg)
235
0
{
236
0
  const char *p;
237
0
  int escaped = 0;
238
239
  /*
240
   * Wildcard characters imply the user is looking to match pathspecs
241
   * that aren't in the filesystem. Note that this doesn't include
242
   * backslash even though it's a glob special; by itself it doesn't
243
   * cause any increase in the match. Likewise ignore backslash-escaped
244
   * wildcard characters.
245
   */
246
0
  for (p = arg; *p; p++) {
247
0
    if (escaped) {
248
0
      escaped = 0;
249
0
    } else if (is_glob_special(*p)) {
250
0
      if (*p == '\\')
251
0
        escaped = 1;
252
0
      else
253
0
        return 1;
254
0
    }
255
0
  }
256
257
  /* long-form pathspec magic */
258
0
  if (starts_with(arg, ":("))
259
0
    return 1;
260
261
0
  return 0;
262
0
}
263
264
/*
265
 * Verify a filename that we got as an argument for a pathspec
266
 * entry. Note that a filename that begins with "-" never verifies
267
 * as true, because even if such a filename were to exist, we want
268
 * it to be preceded by the "--" marker (or we want the user to
269
 * use a format like "./-filename")
270
 *
271
 * The "diagnose_misspelt_rev" is used to provide a user-friendly
272
 * diagnosis when dying upon finding that "name" is not a pathname.
273
 * If set to 1, the diagnosis will try to diagnose "name" as an
274
 * invalid object name (e.g. HEAD:foo). If set to 0, the diagnosis
275
 * will only complain about an inexisting file.
276
 *
277
 * This function is typically called to check that a "file or rev"
278
 * argument is unambiguous. In this case, the caller will want
279
 * diagnose_misspelt_rev == 1 when verifying the first non-rev
280
 * argument (which could have been a revision), and
281
 * diagnose_misspelt_rev == 0 for the next ones (because we already
282
 * saw a filename, there's not ambiguity anymore).
283
 */
284
void verify_filename(const char *prefix,
285
         const char *arg,
286
         int diagnose_misspelt_rev)
287
0
{
288
0
  if (*arg == '-')
289
0
    die(_("option '%s' must come before non-option arguments"), arg);
290
0
  if (looks_like_pathspec(arg) || check_filename(prefix, arg))
291
0
    return;
292
0
  die_verify_filename(the_repository, prefix, arg, diagnose_misspelt_rev);
293
0
}
294
295
/*
296
 * Opposite of the above: the command line did not have -- marker
297
 * and we parsed the arg as a refname.  It should not be interpretable
298
 * as a filename.
299
 */
300
void verify_non_filename(const char *prefix, const char *arg)
301
0
{
302
0
  if (!is_inside_work_tree() || is_inside_git_dir())
303
0
    return;
304
0
  if (*arg == '-')
305
0
    return; /* flag */
306
0
  if (!check_filename(prefix, arg))
307
0
    return;
308
0
  die(_("ambiguous argument '%s': both revision and filename\n"
309
0
        "Use '--' to separate paths from revisions, like this:\n"
310
0
        "'git <command> [<revision>...] -- [<file>...]'"), arg);
311
0
}
312
313
int get_common_dir(struct strbuf *sb, const char *gitdir)
314
0
{
315
0
  const char *git_env_common_dir = getenv(GIT_COMMON_DIR_ENVIRONMENT);
316
0
  if (git_env_common_dir) {
317
0
    strbuf_addstr(sb, git_env_common_dir);
318
0
    return 1;
319
0
  } else {
320
0
    return get_common_dir_noenv(sb, gitdir);
321
0
  }
322
0
}
323
324
int get_common_dir_noenv(struct strbuf *sb, const char *gitdir)
325
0
{
326
0
  struct strbuf data = STRBUF_INIT;
327
0
  struct strbuf path = STRBUF_INIT;
328
0
  int ret = 0;
329
330
0
  strbuf_addf(&path, "%s/commondir", gitdir);
331
0
  if (file_exists(path.buf)) {
332
0
    if (strbuf_read_file(&data, path.buf, 0) <= 0)
333
0
      die_errno(_("failed to read %s"), path.buf);
334
0
    while (data.len && (data.buf[data.len - 1] == '\n' ||
335
0
            data.buf[data.len - 1] == '\r'))
336
0
      data.len--;
337
0
    data.buf[data.len] = '\0';
338
0
    strbuf_reset(&path);
339
0
    if (!is_absolute_path(data.buf))
340
0
      strbuf_addf(&path, "%s/", gitdir);
341
0
    strbuf_addbuf(&path, &data);
342
0
    strbuf_add_real_path(sb, path.buf);
343
0
    ret = 1;
344
0
  } else {
345
0
    strbuf_addstr(sb, gitdir);
346
0
  }
347
348
0
  strbuf_release(&data);
349
0
  strbuf_release(&path);
350
0
  return ret;
351
0
}
352
353
static int validate_headref(const char *path)
354
0
{
355
0
  struct stat st;
356
0
  char buffer[256];
357
0
  const char *refname;
358
0
  struct object_id oid;
359
0
  int fd;
360
0
  ssize_t len;
361
362
0
  if (lstat(path, &st) < 0)
363
0
    return -1;
364
365
  /* Make sure it is a "refs/.." symlink */
366
0
  if (S_ISLNK(st.st_mode)) {
367
0
    len = readlink(path, buffer, sizeof(buffer)-1);
368
0
    if (len >= 5 && !memcmp("refs/", buffer, 5))
369
0
      return 0;
370
0
    return -1;
371
0
  }
372
373
  /*
374
   * Anything else, just open it and try to see if it is a symbolic ref.
375
   */
376
0
  fd = open(path, O_RDONLY);
377
0
  if (fd < 0)
378
0
    return -1;
379
0
  len = read_in_full(fd, buffer, sizeof(buffer)-1);
380
0
  close(fd);
381
382
0
  if (len < 0)
383
0
    return -1;
384
0
  buffer[len] = '\0';
385
386
  /*
387
   * Is it a symbolic ref?
388
   */
389
0
  if (skip_prefix(buffer, "ref:", &refname)) {
390
0
    while (isspace(*refname))
391
0
      refname++;
392
0
    if (starts_with(refname, "refs/"))
393
0
      return 0;
394
0
  }
395
396
  /*
397
   * Is this a detached HEAD?
398
   */
399
0
  if (get_oid_hex_any(buffer, &oid) != GIT_HASH_UNKNOWN)
400
0
    return 0;
401
402
0
  return -1;
403
0
}
404
405
/*
406
 * Test if it looks like we're at a git directory.
407
 * We want to see:
408
 *
409
 *  - either an objects/ directory _or_ the proper
410
 *    GIT_OBJECT_DIRECTORY environment variable
411
 *  - a refs/ directory
412
 *  - either a HEAD symlink or a HEAD file that is formatted as
413
 *    a proper "ref:", or a regular file HEAD that has a properly
414
 *    formatted sha1 object name.
415
 */
416
int is_git_directory(const char *suspect)
417
0
{
418
0
  struct strbuf path = STRBUF_INIT;
419
0
  int ret = 0;
420
0
  size_t len;
421
422
  /* Check worktree-related signatures */
423
0
  strbuf_addstr(&path, suspect);
424
0
  strbuf_complete(&path, '/');
425
0
  strbuf_addstr(&path, "HEAD");
426
0
  if (validate_headref(path.buf))
427
0
    goto done;
428
429
0
  strbuf_reset(&path);
430
0
  get_common_dir(&path, suspect);
431
0
  len = path.len;
432
433
  /* Check non-worktree-related signatures */
434
0
  if (getenv(DB_ENVIRONMENT)) {
435
0
    if (access(getenv(DB_ENVIRONMENT), X_OK))
436
0
      goto done;
437
0
  }
438
0
  else {
439
0
    strbuf_setlen(&path, len);
440
0
    strbuf_addstr(&path, "/objects");
441
0
    if (access(path.buf, X_OK))
442
0
      goto done;
443
0
  }
444
445
0
  strbuf_setlen(&path, len);
446
0
  strbuf_addstr(&path, "/refs");
447
0
  if (access(path.buf, X_OK))
448
0
    goto done;
449
450
0
  ret = 1;
451
0
done:
452
0
  strbuf_release(&path);
453
0
  return ret;
454
0
}
455
456
int is_nonbare_repository_dir(struct strbuf *path)
457
0
{
458
0
  int ret = 0;
459
0
  int gitfile_error;
460
0
  size_t orig_path_len = path->len;
461
0
  assert(orig_path_len != 0);
462
0
  strbuf_complete(path, '/');
463
0
  strbuf_addstr(path, ".git");
464
0
  if (read_gitfile_gently(path->buf, &gitfile_error) || is_git_directory(path->buf))
465
0
    ret = 1;
466
0
  if (gitfile_error == READ_GITFILE_ERR_OPEN_FAILED ||
467
0
      gitfile_error == READ_GITFILE_ERR_READ_FAILED)
468
0
    ret = 1;
469
0
  strbuf_setlen(path, orig_path_len);
470
0
  return ret;
471
0
}
472
473
int is_inside_git_dir(void)
474
0
{
475
0
  if (inside_git_dir < 0)
476
0
    inside_git_dir = is_inside_dir(repo_get_git_dir(the_repository));
477
0
  return inside_git_dir;
478
0
}
479
480
int is_inside_work_tree(void)
481
0
{
482
0
  if (inside_work_tree < 0)
483
0
    inside_work_tree = is_inside_dir(repo_get_work_tree(the_repository));
484
0
  return inside_work_tree;
485
0
}
486
487
void setup_work_tree(void)
488
0
{
489
0
  const char *work_tree;
490
0
  static int initialized = 0;
491
492
0
  if (initialized)
493
0
    return;
494
495
0
  if (work_tree_config_is_bogus)
496
0
    die(_("unable to set up work tree using invalid config"));
497
498
0
  work_tree = repo_get_work_tree(the_repository);
499
0
  if (!work_tree || chdir_notify(work_tree))
500
0
    die(_("this operation must be run in a work tree"));
501
502
  /*
503
   * Make sure subsequent git processes find correct worktree
504
   * if $GIT_WORK_TREE is set relative
505
   */
506
0
  if (getenv(GIT_WORK_TREE_ENVIRONMENT))
507
0
    setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
508
509
0
  initialized = 1;
510
0
}
511
512
static void setup_original_cwd(void)
513
0
{
514
0
  struct strbuf tmp = STRBUF_INIT;
515
0
  const char *worktree = NULL;
516
0
  int offset = -1;
517
518
0
  if (!tmp_original_cwd)
519
0
    return;
520
521
  /*
522
   * startup_info->original_cwd points to the current working
523
   * directory we inherited from our parent process, which is a
524
   * directory we want to avoid removing.
525
   *
526
   * For convenience, we would like to have the path relative to the
527
   * worktree instead of an absolute path.
528
   *
529
   * Yes, startup_info->original_cwd is usually the same as 'prefix',
530
   * but differs in two ways:
531
   *   - prefix has a trailing '/'
532
   *   - if the user passes '-C' to git, that modifies the prefix but
533
   *     not startup_info->original_cwd.
534
   */
535
536
  /* Normalize the directory */
537
0
  if (!strbuf_realpath(&tmp, tmp_original_cwd, 0)) {
538
0
    trace2_data_string("setup", the_repository,
539
0
           "realpath-path", tmp_original_cwd);
540
0
    trace2_data_string("setup", the_repository,
541
0
           "realpath-failure", strerror(errno));
542
0
    free((char*)tmp_original_cwd);
543
0
    tmp_original_cwd = NULL;
544
0
    return;
545
0
  }
546
547
0
  free((char*)tmp_original_cwd);
548
0
  tmp_original_cwd = NULL;
549
0
  startup_info->original_cwd = strbuf_detach(&tmp, NULL);
550
551
  /*
552
   * Get our worktree; we only protect the current working directory
553
   * if it's in the worktree.
554
   */
555
0
  worktree = repo_get_work_tree(the_repository);
556
0
  if (!worktree)
557
0
    goto no_prevention_needed;
558
559
0
  offset = dir_inside_of(startup_info->original_cwd, worktree);
560
0
  if (offset >= 0) {
561
    /*
562
     * If startup_info->original_cwd == worktree, that is already
563
     * protected and we don't need original_cwd as a secondary
564
     * protection measure.
565
     */
566
0
    if (!*(startup_info->original_cwd + offset))
567
0
      goto no_prevention_needed;
568
569
    /*
570
     * original_cwd was inside worktree; precompose it just as
571
     * we do prefix so that built up paths will match
572
     */
573
0
    startup_info->original_cwd = \
574
0
      precompose_string_if_needed(startup_info->original_cwd
575
0
                + offset);
576
0
    return;
577
0
  }
578
579
0
no_prevention_needed:
580
0
  free((char*)startup_info->original_cwd);
581
0
  startup_info->original_cwd = NULL;
582
0
}
583
584
static int read_worktree_config(const char *var, const char *value,
585
        const struct config_context *ctx UNUSED,
586
        void *vdata)
587
0
{
588
0
  struct repository_format *data = vdata;
589
590
0
  if (strcmp(var, "core.bare") == 0) {
591
0
    data->is_bare = git_config_bool(var, value);
592
0
  } else if (strcmp(var, "core.worktree") == 0) {
593
0
    if (!value)
594
0
      return config_error_nonbool(var);
595
0
    free(data->work_tree);
596
0
    data->work_tree = xstrdup(value);
597
0
  }
598
0
  return 0;
599
0
}
600
601
enum extension_result {
602
  EXTENSION_ERROR = -1, /* compatible with error(), etc */
603
  EXTENSION_UNKNOWN = 0,
604
  EXTENSION_OK = 1
605
};
606
607
/*
608
 * Do not add new extensions to this function. It handles extensions which are
609
 * respected even in v0-format repositories for historical compatibility.
610
 */
611
static enum extension_result handle_extension_v0(const char *var,
612
             const char *value,
613
             const char *ext,
614
             struct repository_format *data)
615
0
{
616
0
    if (!strcmp(ext, "noop")) {
617
0
      return EXTENSION_OK;
618
0
    } else if (!strcmp(ext, "preciousobjects")) {
619
0
      data->precious_objects = git_config_bool(var, value);
620
0
      return EXTENSION_OK;
621
0
    } else if (!strcmp(ext, "partialclone")) {
622
0
      if (!value)
623
0
        return config_error_nonbool(var);
624
0
      data->partial_clone = xstrdup(value);
625
0
      return EXTENSION_OK;
626
0
    } else if (!strcmp(ext, "worktreeconfig")) {
627
0
      data->worktree_config = git_config_bool(var, value);
628
0
      return EXTENSION_OK;
629
0
    }
630
631
0
    return EXTENSION_UNKNOWN;
632
0
}
633
634
static void parse_reference_uri(const char *value, char **format,
635
        char **payload)
636
0
{
637
0
  const char *schema_end;
638
639
0
  schema_end = strstr(value, "://");
640
0
  if (!schema_end) {
641
0
    *format = xstrdup(value);
642
0
    *payload = NULL;
643
0
  } else {
644
0
    *format = xstrndup(value, schema_end - value);
645
0
    *payload = xstrdup_or_null(schema_end + 3);
646
0
  }
647
0
}
648
649
/*
650
 * Record any new extensions in this function.
651
 */
652
static enum extension_result handle_extension(const char *var,
653
                const char *value,
654
                const char *ext,
655
                struct repository_format *data)
656
0
{
657
0
  if (!strcmp(ext, "noop-v1")) {
658
0
    return EXTENSION_OK;
659
0
  } else if (!strcmp(ext, "objectformat")) {
660
0
    int format;
661
662
0
    if (!value)
663
0
      return config_error_nonbool(var);
664
0
    format = hash_algo_by_name(value);
665
0
    if (format == GIT_HASH_UNKNOWN)
666
0
      return error(_("invalid value for '%s': '%s'"),
667
0
             "extensions.objectformat", value);
668
0
    data->hash_algo = format;
669
0
    return EXTENSION_OK;
670
0
  } else if (!strcmp(ext, "compatobjectformat")) {
671
0
    struct string_list_item *item;
672
0
    int format;
673
674
0
    if (!value)
675
0
      return config_error_nonbool(var);
676
0
    format = hash_algo_by_name(value);
677
0
    if (format == GIT_HASH_UNKNOWN)
678
0
      return error(_("invalid value for '%s': '%s'"),
679
0
             "extensions.compatobjectformat", value);
680
    /* For now only support compatObjectFormat being specified once. */
681
0
    for_each_string_list_item(item, &data->v1_only_extensions) {
682
0
      if (!strcmp(item->string, "compatobjectformat"))
683
0
        return error(_("'%s' already specified as '%s'"),
684
0
          "extensions.compatobjectformat",
685
0
          hash_algos[data->compat_hash_algo].name);
686
0
    }
687
0
    data->compat_hash_algo = format;
688
0
    return EXTENSION_OK;
689
0
  } else if (!strcmp(ext, "refstorage")) {
690
0
    unsigned int format;
691
0
    char *format_str;
692
693
0
    if (!value)
694
0
      return config_error_nonbool(var);
695
696
0
    parse_reference_uri(value, &format_str,
697
0
            &data->ref_storage_payload);
698
699
0
    format = ref_storage_format_by_name(format_str);
700
0
    free(format_str);
701
702
0
    if (format == REF_STORAGE_FORMAT_UNKNOWN)
703
0
      return error(_("invalid value for '%s': '%s'"),
704
0
             "extensions.refstorage", value);
705
0
    data->ref_storage_format = format;
706
0
    return EXTENSION_OK;
707
0
  } else if (!strcmp(ext, "relativeworktrees")) {
708
0
    data->relative_worktrees = git_config_bool(var, value);
709
0
    return EXTENSION_OK;
710
0
  } else if (!strcmp(ext, "submodulepathconfig")) {
711
0
    data->submodule_path_cfg = git_config_bool(var, value);
712
0
    return EXTENSION_OK;
713
0
  }
714
0
  return EXTENSION_UNKNOWN;
715
0
}
716
717
static int check_repo_format(const char *var, const char *value,
718
           const struct config_context *ctx, void *vdata)
719
0
{
720
0
  struct repository_format *data = vdata;
721
0
  const char *ext;
722
723
0
  if (strcmp(var, "core.repositoryformatversion") == 0)
724
0
    data->version = git_config_int(var, value, ctx->kvi);
725
0
  else if (skip_prefix(var, "extensions.", &ext)) {
726
0
    switch (handle_extension_v0(var, value, ext, data)) {
727
0
    case EXTENSION_ERROR:
728
0
      return -1;
729
0
    case EXTENSION_OK:
730
0
      return 0;
731
0
    case EXTENSION_UNKNOWN:
732
0
      break;
733
0
    }
734
735
0
    switch (handle_extension(var, value, ext, data)) {
736
0
    case EXTENSION_ERROR:
737
0
      return -1;
738
0
    case EXTENSION_OK:
739
0
      string_list_append(&data->v1_only_extensions, ext);
740
0
      return 0;
741
0
    case EXTENSION_UNKNOWN:
742
0
      string_list_append(&data->unknown_extensions, ext);
743
0
      return 0;
744
0
    }
745
0
  }
746
747
0
  return read_worktree_config(var, value, ctx, vdata);
748
0
}
749
750
static int check_repository_format_gently(const char *gitdir, struct repository_format *candidate, int *nongit_ok)
751
0
{
752
0
  struct strbuf sb = STRBUF_INIT;
753
0
  struct strbuf err = STRBUF_INIT;
754
0
  int has_common;
755
756
0
  has_common = get_common_dir(&sb, gitdir);
757
0
  strbuf_addstr(&sb, "/config");
758
0
  read_repository_format(candidate, sb.buf);
759
0
  strbuf_release(&sb);
760
761
  /*
762
   * For historical use of check_repository_format() in git-init,
763
   * we treat a missing config as a silent "ok", even when nongit_ok
764
   * is unset.
765
   */
766
0
  if (candidate->version < 0)
767
0
    return 0;
768
769
0
  if (verify_repository_format(candidate, &err) < 0) {
770
0
    if (nongit_ok) {
771
0
      warning("%s", err.buf);
772
0
      strbuf_release(&err);
773
0
      *nongit_ok = -1;
774
0
      return -1;
775
0
    }
776
0
    die("%s", err.buf);
777
0
  }
778
779
0
  the_repository->repository_format_precious_objects = candidate->precious_objects;
780
781
0
  string_list_clear(&candidate->unknown_extensions, 0);
782
0
  string_list_clear(&candidate->v1_only_extensions, 0);
783
784
0
  if (candidate->worktree_config) {
785
    /*
786
     * pick up core.bare and core.worktree from per-worktree
787
     * config if present
788
     */
789
0
    strbuf_addf(&sb, "%s/config.worktree", gitdir);
790
0
    git_config_from_file(read_worktree_config, sb.buf, candidate);
791
0
    strbuf_release(&sb);
792
0
    has_common = 0;
793
0
  }
794
795
0
  if (!has_common) {
796
0
    if (candidate->is_bare != -1) {
797
0
      is_bare_repository_cfg = candidate->is_bare;
798
0
      if (is_bare_repository_cfg == 1)
799
0
        inside_work_tree = -1;
800
0
    }
801
0
    if (candidate->work_tree) {
802
0
      free(git_work_tree_cfg);
803
0
      git_work_tree_cfg = xstrdup(candidate->work_tree);
804
0
      inside_work_tree = -1;
805
0
    }
806
0
  }
807
808
0
  return 0;
809
0
}
810
811
int upgrade_repository_format(int target_version)
812
0
{
813
0
  struct strbuf sb = STRBUF_INIT;
814
0
  struct strbuf err = STRBUF_INIT;
815
0
  struct strbuf repo_version = STRBUF_INIT;
816
0
  struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
817
0
  int ret;
818
819
0
  repo_common_path_append(the_repository, &sb, "config");
820
0
  read_repository_format(&repo_fmt, sb.buf);
821
0
  strbuf_release(&sb);
822
823
0
  if (repo_fmt.version >= target_version) {
824
0
    ret = 0;
825
0
    goto out;
826
0
  }
827
828
0
  if (verify_repository_format(&repo_fmt, &err) < 0) {
829
0
    ret = error("cannot upgrade repository format from %d to %d: %s",
830
0
          repo_fmt.version, target_version, err.buf);
831
0
    goto out;
832
0
  }
833
0
  if (!repo_fmt.version && repo_fmt.unknown_extensions.nr) {
834
0
    ret = error("cannot upgrade repository format: "
835
0
          "unknown extension %s",
836
0
          repo_fmt.unknown_extensions.items[0].string);
837
0
    goto out;
838
0
  }
839
840
0
  strbuf_addf(&repo_version, "%d", target_version);
841
0
  repo_config_set(the_repository, "core.repositoryformatversion", repo_version.buf);
842
843
0
  ret = 1;
844
845
0
out:
846
0
  clear_repository_format(&repo_fmt);
847
0
  strbuf_release(&repo_version);
848
0
  strbuf_release(&err);
849
0
  return ret;
850
0
}
851
852
static void init_repository_format(struct repository_format *format)
853
0
{
854
0
  const struct repository_format fresh = REPOSITORY_FORMAT_INIT;
855
856
0
  memcpy(format, &fresh, sizeof(fresh));
857
0
}
858
859
int read_repository_format(struct repository_format *format, const char *path)
860
0
{
861
0
  clear_repository_format(format);
862
0
  format->hash_algo = GIT_HASH_SHA1_LEGACY;
863
0
  git_config_from_file(check_repo_format, path, format);
864
0
  if (format->version == -1) {
865
0
    clear_repository_format(format);
866
0
    format->hash_algo = GIT_HASH_SHA1_LEGACY;
867
0
  }
868
0
  return format->version;
869
0
}
870
871
void clear_repository_format(struct repository_format *format)
872
0
{
873
0
  string_list_clear(&format->unknown_extensions, 0);
874
0
  string_list_clear(&format->v1_only_extensions, 0);
875
0
  free(format->work_tree);
876
0
  free(format->partial_clone);
877
0
  free(format->ref_storage_payload);
878
0
  init_repository_format(format);
879
0
}
880
881
int verify_repository_format(const struct repository_format *format,
882
           struct strbuf *err)
883
0
{
884
0
  if (GIT_REPO_VERSION_READ < format->version) {
885
0
    strbuf_addf(err, _("Expected git repo version <= %d, found %d"),
886
0
          GIT_REPO_VERSION_READ, format->version);
887
0
    return -1;
888
0
  }
889
890
0
  if (format->version >= 1 && format->unknown_extensions.nr) {
891
0
    int i;
892
893
0
    strbuf_addstr(err, Q_("unknown repository extension found:",
894
0
              "unknown repository extensions found:",
895
0
              format->unknown_extensions.nr));
896
897
0
    for (i = 0; i < format->unknown_extensions.nr; i++)
898
0
      strbuf_addf(err, "\n\t%s",
899
0
            format->unknown_extensions.items[i].string);
900
0
    return -1;
901
0
  }
902
903
0
  if (format->version == 0 && format->v1_only_extensions.nr) {
904
0
    int i;
905
906
0
    strbuf_addstr(err,
907
0
            Q_("repo version is 0, but v1-only extension found:",
908
0
         "repo version is 0, but v1-only extensions found:",
909
0
         format->v1_only_extensions.nr));
910
911
0
    for (i = 0; i < format->v1_only_extensions.nr; i++)
912
0
      strbuf_addf(err, "\n\t%s",
913
0
            format->v1_only_extensions.items[i].string);
914
0
    return -1;
915
0
  }
916
917
0
  return 0;
918
0
}
919
920
void read_gitfile_error_die(int error_code, const char *path, const char *dir)
921
0
{
922
0
  switch (error_code) {
923
0
  case READ_GITFILE_ERR_NOT_A_FILE:
924
0
  case READ_GITFILE_ERR_STAT_FAILED:
925
0
  case READ_GITFILE_ERR_MISSING:
926
0
  case READ_GITFILE_ERR_IS_A_DIR:
927
    /* non-fatal; follow return path */
928
0
    break;
929
0
  case READ_GITFILE_ERR_OPEN_FAILED:
930
0
    die_errno(_("error opening '%s'"), path);
931
0
  case READ_GITFILE_ERR_TOO_LARGE:
932
0
    die(_("too large to be a .git file: '%s'"), path);
933
0
  case READ_GITFILE_ERR_READ_FAILED:
934
0
    die(_("error reading %s"), path);
935
0
  case READ_GITFILE_ERR_INVALID_FORMAT:
936
0
    die(_("invalid gitfile format: %s"), path);
937
0
  case READ_GITFILE_ERR_NO_PATH:
938
0
    die(_("no path in gitfile: %s"), path);
939
0
  case READ_GITFILE_ERR_NOT_A_REPO:
940
0
    die(_("not a git repository: %s"), dir);
941
0
  default:
942
0
    BUG("unknown error code");
943
0
  }
944
0
}
945
946
/*
947
 * Try to read the location of the git directory from the .git file,
948
 * return path to git directory if found. The return value comes from
949
 * a shared buffer.
950
 *
951
 * On failure, if return_error_code is not NULL, return_error_code
952
 * will be set to an error code and NULL will be returned. If
953
 * return_error_code is NULL the function will die instead (for most
954
 * cases).
955
 */
956
const char *read_gitfile_gently(const char *path, int *return_error_code)
957
0
{
958
0
  const int max_file_size = 1 << 20;  /* 1MB */
959
0
  int error_code = 0;
960
0
  char *buf = NULL;
961
0
  char *dir = NULL;
962
0
  const char *slash;
963
0
  struct stat st;
964
0
  int fd;
965
0
  ssize_t len;
966
0
  static struct strbuf realpath = STRBUF_INIT;
967
968
0
  if (stat(path, &st)) {
969
0
    if (errno == ENOENT || errno == ENOTDIR)
970
0
      error_code = READ_GITFILE_ERR_MISSING;
971
0
    else
972
0
      error_code = READ_GITFILE_ERR_STAT_FAILED;
973
0
    goto cleanup_return;
974
0
  }
975
0
  if (S_ISDIR(st.st_mode)) {
976
0
    error_code = READ_GITFILE_ERR_IS_A_DIR;
977
0
    goto cleanup_return;
978
0
  }
979
0
  if (!S_ISREG(st.st_mode)) {
980
0
    error_code = READ_GITFILE_ERR_NOT_A_FILE;
981
0
    goto cleanup_return;
982
0
  }
983
0
  if (st.st_size > max_file_size) {
984
0
    error_code = READ_GITFILE_ERR_TOO_LARGE;
985
0
    goto cleanup_return;
986
0
  }
987
0
  fd = open(path, O_RDONLY);
988
0
  if (fd < 0) {
989
0
    error_code = READ_GITFILE_ERR_OPEN_FAILED;
990
0
    goto cleanup_return;
991
0
  }
992
0
  buf = xmallocz(st.st_size);
993
0
  len = read_in_full(fd, buf, st.st_size);
994
0
  close(fd);
995
0
  if (len != st.st_size) {
996
0
    error_code = READ_GITFILE_ERR_READ_FAILED;
997
0
    goto cleanup_return;
998
0
  }
999
0
  if (!starts_with(buf, "gitdir: ")) {
1000
0
    error_code = READ_GITFILE_ERR_INVALID_FORMAT;
1001
0
    goto cleanup_return;
1002
0
  }
1003
0
  while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
1004
0
    len--;
1005
0
  if (len < 9) {
1006
0
    error_code = READ_GITFILE_ERR_NO_PATH;
1007
0
    goto cleanup_return;
1008
0
  }
1009
0
  buf[len] = '\0';
1010
0
  dir = buf + 8;
1011
1012
0
  if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) {
1013
0
    size_t pathlen = slash+1 - path;
1014
0
    dir = xstrfmt("%.*s%.*s", (int)pathlen, path,
1015
0
            (int)(len - 8), buf + 8);
1016
0
    free(buf);
1017
0
    buf = dir;
1018
0
  }
1019
0
  if (!is_git_directory(dir)) {
1020
0
    error_code = READ_GITFILE_ERR_NOT_A_REPO;
1021
0
    goto cleanup_return;
1022
0
  }
1023
1024
0
  strbuf_realpath(&realpath, dir, 1);
1025
0
  path = realpath.buf;
1026
1027
0
cleanup_return:
1028
0
  if (return_error_code)
1029
0
    *return_error_code = error_code;
1030
0
  else if (error_code)
1031
0
    read_gitfile_error_die(error_code, path, dir);
1032
1033
0
  free(buf);
1034
0
  return error_code ? NULL : path;
1035
0
}
1036
1037
static void setup_git_env_internal(const char *git_dir,
1038
           bool skip_initializing_odb)
1039
0
{
1040
0
  char *git_replace_ref_base;
1041
0
  const char *shallow_file;
1042
0
  const char *replace_ref_base;
1043
0
  struct set_gitdir_args args = { NULL };
1044
0
  struct strvec to_free = STRVEC_INIT;
1045
1046
0
  args.commondir = getenv_safe(&to_free, GIT_COMMON_DIR_ENVIRONMENT);
1047
0
  args.object_dir = getenv_safe(&to_free, DB_ENVIRONMENT);
1048
0
  args.graft_file = getenv_safe(&to_free, GRAFT_ENVIRONMENT);
1049
0
  args.index_file = getenv_safe(&to_free, INDEX_ENVIRONMENT);
1050
0
  args.alternate_db = getenv_safe(&to_free, ALTERNATE_DB_ENVIRONMENT);
1051
0
  if (getenv(GIT_QUARANTINE_ENVIRONMENT))
1052
0
    args.disable_ref_updates = true;
1053
0
  args.skip_initializing_odb = skip_initializing_odb;
1054
1055
0
  repo_set_gitdir(the_repository, git_dir, &args);
1056
0
  strvec_clear(&to_free);
1057
1058
0
  if (getenv(NO_REPLACE_OBJECTS_ENVIRONMENT))
1059
0
    disable_replace_refs();
1060
0
  replace_ref_base = getenv(GIT_REPLACE_REF_BASE_ENVIRONMENT);
1061
0
  git_replace_ref_base = xstrdup(replace_ref_base ? replace_ref_base
1062
0
                : "refs/replace/");
1063
0
  update_ref_namespace(NAMESPACE_REPLACE, git_replace_ref_base);
1064
1065
0
  shallow_file = getenv(GIT_SHALLOW_FILE_ENVIRONMENT);
1066
0
  if (shallow_file)
1067
0
    set_alternate_shallow_file(the_repository, shallow_file, 0);
1068
1069
0
  if (git_env_bool(NO_LAZY_FETCH_ENVIRONMENT, 0))
1070
0
    fetch_if_missing = 0;
1071
0
}
1072
1073
void setup_git_env(const char *git_dir)
1074
0
{
1075
0
  setup_git_env_internal(git_dir, false);
1076
0
}
1077
1078
static void set_git_dir_1(const char *path, bool skip_initializing_odb)
1079
0
{
1080
0
  xsetenv(GIT_DIR_ENVIRONMENT, path, 1);
1081
0
  setup_git_env_internal(path, skip_initializing_odb);
1082
0
}
1083
1084
static void update_relative_gitdir(const char *name UNUSED,
1085
           const char *old_cwd,
1086
           const char *new_cwd,
1087
           void *data UNUSED)
1088
0
{
1089
0
  char *path = reparent_relative_path(old_cwd, new_cwd,
1090
0
              repo_get_git_dir(the_repository));
1091
0
  trace_printf_key(&trace_setup_key,
1092
0
       "setup: move $GIT_DIR to '%s'",
1093
0
       path);
1094
0
  set_git_dir_1(path, true);
1095
0
  free(path);
1096
0
}
1097
1098
static void set_git_dir(const char *path, int make_realpath)
1099
0
{
1100
0
  struct strbuf realpath = STRBUF_INIT;
1101
1102
0
  if (make_realpath) {
1103
0
    strbuf_realpath(&realpath, path, 1);
1104
0
    path = realpath.buf;
1105
0
  }
1106
1107
0
  set_git_dir_1(path, false);
1108
0
  if (!is_absolute_path(path))
1109
0
    chdir_notify_register(NULL, update_relative_gitdir, NULL);
1110
1111
0
  strbuf_release(&realpath);
1112
0
}
1113
1114
static const char *setup_explicit_git_dir(const char *gitdirenv,
1115
            struct strbuf *cwd,
1116
            struct repository_format *repo_fmt,
1117
            int *nongit_ok)
1118
0
{
1119
0
  const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
1120
0
  const char *worktree;
1121
0
  char *gitfile;
1122
0
  int offset;
1123
1124
0
  if (PATH_MAX - 40 < strlen(gitdirenv))
1125
0
    die(_("'$%s' too big"), GIT_DIR_ENVIRONMENT);
1126
1127
0
  gitfile = (char*)read_gitfile(gitdirenv);
1128
0
  if (gitfile) {
1129
0
    gitfile = xstrdup(gitfile);
1130
0
    gitdirenv = gitfile;
1131
0
  }
1132
1133
0
  if (!is_git_directory(gitdirenv)) {
1134
0
    if (nongit_ok) {
1135
0
      *nongit_ok = 1;
1136
0
      free(gitfile);
1137
0
      return NULL;
1138
0
    }
1139
0
    die(_("not a git repository: '%s'"), gitdirenv);
1140
0
  }
1141
1142
0
  if (check_repository_format_gently(gitdirenv, repo_fmt, nongit_ok)) {
1143
0
    free(gitfile);
1144
0
    return NULL;
1145
0
  }
1146
1147
  /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
1148
0
  if (work_tree_env)
1149
0
    set_git_work_tree(work_tree_env);
1150
0
  else if (is_bare_repository_cfg > 0) {
1151
0
    if (git_work_tree_cfg) {
1152
      /* #22.2, #30 */
1153
0
      warning("core.bare and core.worktree do not make sense");
1154
0
      work_tree_config_is_bogus = 1;
1155
0
    }
1156
1157
    /* #18, #26 */
1158
0
    set_git_dir(gitdirenv, 0);
1159
0
    free(gitfile);
1160
0
    return NULL;
1161
0
  }
1162
0
  else if (git_work_tree_cfg) { /* #6, #14 */
1163
0
    if (is_absolute_path(git_work_tree_cfg))
1164
0
      set_git_work_tree(git_work_tree_cfg);
1165
0
    else {
1166
0
      char *core_worktree;
1167
0
      if (chdir(gitdirenv))
1168
0
        die_errno(_("cannot chdir to '%s'"), gitdirenv);
1169
0
      if (chdir(git_work_tree_cfg))
1170
0
        die_errno(_("cannot chdir to '%s'"), git_work_tree_cfg);
1171
0
      core_worktree = xgetcwd();
1172
0
      if (chdir(cwd->buf))
1173
0
        die_errno(_("cannot come back to cwd"));
1174
0
      set_git_work_tree(core_worktree);
1175
0
      free(core_worktree);
1176
0
    }
1177
0
  }
1178
0
  else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, 1)) {
1179
    /* #16d */
1180
0
    set_git_dir(gitdirenv, 0);
1181
0
    free(gitfile);
1182
0
    return NULL;
1183
0
  }
1184
0
  else /* #2, #10 */
1185
0
    set_git_work_tree(".");
1186
1187
  /* set_git_work_tree() must have been called by now */
1188
0
  worktree = repo_get_work_tree(the_repository);
1189
1190
  /* both repo_get_work_tree() and cwd are already normalized */
1191
0
  if (!strcmp(cwd->buf, worktree)) { /* cwd == worktree */
1192
0
    set_git_dir(gitdirenv, 0);
1193
0
    free(gitfile);
1194
0
    return NULL;
1195
0
  }
1196
1197
0
  offset = dir_inside_of(cwd->buf, worktree);
1198
0
  if (offset >= 0) { /* cwd inside worktree? */
1199
0
    set_git_dir(gitdirenv, 1);
1200
0
    if (chdir(worktree))
1201
0
      die_errno(_("cannot chdir to '%s'"), worktree);
1202
0
    strbuf_addch(cwd, '/');
1203
0
    free(gitfile);
1204
0
    return cwd->buf + offset;
1205
0
  }
1206
1207
  /* cwd outside worktree */
1208
0
  set_git_dir(gitdirenv, 0);
1209
0
  free(gitfile);
1210
0
  return NULL;
1211
0
}
1212
1213
static const char *setup_discovered_git_dir(const char *gitdir,
1214
              struct strbuf *cwd, int offset,
1215
              struct repository_format *repo_fmt,
1216
              int *nongit_ok)
1217
0
{
1218
0
  if (check_repository_format_gently(gitdir, repo_fmt, nongit_ok))
1219
0
    return NULL;
1220
1221
  /* --work-tree is set without --git-dir; use discovered one */
1222
0
  if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1223
0
    char *to_free = NULL;
1224
0
    const char *ret;
1225
1226
0
    if (offset != cwd->len && !is_absolute_path(gitdir))
1227
0
      gitdir = to_free = real_pathdup(gitdir, 1);
1228
0
    if (chdir(cwd->buf))
1229
0
      die_errno(_("cannot come back to cwd"));
1230
0
    ret = setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1231
0
    free(to_free);
1232
0
    return ret;
1233
0
  }
1234
1235
  /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
1236
0
  if (is_bare_repository_cfg > 0) {
1237
0
    set_git_dir(gitdir, (offset != cwd->len));
1238
0
    if (chdir(cwd->buf))
1239
0
      die_errno(_("cannot come back to cwd"));
1240
0
    return NULL;
1241
0
  }
1242
1243
  /* #0, #1, #5, #8, #9, #12, #13 */
1244
0
  set_git_work_tree(".");
1245
0
  if (strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT))
1246
0
    set_git_dir(gitdir, 0);
1247
0
  inside_git_dir = 0;
1248
0
  inside_work_tree = 1;
1249
0
  if (offset >= cwd->len)
1250
0
    return NULL;
1251
1252
  /* Make "offset" point past the '/' (already the case for root dirs) */
1253
0
  if (offset != offset_1st_component(cwd->buf))
1254
0
    offset++;
1255
  /* Add a '/' at the end */
1256
0
  strbuf_addch(cwd, '/');
1257
0
  return cwd->buf + offset;
1258
0
}
1259
1260
/* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
1261
static const char *setup_bare_git_dir(struct strbuf *cwd, int offset,
1262
              struct repository_format *repo_fmt,
1263
              int *nongit_ok)
1264
0
{
1265
0
  int root_len;
1266
1267
0
  if (check_repository_format_gently(".", repo_fmt, nongit_ok))
1268
0
    return NULL;
1269
1270
0
  setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, "0", 1);
1271
1272
  /* --work-tree is set without --git-dir; use discovered one */
1273
0
  if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1274
0
    static const char *gitdir;
1275
1276
0
    gitdir = offset == cwd->len ? "." : xmemdupz(cwd->buf, offset);
1277
0
    if (chdir(cwd->buf))
1278
0
      die_errno(_("cannot come back to cwd"));
1279
0
    return setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1280
0
  }
1281
1282
0
  inside_git_dir = 1;
1283
0
  inside_work_tree = 0;
1284
0
  if (offset != cwd->len) {
1285
0
    if (chdir(cwd->buf))
1286
0
      die_errno(_("cannot come back to cwd"));
1287
0
    root_len = offset_1st_component(cwd->buf);
1288
0
    strbuf_setlen(cwd, offset > root_len ? offset : root_len);
1289
0
    set_git_dir(cwd->buf, 0);
1290
0
  }
1291
0
  else
1292
0
    set_git_dir(".", 0);
1293
0
  return NULL;
1294
0
}
1295
1296
static dev_t get_device_or_die(const char *path, const char *prefix, int prefix_len)
1297
0
{
1298
0
  struct stat buf;
1299
0
  if (stat(path, &buf)) {
1300
0
    die_errno(_("failed to stat '%*s%s%s'"),
1301
0
        prefix_len,
1302
0
        prefix ? prefix : "",
1303
0
        prefix ? "/" : "", path);
1304
0
  }
1305
0
  return buf.st_dev;
1306
0
}
1307
1308
/*
1309
 * A "string_list_each_func_t" function that canonicalizes an entry
1310
 * from GIT_CEILING_DIRECTORIES using real_pathdup(), or
1311
 * discards it if unusable.  The presence of an empty entry in
1312
 * GIT_CEILING_DIRECTORIES turns off canonicalization for all
1313
 * subsequent entries.
1314
 */
1315
static int canonicalize_ceiling_entry(struct string_list_item *item,
1316
              void *cb_data)
1317
0
{
1318
0
  int *empty_entry_found = cb_data;
1319
0
  char *ceil = item->string;
1320
1321
0
  if (!*ceil) {
1322
0
    *empty_entry_found = 1;
1323
0
    return 0;
1324
0
  } else if (!is_absolute_path(ceil)) {
1325
0
    return 0;
1326
0
  } else if (*empty_entry_found) {
1327
    /* Keep entry but do not canonicalize it */
1328
0
    return 1;
1329
0
  } else {
1330
0
    char *real_path = real_pathdup(ceil, 0);
1331
0
    if (!real_path) {
1332
0
      return 0;
1333
0
    }
1334
0
    free(item->string);
1335
0
    item->string = real_path;
1336
0
    return 1;
1337
0
  }
1338
0
}
1339
1340
struct safe_directory_data {
1341
  char *path;
1342
  int is_safe;
1343
};
1344
1345
static int safe_directory_cb(const char *key, const char *value,
1346
           const struct config_context *ctx UNUSED, void *d)
1347
0
{
1348
0
  struct safe_directory_data *data = d;
1349
1350
0
  if (strcmp(key, "safe.directory"))
1351
0
    return 0;
1352
1353
0
  if (!value || !*value) {
1354
0
    data->is_safe = 0;
1355
0
  } else if (!strcmp(value, "*")) {
1356
0
    data->is_safe = 1;
1357
0
  } else {
1358
0
    char *allowed = NULL;
1359
1360
0
    if (!git_config_pathname(&allowed, key, value) && allowed) {
1361
0
      char *normalized = NULL;
1362
1363
      /*
1364
       * Setting safe.directory to a non-absolute path
1365
       * makes little sense---it won't be relative to
1366
       * the configuration file the item is defined in.
1367
       * Except for ".", which means "if we are at the top
1368
       * level of a repository, then it is OK", which is
1369
       * slightly tighter than "*" that allows discovery.
1370
       */
1371
0
      if (!is_absolute_path(allowed) && strcmp(allowed, ".")) {
1372
0
        warning(_("safe.directory '%s' not absolute"),
1373
0
          allowed);
1374
0
        goto next;
1375
0
      }
1376
1377
      /*
1378
       * A .gitconfig in $HOME may be shared across
1379
       * different machines and safe.directory entries
1380
       * may or may not exist as paths on all of these
1381
       * machines.  In other words, it is not a warning
1382
       * worthy event when there is no such path on this
1383
       * machine---the entry may be useful elsewhere.
1384
       */
1385
0
      normalized = real_pathdup(allowed, 0);
1386
0
      if (!normalized)
1387
0
        goto next;
1388
1389
0
      if (ends_with(normalized, "/*")) {
1390
0
        size_t len = strlen(normalized);
1391
0
        if (!fspathncmp(normalized, data->path, len - 1))
1392
0
          data->is_safe = 1;
1393
0
      } else if (!fspathcmp(data->path, normalized)) {
1394
0
        data->is_safe = 1;
1395
0
      }
1396
0
    next:
1397
0
      free(normalized);
1398
0
      free(allowed);
1399
0
    }
1400
0
  }
1401
1402
0
  return 0;
1403
0
}
1404
1405
/*
1406
 * Check if a repository is safe, by verifying the ownership of the
1407
 * worktree (if any), the git directory, and the gitfile (if any).
1408
 *
1409
 * Exemptions for known-safe repositories can be added via `safe.directory`
1410
 * config settings; for non-bare repositories, their worktree needs to be
1411
 * added, for bare ones their git directory.
1412
 */
1413
static int ensure_valid_ownership(const char *gitfile,
1414
          const char *worktree, const char *gitdir,
1415
          struct strbuf *report)
1416
0
{
1417
0
  struct safe_directory_data data = { 0 };
1418
1419
0
  if (!git_env_bool("GIT_TEST_ASSUME_DIFFERENT_OWNER", 0) &&
1420
0
      (!gitfile || is_path_owned_by_current_user(gitfile, report)) &&
1421
0
      (!worktree || is_path_owned_by_current_user(worktree, report)) &&
1422
0
      (!gitdir || is_path_owned_by_current_user(gitdir, report)))
1423
0
    return 1;
1424
1425
  /*
1426
   * normalize the data.path for comparison with normalized paths
1427
   * that come from the configuration file.  The path is unsafe
1428
   * if it cannot be normalized.
1429
   */
1430
0
  data.path = real_pathdup(worktree ? worktree : gitdir, 0);
1431
0
  if (!data.path)
1432
0
    return 0;
1433
1434
  /*
1435
   * data.path is the "path" that identifies the repository and it is
1436
   * constant regardless of what failed above. data.is_safe should be
1437
   * initialized to false, and might be changed by the callback.
1438
   */
1439
0
  git_protected_config(safe_directory_cb, &data);
1440
1441
0
  free(data.path);
1442
0
  return data.is_safe;
1443
0
}
1444
1445
void die_upon_dubious_ownership(const char *gitfile, const char *worktree,
1446
        const char *gitdir)
1447
0
{
1448
0
  struct strbuf report = STRBUF_INIT, quoted = STRBUF_INIT;
1449
0
  const char *path;
1450
1451
0
  if (ensure_valid_ownership(gitfile, worktree, gitdir, &report))
1452
0
    return;
1453
1454
0
  strbuf_complete(&report, '\n');
1455
0
  path = gitfile ? gitfile : gitdir;
1456
0
  sq_quote_buf_pretty(&quoted, path);
1457
1458
0
  die(_("detected dubious ownership in repository at '%s'\n"
1459
0
        "%s"
1460
0
        "To add an exception for this directory, call:\n"
1461
0
        "\n"
1462
0
        "\tgit config --global --add safe.directory %s"),
1463
0
      path, report.buf, quoted.buf);
1464
0
}
1465
1466
static int allowed_bare_repo_cb(const char *key, const char *value,
1467
        const struct config_context *ctx UNUSED,
1468
        void *d)
1469
0
{
1470
0
  enum allowed_bare_repo *allowed_bare_repo = d;
1471
1472
0
  if (strcasecmp(key, "safe.bareRepository"))
1473
0
    return 0;
1474
1475
0
  if (!strcmp(value, "explicit")) {
1476
0
    *allowed_bare_repo = ALLOWED_BARE_REPO_EXPLICIT;
1477
0
    return 0;
1478
0
  }
1479
0
  if (!strcmp(value, "all")) {
1480
0
    *allowed_bare_repo = ALLOWED_BARE_REPO_ALL;
1481
0
    return 0;
1482
0
  }
1483
0
  return -1;
1484
0
}
1485
1486
static enum allowed_bare_repo get_allowed_bare_repo(void)
1487
0
{
1488
0
  enum allowed_bare_repo result = ALLOWED_BARE_REPO_ALL;
1489
0
  git_protected_config(allowed_bare_repo_cb, &result);
1490
0
  return result;
1491
0
}
1492
1493
static const char *allowed_bare_repo_to_string(
1494
  enum allowed_bare_repo allowed_bare_repo)
1495
0
{
1496
0
  switch (allowed_bare_repo) {
1497
0
  case ALLOWED_BARE_REPO_EXPLICIT:
1498
0
    return "explicit";
1499
0
  case ALLOWED_BARE_REPO_ALL:
1500
0
    return "all";
1501
0
  default:
1502
0
    BUG("invalid allowed_bare_repo %d",
1503
0
        allowed_bare_repo);
1504
0
  }
1505
0
  return NULL;
1506
0
}
1507
1508
static int is_implicit_bare_repo(const char *path)
1509
0
{
1510
  /*
1511
   * what we found is a ".git" directory at the root of
1512
   * the working tree.
1513
   */
1514
0
  if (ends_with_path_components(path, ".git"))
1515
0
    return 1;
1516
1517
  /*
1518
   * we are inside $GIT_DIR of a secondary worktree of a
1519
   * non-bare repository.
1520
   */
1521
0
  if (strstr(path, "/.git/worktrees/"))
1522
0
    return 1;
1523
1524
  /*
1525
   * we are inside $GIT_DIR of a worktree of a non-embedded
1526
   * submodule, whose superproject is not a bare repository.
1527
   */
1528
0
  if (strstr(path, "/.git/modules/"))
1529
0
    return 1;
1530
1531
0
  return 0;
1532
0
}
1533
1534
/*
1535
 * We cannot decide in this function whether we are in the work tree or
1536
 * not, since the config can only be read _after_ this function was called.
1537
 *
1538
 * Also, we avoid changing any global state (such as the current working
1539
 * directory) to allow early callers.
1540
 *
1541
 * The directory where the search should start needs to be passed in via the
1542
 * `dir` parameter; upon return, the `dir` buffer will contain the path of
1543
 * the directory where the search ended, and `gitdir` will contain the path of
1544
 * the discovered .git/ directory, if any. If `gitdir` is not absolute, it
1545
 * is relative to `dir` (i.e. *not* necessarily the cwd).
1546
 */
1547
static enum discovery_result setup_git_directory_gently_1(struct strbuf *dir,
1548
                struct strbuf *gitdir,
1549
                struct strbuf *report,
1550
                int die_on_error)
1551
0
{
1552
0
  const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
1553
0
  struct string_list ceiling_dirs = STRING_LIST_INIT_DUP;
1554
0
  const char *gitdirenv;
1555
0
  int ceil_offset = -1, min_offset = offset_1st_component(dir->buf);
1556
0
  dev_t current_device = 0;
1557
0
  int one_filesystem = 1;
1558
1559
  /*
1560
   * If GIT_DIR is set explicitly, we're not going
1561
   * to do any discovery, but we still do repository
1562
   * validation.
1563
   */
1564
0
  gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
1565
0
  if (gitdirenv) {
1566
0
    strbuf_addstr(gitdir, gitdirenv);
1567
0
    return GIT_DIR_EXPLICIT;
1568
0
  }
1569
1570
0
  if (env_ceiling_dirs) {
1571
0
    int empty_entry_found = 0;
1572
0
    static const char path_sep[] = { PATH_SEP, '\0' };
1573
1574
0
    string_list_split(&ceiling_dirs, env_ceiling_dirs, path_sep, -1);
1575
0
    filter_string_list(&ceiling_dirs, 0,
1576
0
           canonicalize_ceiling_entry, &empty_entry_found);
1577
0
    ceil_offset = longest_ancestor_length(dir->buf, &ceiling_dirs);
1578
0
    string_list_clear(&ceiling_dirs, 0);
1579
0
  }
1580
1581
0
  if (ceil_offset < 0)
1582
0
    ceil_offset = min_offset - 2;
1583
1584
0
  if (min_offset && min_offset == dir->len &&
1585
0
      !is_dir_sep(dir->buf[min_offset - 1])) {
1586
0
    strbuf_addch(dir, '/');
1587
0
    min_offset++;
1588
0
  }
1589
1590
  /*
1591
   * Test in the following order (relative to the dir):
1592
   * - .git (file containing "gitdir: <path>")
1593
   * - .git/
1594
   * - ./ (bare)
1595
   * - ../.git
1596
   * - ../.git/
1597
   * - ../ (bare)
1598
   * - ../../.git
1599
   *   etc.
1600
   */
1601
0
  one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
1602
0
  if (one_filesystem)
1603
0
    current_device = get_device_or_die(dir->buf, NULL, 0);
1604
0
  for (;;) {
1605
0
    int offset = dir->len, error_code = 0;
1606
0
    char *gitdir_path = NULL;
1607
0
    char *gitfile = NULL;
1608
1609
0
    if (offset > min_offset)
1610
0
      strbuf_addch(dir, '/');
1611
0
    strbuf_addstr(dir, DEFAULT_GIT_DIR_ENVIRONMENT);
1612
0
    gitdirenv = read_gitfile_gently(dir->buf, &error_code);
1613
0
    if (!gitdirenv) {
1614
0
      switch (error_code) {
1615
0
      case READ_GITFILE_ERR_MISSING:
1616
        /* no .git in this directory, move on */
1617
0
        break;
1618
0
      case READ_GITFILE_ERR_IS_A_DIR:
1619
0
        if (is_git_directory(dir->buf)) {
1620
0
          gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT;
1621
0
          gitdir_path = xstrdup(dir->buf);
1622
0
        }
1623
0
        break;
1624
0
      case READ_GITFILE_ERR_STAT_FAILED:
1625
0
        if (die_on_error)
1626
0
          die(_("error reading '%s'"), dir->buf);
1627
0
        else
1628
0
          return GIT_DIR_INVALID_GITFILE;
1629
0
      case READ_GITFILE_ERR_NOT_A_FILE:
1630
0
        if (die_on_error)
1631
0
          die(_("not a regular file: '%s'"), dir->buf);
1632
0
        else
1633
0
          return GIT_DIR_INVALID_GITFILE;
1634
0
      default:
1635
0
        if (die_on_error)
1636
0
          read_gitfile_error_die(error_code, dir->buf, NULL);
1637
0
        else
1638
0
          return GIT_DIR_INVALID_GITFILE;
1639
0
      }
1640
0
    } else {
1641
0
      gitfile = xstrdup(dir->buf);
1642
0
    }
1643
    /*
1644
     * Earlier, we tentatively added DEFAULT_GIT_DIR_ENVIRONMENT
1645
     * to check that directory for a repository.
1646
     * Now trim that tentative addition away, because we want to
1647
     * focus on the real directory we are in.
1648
     */
1649
0
    strbuf_setlen(dir, offset);
1650
0
    if (gitdirenv) {
1651
0
      enum discovery_result ret;
1652
0
      const char *gitdir_candidate =
1653
0
        gitdir_path ? gitdir_path : gitdirenv;
1654
1655
0
      if (ensure_valid_ownership(gitfile, dir->buf,
1656
0
               gitdir_candidate, report)) {
1657
0
        strbuf_addstr(gitdir, gitdirenv);
1658
0
        ret = GIT_DIR_DISCOVERED;
1659
0
      } else
1660
0
        ret = GIT_DIR_INVALID_OWNERSHIP;
1661
1662
      /*
1663
       * Earlier, during discovery, we might have allocated
1664
       * string copies for gitdir_path or gitfile so make
1665
       * sure we don't leak by freeing them now, before
1666
       * leaving the loop and function.
1667
       *
1668
       * Note: gitdirenv will be non-NULL whenever these are
1669
       * allocated, therefore we need not take care of releasing
1670
       * them outside of this conditional block.
1671
       */
1672
0
      free(gitdir_path);
1673
0
      free(gitfile);
1674
1675
0
      return ret;
1676
0
    }
1677
1678
0
    if (is_git_directory(dir->buf)) {
1679
0
      trace2_data_string("setup", NULL, "implicit-bare-repository", dir->buf);
1680
0
      if (get_allowed_bare_repo() == ALLOWED_BARE_REPO_EXPLICIT &&
1681
0
          !is_implicit_bare_repo(dir->buf))
1682
0
        return GIT_DIR_DISALLOWED_BARE;
1683
0
      if (!ensure_valid_ownership(NULL, NULL, dir->buf, report))
1684
0
        return GIT_DIR_INVALID_OWNERSHIP;
1685
0
      strbuf_addstr(gitdir, ".");
1686
0
      return GIT_DIR_BARE;
1687
0
    }
1688
1689
0
    if (offset <= min_offset)
1690
0
      return GIT_DIR_HIT_CEILING;
1691
1692
0
    while (--offset > ceil_offset && !is_dir_sep(dir->buf[offset]))
1693
0
      ; /* continue */
1694
0
    if (offset <= ceil_offset)
1695
0
      return GIT_DIR_HIT_CEILING;
1696
1697
0
    strbuf_setlen(dir, offset > min_offset ?  offset : min_offset);
1698
0
    if (one_filesystem &&
1699
0
        current_device != get_device_or_die(dir->buf, NULL, offset))
1700
0
      return GIT_DIR_HIT_MOUNT_POINT;
1701
0
  }
1702
0
}
1703
1704
enum discovery_result discover_git_directory_reason(struct strbuf *commondir,
1705
                struct strbuf *gitdir)
1706
0
{
1707
0
  struct strbuf dir = STRBUF_INIT, err = STRBUF_INIT;
1708
0
  size_t gitdir_offset = gitdir->len, cwd_len;
1709
0
  size_t commondir_offset = commondir->len;
1710
0
  struct repository_format candidate = REPOSITORY_FORMAT_INIT;
1711
0
  enum discovery_result result;
1712
1713
0
  if (strbuf_getcwd(&dir))
1714
0
    return GIT_DIR_CWD_FAILURE;
1715
1716
0
  cwd_len = dir.len;
1717
0
  result = setup_git_directory_gently_1(&dir, gitdir, NULL, 0);
1718
0
  if (result <= 0) {
1719
0
    strbuf_release(&dir);
1720
0
    return result;
1721
0
  }
1722
1723
  /*
1724
   * The returned gitdir is relative to dir, and if dir does not reflect
1725
   * the current working directory, we simply make the gitdir absolute.
1726
   */
1727
0
  if (dir.len < cwd_len && !is_absolute_path(gitdir->buf + gitdir_offset)) {
1728
    /* Avoid a trailing "/." */
1729
0
    if (!strcmp(".", gitdir->buf + gitdir_offset))
1730
0
      strbuf_setlen(gitdir, gitdir_offset);
1731
0
    else
1732
0
      strbuf_addch(&dir, '/');
1733
0
    strbuf_insert(gitdir, gitdir_offset, dir.buf, dir.len);
1734
0
  }
1735
1736
0
  get_common_dir(commondir, gitdir->buf + gitdir_offset);
1737
1738
0
  strbuf_reset(&dir);
1739
0
  strbuf_addf(&dir, "%s/config", commondir->buf + commondir_offset);
1740
0
  read_repository_format(&candidate, dir.buf);
1741
0
  strbuf_release(&dir);
1742
1743
0
  if (verify_repository_format(&candidate, &err) < 0) {
1744
0
    warning("ignoring git dir '%s': %s",
1745
0
      gitdir->buf + gitdir_offset, err.buf);
1746
0
    strbuf_release(&err);
1747
0
    strbuf_setlen(commondir, commondir_offset);
1748
0
    strbuf_setlen(gitdir, gitdir_offset);
1749
0
    clear_repository_format(&candidate);
1750
0
    return GIT_DIR_INVALID_FORMAT;
1751
0
  }
1752
1753
0
  clear_repository_format(&candidate);
1754
0
  return result;
1755
0
}
1756
1757
const char *enter_repo(const char *path, unsigned flags)
1758
0
{
1759
0
  static struct strbuf validated_path = STRBUF_INIT;
1760
0
  static struct strbuf used_path = STRBUF_INIT;
1761
1762
0
  if (!path)
1763
0
    return NULL;
1764
1765
0
  if (!(flags & ENTER_REPO_STRICT)) {
1766
0
    static const char *suffix[] = {
1767
0
      "/.git", "", ".git/.git", ".git", NULL,
1768
0
    };
1769
0
    const char *gitfile;
1770
0
    int len = strlen(path);
1771
0
    int i;
1772
0
    while ((1 < len) && (path[len-1] == '/'))
1773
0
      len--;
1774
1775
    /*
1776
     * We can handle arbitrary-sized buffers, but this remains as a
1777
     * sanity check on untrusted input.
1778
     */
1779
0
    if (PATH_MAX <= len)
1780
0
      return NULL;
1781
1782
0
    strbuf_reset(&used_path);
1783
0
    strbuf_reset(&validated_path);
1784
0
    strbuf_add(&used_path, path, len);
1785
0
    strbuf_add(&validated_path, path, len);
1786
1787
0
    if (used_path.buf[0] == '~') {
1788
0
      char *newpath = interpolate_path(used_path.buf, 0);
1789
0
      if (!newpath)
1790
0
        return NULL;
1791
0
      strbuf_attach(&used_path, newpath, strlen(newpath),
1792
0
              strlen(newpath));
1793
0
    }
1794
0
    for (i = 0; suffix[i]; i++) {
1795
0
      struct stat st;
1796
0
      size_t baselen = used_path.len;
1797
0
      strbuf_addstr(&used_path, suffix[i]);
1798
0
      if (!stat(used_path.buf, &st) &&
1799
0
          (S_ISREG(st.st_mode) ||
1800
0
          (S_ISDIR(st.st_mode) && is_git_directory(used_path.buf)))) {
1801
0
        strbuf_addstr(&validated_path, suffix[i]);
1802
0
        break;
1803
0
      }
1804
0
      strbuf_setlen(&used_path, baselen);
1805
0
    }
1806
0
    if (!suffix[i])
1807
0
      return NULL;
1808
0
    gitfile = read_gitfile(used_path.buf);
1809
0
    if (!(flags & ENTER_REPO_ANY_OWNER_OK))
1810
0
      die_upon_dubious_ownership(gitfile, NULL, used_path.buf);
1811
0
    if (gitfile) {
1812
0
      strbuf_reset(&used_path);
1813
0
      strbuf_addstr(&used_path, gitfile);
1814
0
    }
1815
0
    if (chdir(used_path.buf))
1816
0
      return NULL;
1817
0
    path = validated_path.buf;
1818
0
  }
1819
0
  else {
1820
0
    const char *gitfile = read_gitfile(path);
1821
0
    if (!(flags & ENTER_REPO_ANY_OWNER_OK))
1822
0
      die_upon_dubious_ownership(gitfile, NULL, path);
1823
0
    if (gitfile)
1824
0
      path = gitfile;
1825
0
    if (chdir(path))
1826
0
      return NULL;
1827
0
  }
1828
1829
0
  if (is_git_directory(".")) {
1830
0
    set_git_dir(".", 0);
1831
0
    check_repository_format(NULL);
1832
0
    return path;
1833
0
  }
1834
1835
0
  return NULL;
1836
0
}
1837
1838
static int git_work_tree_initialized;
1839
1840
/*
1841
 * Note.  This works only before you used a work tree.  This was added
1842
 * primarily to support git-clone to work in a new repository it just
1843
 * created, and is not meant to flip between different work trees.
1844
 */
1845
void set_git_work_tree(const char *new_work_tree)
1846
0
{
1847
0
  if (git_work_tree_initialized) {
1848
0
    struct strbuf realpath = STRBUF_INIT;
1849
1850
0
    strbuf_realpath(&realpath, new_work_tree, 1);
1851
0
    new_work_tree = realpath.buf;
1852
0
    if (strcmp(new_work_tree, the_repository->worktree))
1853
0
      die("internal error: work tree has already been set\n"
1854
0
          "Current worktree: %s\nNew worktree: %s",
1855
0
          the_repository->worktree, new_work_tree);
1856
0
    strbuf_release(&realpath);
1857
0
    return;
1858
0
  }
1859
0
  git_work_tree_initialized = 1;
1860
0
  repo_set_worktree(the_repository, new_work_tree);
1861
0
}
1862
1863
const char *setup_git_directory_gently(int *nongit_ok)
1864
0
{
1865
0
  static struct strbuf cwd = STRBUF_INIT;
1866
0
  struct strbuf dir = STRBUF_INIT, gitdir = STRBUF_INIT, report = STRBUF_INIT;
1867
0
  const char *prefix = NULL;
1868
0
  const char *ref_backend_uri;
1869
0
  struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1870
1871
  /*
1872
   * We may have read an incomplete configuration before
1873
   * setting-up the git directory. If so, clear the cache so
1874
   * that the next queries to the configuration reload complete
1875
   * configuration (including the per-repo config file that we
1876
   * ignored previously).
1877
   */
1878
0
  repo_config_clear(the_repository);
1879
1880
  /*
1881
   * Let's assume that we are in a git repository.
1882
   * If it turns out later that we are somewhere else, the value will be
1883
   * updated accordingly.
1884
   */
1885
0
  if (nongit_ok)
1886
0
    *nongit_ok = 0;
1887
1888
0
  if (strbuf_getcwd(&cwd))
1889
0
    die_errno(_("Unable to read current working directory"));
1890
0
  strbuf_addbuf(&dir, &cwd);
1891
1892
0
  switch (setup_git_directory_gently_1(&dir, &gitdir, &report, 1)) {
1893
0
  case GIT_DIR_EXPLICIT:
1894
0
    prefix = setup_explicit_git_dir(gitdir.buf, &cwd, &repo_fmt, nongit_ok);
1895
0
    break;
1896
0
  case GIT_DIR_DISCOVERED:
1897
0
    if (dir.len < cwd.len && chdir(dir.buf))
1898
0
      die(_("cannot change to '%s'"), dir.buf);
1899
0
    prefix = setup_discovered_git_dir(gitdir.buf, &cwd, dir.len,
1900
0
              &repo_fmt, nongit_ok);
1901
0
    break;
1902
0
  case GIT_DIR_BARE:
1903
0
    if (dir.len < cwd.len && chdir(dir.buf))
1904
0
      die(_("cannot change to '%s'"), dir.buf);
1905
0
    prefix = setup_bare_git_dir(&cwd, dir.len, &repo_fmt, nongit_ok);
1906
0
    break;
1907
0
  case GIT_DIR_HIT_CEILING:
1908
0
    if (!nongit_ok)
1909
0
      die(_("not a git repository (or any of the parent directories): %s"),
1910
0
          DEFAULT_GIT_DIR_ENVIRONMENT);
1911
0
    *nongit_ok = 1;
1912
0
    break;
1913
0
  case GIT_DIR_HIT_MOUNT_POINT:
1914
0
    if (!nongit_ok)
1915
0
      die(_("not a git repository (or any parent up to mount point %s)\n"
1916
0
            "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."),
1917
0
          dir.buf);
1918
0
    *nongit_ok = 1;
1919
0
    break;
1920
0
  case GIT_DIR_INVALID_OWNERSHIP:
1921
0
    if (!nongit_ok) {
1922
0
      struct strbuf quoted = STRBUF_INIT;
1923
1924
0
      strbuf_complete(&report, '\n');
1925
0
      sq_quote_buf_pretty(&quoted, dir.buf);
1926
0
      die(_("detected dubious ownership in repository at '%s'\n"
1927
0
            "%s"
1928
0
            "To add an exception for this directory, call:\n"
1929
0
            "\n"
1930
0
            "\tgit config --global --add safe.directory %s"),
1931
0
          dir.buf, report.buf, quoted.buf);
1932
0
    }
1933
0
    *nongit_ok = 1;
1934
0
    break;
1935
0
  case GIT_DIR_DISALLOWED_BARE:
1936
0
    if (!nongit_ok) {
1937
0
      die(_("cannot use bare repository '%s' (safe.bareRepository is '%s')"),
1938
0
          dir.buf,
1939
0
          allowed_bare_repo_to_string(get_allowed_bare_repo()));
1940
0
    }
1941
0
    *nongit_ok = 1;
1942
0
    break;
1943
0
  case GIT_DIR_CWD_FAILURE:
1944
0
  case GIT_DIR_INVALID_FORMAT:
1945
    /*
1946
     * As a safeguard against setup_git_directory_gently_1 returning
1947
     * these values, fallthrough to BUG. Otherwise it is possible to
1948
     * set startup_info->have_repository to 1 when we did nothing to
1949
     * find a repository.
1950
     */
1951
0
  default:
1952
0
    BUG("unhandled setup_git_directory_gently_1() result");
1953
0
  }
1954
1955
  /*
1956
   * At this point, nongit_ok is stable. If it is non-NULL and points
1957
   * to a non-zero value, then this means that we haven't found a
1958
   * repository and that the caller expects startup_info to reflect
1959
   * this.
1960
   *
1961
   * Regardless of the state of nongit_ok, startup_info->prefix and
1962
   * the GIT_PREFIX environment variable must always match. For details
1963
   * see Documentation/config/alias.adoc.
1964
   */
1965
0
  if (nongit_ok && *nongit_ok)
1966
0
    startup_info->have_repository = 0;
1967
0
  else
1968
0
    startup_info->have_repository = 1;
1969
1970
  /*
1971
   * Not all paths through the setup code will call 'set_git_dir()' (which
1972
   * directly sets up the environment) so in order to guarantee that the
1973
   * environment is in a consistent state after setup, explicitly setup
1974
   * the environment if we have a repository.
1975
   *
1976
   * NEEDSWORK: currently we allow bogus GIT_DIR values to be set in some
1977
   * code paths so we also need to explicitly setup the environment if
1978
   * the user has set GIT_DIR.  It may be beneficial to disallow bogus
1979
   * GIT_DIR values at some point in the future.
1980
   */
1981
0
  if (/* GIT_DIR_EXPLICIT, GIT_DIR_DISCOVERED, GIT_DIR_BARE */
1982
0
      startup_info->have_repository ||
1983
      /* GIT_DIR_EXPLICIT */
1984
0
      getenv(GIT_DIR_ENVIRONMENT)) {
1985
0
    if (!the_repository->gitdir) {
1986
0
      const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
1987
0
      if (!gitdir)
1988
0
        gitdir = DEFAULT_GIT_DIR_ENVIRONMENT;
1989
0
      setup_git_env(gitdir);
1990
0
    }
1991
0
    if (startup_info->have_repository) {
1992
0
      repo_set_hash_algo(the_repository, repo_fmt.hash_algo);
1993
0
      repo_set_compat_hash_algo(the_repository,
1994
0
              repo_fmt.compat_hash_algo);
1995
0
      repo_set_ref_storage_format(the_repository,
1996
0
                repo_fmt.ref_storage_format,
1997
0
                repo_fmt.ref_storage_payload);
1998
0
      the_repository->repository_format_worktree_config =
1999
0
        repo_fmt.worktree_config;
2000
0
      the_repository->repository_format_relative_worktrees =
2001
0
        repo_fmt.relative_worktrees;
2002
0
      the_repository->repository_format_submodule_path_cfg =
2003
0
        repo_fmt.submodule_path_cfg;
2004
      /* take ownership of repo_fmt.partial_clone */
2005
0
      the_repository->repository_format_partial_clone =
2006
0
        repo_fmt.partial_clone;
2007
0
      repo_fmt.partial_clone = NULL;
2008
0
      the_repository->repository_format_precious_objects =
2009
0
        repo_fmt.precious_objects;
2010
0
    }
2011
0
  }
2012
  /*
2013
   * Since precompose_string_if_needed() needs to look at
2014
   * the core.precomposeunicode configuration, this
2015
   * has to happen after the above block that finds
2016
   * out where the repository is, i.e. a preparation
2017
   * for calling repo_config_get_bool().
2018
   */
2019
0
  if (prefix) {
2020
0
    prefix = precompose_string_if_needed(prefix);
2021
0
    startup_info->prefix = prefix;
2022
0
    setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);
2023
0
  } else {
2024
0
    startup_info->prefix = NULL;
2025
0
    setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
2026
0
  }
2027
2028
  /*
2029
   * The env variable should override the repository config
2030
   * for 'extensions.refStorage'.
2031
   */
2032
0
  ref_backend_uri = getenv(GIT_REFERENCE_BACKEND_ENVIRONMENT);
2033
0
  if (ref_backend_uri) {
2034
0
    char *backend, *payload;
2035
0
    enum ref_storage_format format;
2036
2037
0
    parse_reference_uri(ref_backend_uri, &backend, &payload);
2038
0
    format = ref_storage_format_by_name(backend);
2039
0
    if (format == REF_STORAGE_FORMAT_UNKNOWN)
2040
0
      die(_("unknown ref storage format: '%s'"), backend);
2041
0
    repo_set_ref_storage_format(the_repository, format, payload);
2042
2043
0
    free(backend);
2044
0
    free(payload);
2045
0
  }
2046
2047
0
  setup_original_cwd();
2048
2049
0
  strbuf_release(&dir);
2050
0
  strbuf_release(&gitdir);
2051
0
  strbuf_release(&report);
2052
0
  clear_repository_format(&repo_fmt);
2053
2054
0
  return prefix;
2055
0
}
2056
2057
int git_config_perm(const char *var, const char *value)
2058
0
{
2059
0
  int i;
2060
0
  char *endptr;
2061
2062
0
  if (!value)
2063
0
    return PERM_GROUP;
2064
2065
0
  if (!strcmp(value, "umask"))
2066
0
    return PERM_UMASK;
2067
0
  if (!strcmp(value, "group"))
2068
0
    return PERM_GROUP;
2069
0
  if (!strcmp(value, "all") ||
2070
0
      !strcmp(value, "world") ||
2071
0
      !strcmp(value, "everybody"))
2072
0
    return PERM_EVERYBODY;
2073
2074
  /* Parse octal numbers */
2075
0
  i = strtol(value, &endptr, 8);
2076
2077
  /* If not an octal number, maybe true/false? */
2078
0
  if (*endptr != 0)
2079
0
    return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
2080
2081
  /*
2082
   * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
2083
   * a chmod value to restrict to.
2084
   */
2085
0
  switch (i) {
2086
0
  case PERM_UMASK:               /* 0 */
2087
0
    return PERM_UMASK;
2088
0
  case OLD_PERM_GROUP:           /* 1 */
2089
0
    return PERM_GROUP;
2090
0
  case OLD_PERM_EVERYBODY:       /* 2 */
2091
0
    return PERM_EVERYBODY;
2092
0
  }
2093
2094
  /* A filemode value was given: 0xxx */
2095
2096
0
  if ((i & 0600) != 0600)
2097
0
    die(_("problem with core.sharedRepository filemode value "
2098
0
        "(0%.3o).\nThe owner of files must always have "
2099
0
        "read and write permissions."), i);
2100
2101
  /*
2102
   * Mask filemode value. Others can not get write permission.
2103
   * x flags for directories are handled separately.
2104
   */
2105
0
  return -(i & 0666);
2106
0
}
2107
2108
void check_repository_format(struct repository_format *fmt)
2109
0
{
2110
0
  struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
2111
0
  if (!fmt)
2112
0
    fmt = &repo_fmt;
2113
0
  check_repository_format_gently(repo_get_git_dir(the_repository), fmt, NULL);
2114
0
  startup_info->have_repository = 1;
2115
0
  repo_set_hash_algo(the_repository, fmt->hash_algo);
2116
0
  repo_set_compat_hash_algo(the_repository, fmt->compat_hash_algo);
2117
0
  repo_set_ref_storage_format(the_repository,
2118
0
            fmt->ref_storage_format,
2119
0
            fmt->ref_storage_payload);
2120
0
  the_repository->repository_format_worktree_config =
2121
0
    fmt->worktree_config;
2122
0
  the_repository->repository_format_submodule_path_cfg =
2123
0
    fmt->submodule_path_cfg;
2124
0
  the_repository->repository_format_relative_worktrees =
2125
0
    fmt->relative_worktrees;
2126
0
  the_repository->repository_format_partial_clone =
2127
0
    xstrdup_or_null(fmt->partial_clone);
2128
0
  clear_repository_format(&repo_fmt);
2129
0
}
2130
2131
/*
2132
 * Returns the "prefix", a path to the current working directory
2133
 * relative to the work tree root, or NULL, if the current working
2134
 * directory is not a strict subdirectory of the work tree root. The
2135
 * prefix always ends with a '/' character.
2136
 */
2137
const char *setup_git_directory(void)
2138
0
{
2139
0
  return setup_git_directory_gently(NULL);
2140
0
}
2141
2142
const char *resolve_gitdir_gently(const char *suspect, int *return_error_code)
2143
0
{
2144
0
  if (is_git_directory(suspect))
2145
0
    return suspect;
2146
0
  return read_gitfile_gently(suspect, return_error_code);
2147
0
}
2148
2149
/* if any standard file descriptor is missing open it to /dev/null */
2150
void sanitize_stdfds(void)
2151
0
{
2152
0
  int fd = xopen("/dev/null", O_RDWR);
2153
0
  while (fd < 2)
2154
0
    fd = xdup(fd);
2155
0
  if (fd > 2)
2156
0
    close(fd);
2157
0
}
2158
2159
int daemonize(void)
2160
0
{
2161
#ifdef NO_POSIX_GOODIES
2162
  errno = ENOSYS;
2163
  return -1;
2164
#else
2165
0
  switch (fork()) {
2166
0
    case 0:
2167
0
      break;
2168
0
    case -1:
2169
0
      die_errno(_("fork failed"));
2170
0
    default:
2171
0
      exit(0);
2172
0
  }
2173
0
  if (setsid() == -1)
2174
0
    die_errno(_("setsid failed"));
2175
0
  close(0);
2176
0
  close(1);
2177
0
  close(2);
2178
0
  sanitize_stdfds();
2179
0
  return 0;
2180
0
#endif
2181
0
}
2182
2183
struct template_dir_cb_data {
2184
  char *path;
2185
  int initialized;
2186
};
2187
2188
static int template_dir_cb(const char *key, const char *value,
2189
         const struct config_context *ctx UNUSED, void *d)
2190
0
{
2191
0
  struct template_dir_cb_data *data = d;
2192
2193
0
  if (strcmp(key, "init.templatedir"))
2194
0
    return 0;
2195
2196
0
  if (!value) {
2197
0
    data->path = NULL;
2198
0
  } else {
2199
0
    char *path = NULL;
2200
2201
0
    FREE_AND_NULL(data->path);
2202
0
    if (!git_config_pathname(&path, key, value))
2203
0
      data->path = path ? path : xstrdup(value);
2204
0
  }
2205
2206
0
  return 0;
2207
0
}
2208
2209
const char *get_template_dir(const char *option_template)
2210
0
{
2211
0
  const char *template_dir = option_template;
2212
2213
0
  if (!template_dir)
2214
0
    template_dir = getenv(TEMPLATE_DIR_ENVIRONMENT);
2215
0
  if (!template_dir) {
2216
0
    static struct template_dir_cb_data data;
2217
2218
0
    if (!data.initialized) {
2219
0
      git_protected_config(template_dir_cb, &data);
2220
0
      data.initialized = 1;
2221
0
    }
2222
0
    template_dir = data.path;
2223
0
  }
2224
0
  if (!template_dir) {
2225
0
    static char *dir;
2226
2227
0
    if (!dir)
2228
0
      dir = system_path(DEFAULT_GIT_TEMPLATE_DIR);
2229
0
    template_dir = dir;
2230
0
  }
2231
0
  return template_dir;
2232
0
}
2233
2234
#ifdef NO_TRUSTABLE_FILEMODE
2235
#define TEST_FILEMODE 0
2236
#else
2237
0
#define TEST_FILEMODE 1
2238
#endif
2239
2240
0
#define GIT_DEFAULT_HASH_ENVIRONMENT "GIT_DEFAULT_HASH"
2241
2242
static void copy_templates_1(struct strbuf *path, struct strbuf *template_path,
2243
           DIR *dir)
2244
0
{
2245
0
  size_t path_baselen = path->len;
2246
0
  size_t template_baselen = template_path->len;
2247
0
  struct dirent *de;
2248
2249
  /* Note: if ".git/hooks" file exists in the repository being
2250
   * re-initialized, /etc/core-git/templates/hooks/update would
2251
   * cause "git init" to fail here.  I think this is sane but
2252
   * it means that the set of templates we ship by default, along
2253
   * with the way the namespace under .git/ is organized, should
2254
   * be really carefully chosen.
2255
   */
2256
0
  safe_create_dir(the_repository, path->buf, 1);
2257
0
  while ((de = readdir(dir)) != NULL) {
2258
0
    struct stat st_git, st_template;
2259
0
    int exists = 0;
2260
2261
0
    strbuf_setlen(path, path_baselen);
2262
0
    strbuf_setlen(template_path, template_baselen);
2263
2264
0
    if (de->d_name[0] == '.')
2265
0
      continue;
2266
0
    strbuf_addstr(path, de->d_name);
2267
0
    strbuf_addstr(template_path, de->d_name);
2268
0
    if (lstat(path->buf, &st_git)) {
2269
0
      if (errno != ENOENT)
2270
0
        die_errno(_("cannot stat '%s'"), path->buf);
2271
0
    }
2272
0
    else
2273
0
      exists = 1;
2274
2275
0
    if (lstat(template_path->buf, &st_template))
2276
0
      die_errno(_("cannot stat template '%s'"), template_path->buf);
2277
2278
0
    if (S_ISDIR(st_template.st_mode)) {
2279
0
      DIR *subdir = opendir(template_path->buf);
2280
0
      if (!subdir)
2281
0
        die_errno(_("cannot opendir '%s'"), template_path->buf);
2282
0
      strbuf_addch(path, '/');
2283
0
      strbuf_addch(template_path, '/');
2284
0
      copy_templates_1(path, template_path, subdir);
2285
0
      closedir(subdir);
2286
0
    }
2287
0
    else if (exists)
2288
0
      continue;
2289
0
    else if (S_ISLNK(st_template.st_mode)) {
2290
0
      struct strbuf lnk = STRBUF_INIT;
2291
0
      if (strbuf_readlink(&lnk, template_path->buf,
2292
0
              st_template.st_size) < 0)
2293
0
        die_errno(_("cannot readlink '%s'"), template_path->buf);
2294
0
      if (symlink(lnk.buf, path->buf))
2295
0
        die_errno(_("cannot symlink '%s' '%s'"),
2296
0
            lnk.buf, path->buf);
2297
0
      strbuf_release(&lnk);
2298
0
    }
2299
0
    else if (S_ISREG(st_template.st_mode)) {
2300
0
      if (copy_file(path->buf, template_path->buf, st_template.st_mode))
2301
0
        die_errno(_("cannot copy '%s' to '%s'"),
2302
0
            template_path->buf, path->buf);
2303
0
    }
2304
0
    else
2305
0
      error(_("ignoring template %s"), template_path->buf);
2306
0
  }
2307
0
}
2308
2309
static void copy_templates(const char *option_template)
2310
0
{
2311
0
  const char *template_dir = get_template_dir(option_template);
2312
0
  struct strbuf path = STRBUF_INIT;
2313
0
  struct strbuf template_path = STRBUF_INIT;
2314
0
  size_t template_len;
2315
0
  struct repository_format template_format = REPOSITORY_FORMAT_INIT;
2316
0
  struct strbuf err = STRBUF_INIT;
2317
0
  DIR *dir;
2318
0
  char *to_free = NULL;
2319
2320
0
  if (!template_dir || !*template_dir)
2321
0
    return;
2322
2323
0
  strbuf_addstr(&template_path, template_dir);
2324
0
  strbuf_complete(&template_path, '/');
2325
0
  template_len = template_path.len;
2326
2327
0
  dir = opendir(template_path.buf);
2328
0
  if (!dir) {
2329
0
    warning(_("templates not found in %s"), template_dir);
2330
0
    goto free_return;
2331
0
  }
2332
2333
  /* Make sure that template is from the correct vintage */
2334
0
  strbuf_addstr(&template_path, "config");
2335
0
  read_repository_format(&template_format, template_path.buf);
2336
0
  strbuf_setlen(&template_path, template_len);
2337
2338
  /*
2339
   * No mention of version at all is OK, but anything else should be
2340
   * verified.
2341
   */
2342
0
  if (template_format.version >= 0 &&
2343
0
      verify_repository_format(&template_format, &err) < 0) {
2344
0
    warning(_("not copying templates from '%s': %s"),
2345
0
        template_dir, err.buf);
2346
0
    strbuf_release(&err);
2347
0
    goto close_free_return;
2348
0
  }
2349
2350
0
  strbuf_addstr(&path, repo_get_common_dir(the_repository));
2351
0
  strbuf_complete(&path, '/');
2352
0
  copy_templates_1(&path, &template_path, dir);
2353
0
close_free_return:
2354
0
  closedir(dir);
2355
0
free_return:
2356
0
  free(to_free);
2357
0
  strbuf_release(&path);
2358
0
  strbuf_release(&template_path);
2359
0
  clear_repository_format(&template_format);
2360
0
}
2361
2362
/*
2363
 * If the git_dir is not directly inside the working tree, then git will not
2364
 * find it by default, and we need to set the worktree explicitly.
2365
 */
2366
static int needs_work_tree_config(const char *git_dir, const char *work_tree)
2367
0
{
2368
0
  if (!strcmp(work_tree, "/") && !strcmp(git_dir, "/.git"))
2369
0
    return 0;
2370
0
  if (skip_prefix(git_dir, work_tree, &git_dir) &&
2371
0
      !strcmp(git_dir, "/.git"))
2372
0
    return 0;
2373
0
  return 1;
2374
0
}
2375
2376
void initialize_repository_version(int hash_algo,
2377
           enum ref_storage_format ref_storage_format,
2378
           int reinit)
2379
0
{
2380
0
  struct strbuf repo_version = STRBUF_INIT;
2381
0
  int target_version = GIT_REPO_VERSION;
2382
0
  int default_submodule_path_config = 0;
2383
2384
  /*
2385
   * Note that we initialize the repository version to 1 when the ref
2386
   * storage format is unknown. This is on purpose so that we can add the
2387
   * correct object format to the config during git-clone(1). The format
2388
   * version will get adjusted by git-clone(1) once it has learned about
2389
   * the remote repository's format.
2390
   */
2391
0
  if (hash_algo != GIT_HASH_SHA1_LEGACY ||
2392
0
      ref_storage_format != REF_STORAGE_FORMAT_FILES ||
2393
0
      the_repository->ref_storage_payload)
2394
0
    target_version = GIT_REPO_VERSION_READ;
2395
2396
0
  if (hash_algo != GIT_HASH_SHA1_LEGACY && hash_algo != GIT_HASH_UNKNOWN)
2397
0
    repo_config_set(the_repository, "extensions.objectformat",
2398
0
        hash_algos[hash_algo].name);
2399
0
  else if (reinit)
2400
0
    repo_config_set_gently(the_repository, "extensions.objectformat", NULL);
2401
2402
0
  if (the_repository->ref_storage_payload) {
2403
0
    struct strbuf ref_uri = STRBUF_INIT;
2404
2405
0
    strbuf_addf(&ref_uri, "%s://%s",
2406
0
          ref_storage_format_to_name(ref_storage_format),
2407
0
          the_repository->ref_storage_payload);
2408
0
    repo_config_set(the_repository, "extensions.refstorage", ref_uri.buf);
2409
0
    strbuf_release(&ref_uri);
2410
0
  } else if (ref_storage_format != REF_STORAGE_FORMAT_FILES) {
2411
0
    repo_config_set(the_repository, "extensions.refstorage",
2412
0
        ref_storage_format_to_name(ref_storage_format));
2413
0
  } else if (reinit) {
2414
0
    repo_config_set_gently(the_repository, "extensions.refstorage", NULL);
2415
0
  }
2416
2417
0
  if (reinit) {
2418
0
    struct strbuf config = STRBUF_INIT;
2419
0
    struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
2420
2421
0
    repo_common_path_append(the_repository, &config, "config");
2422
0
    read_repository_format(&repo_fmt, config.buf);
2423
2424
0
    if (repo_fmt.v1_only_extensions.nr)
2425
0
      target_version = GIT_REPO_VERSION_READ;
2426
2427
0
    strbuf_release(&config);
2428
0
    clear_repository_format(&repo_fmt);
2429
0
  }
2430
2431
0
  repo_config_get_bool(the_repository, "init.defaultSubmodulePathConfig",
2432
0
           &default_submodule_path_config);
2433
0
  if (default_submodule_path_config) {
2434
    /* extensions.submodulepathconfig requires at least version 1 */
2435
0
    if (target_version == 0)
2436
0
      target_version = 1;
2437
0
    repo_config_set(the_repository, "extensions.submodulepathconfig", "true");
2438
0
  }
2439
2440
0
  strbuf_addf(&repo_version, "%d", target_version);
2441
0
  repo_config_set(the_repository, "core.repositoryformatversion", repo_version.buf);
2442
2443
0
  strbuf_release(&repo_version);
2444
0
}
2445
2446
static int is_reinit(void)
2447
0
{
2448
0
  struct strbuf buf = STRBUF_INIT;
2449
0
  char junk[2];
2450
0
  int ret;
2451
2452
0
  repo_git_path_replace(the_repository, &buf, "HEAD");
2453
0
  ret = !access(buf.buf, R_OK) || readlink(buf.buf, junk, sizeof(junk) - 1) != -1;
2454
0
  strbuf_release(&buf);
2455
0
  return ret;
2456
0
}
2457
2458
void create_reference_database(const char *initial_branch, int quiet)
2459
0
{
2460
0
  struct strbuf err = STRBUF_INIT;
2461
0
  char *to_free = NULL;
2462
0
  int reinit = is_reinit();
2463
2464
0
  if (ref_store_create_on_disk(get_main_ref_store(the_repository), 0, &err))
2465
0
    die("failed to set up refs db: %s", err.buf);
2466
2467
  /*
2468
   * Point the HEAD symref to the initial branch with if HEAD does
2469
   * not yet exist.
2470
   */
2471
0
  if (!reinit) {
2472
0
    char *ref;
2473
2474
0
    if (!initial_branch)
2475
0
      initial_branch = to_free =
2476
0
        repo_default_branch_name(the_repository, quiet);
2477
2478
0
    ref = xstrfmt("refs/heads/%s", initial_branch);
2479
0
    if (check_refname_format(ref, 0) < 0)
2480
0
      die(_("invalid initial branch name: '%s'"),
2481
0
          initial_branch);
2482
2483
0
    if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, NULL) < 0)
2484
0
      exit(1);
2485
0
    free(ref);
2486
0
  }
2487
2488
0
  if (reinit && initial_branch)
2489
0
    warning(_("re-init: ignored --initial-branch=%s"),
2490
0
      initial_branch);
2491
2492
0
  strbuf_release(&err);
2493
0
  free(to_free);
2494
0
}
2495
2496
static int create_default_files(const char *template_path,
2497
        const char *original_git_dir,
2498
        const struct repository_format *fmt,
2499
        int init_shared_repository)
2500
0
{
2501
0
  struct stat st1;
2502
0
  struct strbuf path = STRBUF_INIT;
2503
0
  int reinit;
2504
0
  int filemode;
2505
0
  const char *work_tree = repo_get_work_tree(the_repository);
2506
2507
  /*
2508
   * First copy the templates -- we might have the default
2509
   * config file there, in which case we would want to read
2510
   * from it after installing.
2511
   *
2512
   * Before reading that config, we also need to clear out any cached
2513
   * values (since we've just potentially changed what's available on
2514
   * disk).
2515
   */
2516
0
  copy_templates(template_path);
2517
0
  repo_config_clear(the_repository);
2518
0
  repo_settings_reset_shared_repository(the_repository);
2519
0
  repo_config(the_repository, git_default_config, NULL);
2520
2521
0
  reinit = is_reinit();
2522
2523
  /*
2524
   * We must make sure command-line options continue to override any
2525
   * values we might have just re-read from the config.
2526
   */
2527
0
  if (init_shared_repository != -1)
2528
0
    repo_settings_set_shared_repository(the_repository,
2529
0
                init_shared_repository);
2530
2531
0
  is_bare_repository_cfg = !work_tree;
2532
2533
  /*
2534
   * We would have created the above under user's umask -- under
2535
   * shared-repository settings, we would need to fix them up.
2536
   */
2537
0
  if (repo_settings_get_shared_repository(the_repository)) {
2538
0
    adjust_shared_perm(the_repository, repo_get_git_dir(the_repository));
2539
0
  }
2540
2541
0
  initialize_repository_version(fmt->hash_algo, fmt->ref_storage_format, reinit);
2542
2543
  /* Check filemode trustability */
2544
0
  repo_git_path_replace(the_repository, &path, "config");
2545
0
  filemode = TEST_FILEMODE;
2546
0
  if (TEST_FILEMODE && !lstat(path.buf, &st1)) {
2547
0
    struct stat st2;
2548
0
    filemode = (!chmod(path.buf, st1.st_mode ^ S_IXUSR) &&
2549
0
        !lstat(path.buf, &st2) &&
2550
0
        st1.st_mode != st2.st_mode &&
2551
0
        !chmod(path.buf, st1.st_mode));
2552
0
    if (filemode && !reinit && (st1.st_mode & S_IXUSR))
2553
0
      filemode = 0;
2554
0
  }
2555
0
  repo_config_set(the_repository, "core.filemode", filemode ? "true" : "false");
2556
2557
0
  if (is_bare_repository())
2558
0
    repo_config_set(the_repository, "core.bare", "true");
2559
0
  else {
2560
0
    repo_config_set(the_repository, "core.bare", "false");
2561
    /* allow template config file to override the default */
2562
0
    if (repo_settings_get_log_all_ref_updates(the_repository) == LOG_REFS_UNSET)
2563
0
      repo_config_set(the_repository, "core.logallrefupdates", "true");
2564
0
    if (needs_work_tree_config(original_git_dir, work_tree))
2565
0
      repo_config_set(the_repository, "core.worktree", work_tree);
2566
0
  }
2567
2568
0
  if (!reinit) {
2569
    /* Check if symlink is supported in the work tree */
2570
0
    repo_git_path_replace(the_repository, &path, "tXXXXXX");
2571
0
    if (!close(xmkstemp(path.buf)) &&
2572
0
        !unlink(path.buf) &&
2573
0
        !symlink("testing", path.buf) &&
2574
0
        !lstat(path.buf, &st1) &&
2575
0
        S_ISLNK(st1.st_mode))
2576
0
      unlink(path.buf); /* good */
2577
0
    else
2578
0
      repo_config_set(the_repository, "core.symlinks", "false");
2579
2580
    /* Check if the filesystem is case-insensitive */
2581
0
    repo_git_path_replace(the_repository, &path, "CoNfIg");
2582
0
    if (!access(path.buf, F_OK))
2583
0
      repo_config_set(the_repository, "core.ignorecase", "true");
2584
0
    probe_utf8_pathname_composition();
2585
0
  }
2586
2587
0
  strbuf_release(&path);
2588
0
  return reinit;
2589
0
}
2590
2591
static void create_object_directory(void)
2592
0
{
2593
0
  struct strbuf path = STRBUF_INIT;
2594
0
  size_t baselen;
2595
2596
0
  strbuf_addstr(&path, repo_get_object_directory(the_repository));
2597
0
  baselen = path.len;
2598
2599
0
  safe_create_dir(the_repository, path.buf, 1);
2600
2601
0
  strbuf_setlen(&path, baselen);
2602
0
  strbuf_addstr(&path, "/pack");
2603
0
  safe_create_dir(the_repository, path.buf, 1);
2604
2605
0
  strbuf_setlen(&path, baselen);
2606
0
  strbuf_addstr(&path, "/info");
2607
0
  safe_create_dir(the_repository, path.buf, 1);
2608
2609
0
  strbuf_release(&path);
2610
0
}
2611
2612
static void separate_git_dir(const char *git_dir, const char *git_link)
2613
0
{
2614
0
  struct stat st;
2615
2616
0
  if (!stat(git_link, &st)) {
2617
0
    const char *src;
2618
2619
0
    if (S_ISREG(st.st_mode))
2620
0
      src = read_gitfile(git_link);
2621
0
    else if (S_ISDIR(st.st_mode))
2622
0
      src = git_link;
2623
0
    else
2624
0
      die(_("unable to handle file type %d"), (int)st.st_mode);
2625
2626
0
    if (rename(src, git_dir))
2627
0
      die_errno(_("unable to move %s to %s"), src, git_dir);
2628
0
    repair_worktrees_after_gitdir_move(src);
2629
0
  }
2630
2631
0
  write_file(git_link, "gitdir: %s", git_dir);
2632
0
}
2633
2634
struct default_format_config {
2635
  int hash;
2636
  enum ref_storage_format ref_format;
2637
};
2638
2639
static int read_default_format_config(const char *key, const char *value,
2640
              const struct config_context *ctx UNUSED,
2641
              void *payload)
2642
0
{
2643
0
  struct default_format_config *cfg = payload;
2644
0
  char *str = NULL;
2645
0
  int ret;
2646
2647
0
  if (!strcmp(key, "init.defaultobjectformat")) {
2648
0
    ret = git_config_string(&str, key, value);
2649
0
    if (ret)
2650
0
      goto out;
2651
0
    cfg->hash = hash_algo_by_name(str);
2652
0
    if (cfg->hash == GIT_HASH_UNKNOWN)
2653
0
      warning(_("unknown hash algorithm '%s'"), str);
2654
0
    goto out;
2655
0
  }
2656
2657
0
  if (!strcmp(key, "init.defaultrefformat")) {
2658
0
    ret = git_config_string(&str, key, value);
2659
0
    if (ret)
2660
0
      goto out;
2661
0
    cfg->ref_format = ref_storage_format_by_name(str);
2662
0
    if (cfg->ref_format == REF_STORAGE_FORMAT_UNKNOWN)
2663
0
      warning(_("unknown ref storage format '%s'"), str);
2664
0
    goto out;
2665
0
  }
2666
2667
  /*
2668
   * Enable the reftable format when "features.experimental" is enabled.
2669
   * "init.defaultRefFormat" takes precedence over this setting.
2670
   */
2671
0
  if (!strcmp(key, "feature.experimental") &&
2672
0
      cfg->ref_format == REF_STORAGE_FORMAT_UNKNOWN &&
2673
0
      git_config_bool(key, value)) {
2674
0
    cfg->ref_format = REF_STORAGE_FORMAT_REFTABLE;
2675
0
    ret = 0;
2676
0
    goto out;
2677
0
  }
2678
2679
0
  ret = 0;
2680
0
out:
2681
0
  free(str);
2682
0
  return ret;
2683
0
}
2684
2685
static void repository_format_configure(struct repository_format *repo_fmt,
2686
          int hash, enum ref_storage_format ref_format)
2687
0
{
2688
0
  struct default_format_config cfg = {
2689
0
    .hash = GIT_HASH_UNKNOWN,
2690
0
    .ref_format = REF_STORAGE_FORMAT_UNKNOWN,
2691
0
  };
2692
0
  struct config_options opts = {
2693
0
    .respect_includes = 1,
2694
0
    .ignore_repo = 1,
2695
0
    .ignore_worktree = 1,
2696
0
  };
2697
0
  const char *ref_backend_uri;
2698
0
  const char *env;
2699
2700
0
  config_with_options(read_default_format_config, &cfg, NULL, NULL, &opts);
2701
2702
  /*
2703
   * If we already have an initialized repo, don't allow the user to
2704
   * specify a different algorithm, as that could cause corruption.
2705
   * Otherwise, if the user has specified one on the command line, use it.
2706
   */
2707
0
  env = getenv(GIT_DEFAULT_HASH_ENVIRONMENT);
2708
0
  if (repo_fmt->version >= 0 && hash != GIT_HASH_UNKNOWN && hash != repo_fmt->hash_algo)
2709
0
    die(_("attempt to reinitialize repository with different hash"));
2710
0
  else if (hash != GIT_HASH_UNKNOWN)
2711
0
    repo_fmt->hash_algo = hash;
2712
0
  else if (env) {
2713
0
    int env_algo = hash_algo_by_name(env);
2714
0
    if (env_algo == GIT_HASH_UNKNOWN)
2715
0
      die(_("unknown hash algorithm '%s'"), env);
2716
0
    if (repo_fmt->version < 0 ||
2717
0
        repo_fmt->hash_algo == GIT_HASH_UNKNOWN)
2718
0
      repo_fmt->hash_algo = env_algo;
2719
0
  } else if (cfg.hash != GIT_HASH_UNKNOWN) {
2720
0
    repo_fmt->hash_algo = cfg.hash;
2721
0
  }
2722
0
  repo_set_hash_algo(the_repository, repo_fmt->hash_algo);
2723
2724
0
  env = getenv("GIT_DEFAULT_REF_FORMAT");
2725
0
  if (repo_fmt->version >= 0 &&
2726
0
      ref_format != REF_STORAGE_FORMAT_UNKNOWN &&
2727
0
      ref_format != repo_fmt->ref_storage_format) {
2728
0
    die(_("attempt to reinitialize repository with different reference storage format"));
2729
0
  } else if (ref_format != REF_STORAGE_FORMAT_UNKNOWN) {
2730
0
    repo_fmt->ref_storage_format = ref_format;
2731
0
  } else if (env) {
2732
0
    ref_format = ref_storage_format_by_name(env);
2733
0
    if (ref_format == REF_STORAGE_FORMAT_UNKNOWN)
2734
0
      die(_("unknown ref storage format '%s'"), env);
2735
0
    if (repo_fmt->version < 0 ||
2736
0
        repo_fmt->ref_storage_format == REF_STORAGE_FORMAT_UNKNOWN)
2737
0
      repo_fmt->ref_storage_format = ref_format;
2738
0
  } else if (cfg.ref_format != REF_STORAGE_FORMAT_UNKNOWN) {
2739
0
    repo_fmt->ref_storage_format = cfg.ref_format;
2740
0
  } else {
2741
0
    repo_fmt->ref_storage_format = REF_STORAGE_FORMAT_DEFAULT;
2742
0
  }
2743
2744
2745
0
  ref_backend_uri = getenv(GIT_REFERENCE_BACKEND_ENVIRONMENT);
2746
0
  if (ref_backend_uri) {
2747
0
    char *backend, *payload;
2748
0
    enum ref_storage_format format;
2749
2750
0
    parse_reference_uri(ref_backend_uri, &backend, &payload);
2751
0
    format = ref_storage_format_by_name(backend);
2752
0
    if (format == REF_STORAGE_FORMAT_UNKNOWN)
2753
0
      die(_("unknown ref storage format: '%s'"), backend);
2754
2755
0
    repo_fmt->ref_storage_format = format;
2756
0
    repo_fmt->ref_storage_payload = payload;
2757
2758
0
    free(backend);
2759
0
  }
2760
2761
0
  repo_set_ref_storage_format(the_repository, repo_fmt->ref_storage_format,
2762
0
            repo_fmt->ref_storage_payload);
2763
0
}
2764
2765
int init_db(const char *git_dir, const char *real_git_dir,
2766
      const char *template_dir, int hash,
2767
      enum ref_storage_format ref_storage_format,
2768
      const char *initial_branch,
2769
      int init_shared_repository, unsigned int flags)
2770
0
{
2771
0
  int reinit;
2772
0
  int exist_ok = flags & INIT_DB_EXIST_OK;
2773
0
  char *original_git_dir = real_pathdup(git_dir, 1);
2774
0
  struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
2775
2776
0
  if (real_git_dir) {
2777
0
    struct stat st;
2778
2779
0
    if (!exist_ok && !stat(git_dir, &st))
2780
0
      die(_("%s already exists"), git_dir);
2781
2782
0
    if (!exist_ok && !stat(real_git_dir, &st))
2783
0
      die(_("%s already exists"), real_git_dir);
2784
2785
0
    set_git_dir(real_git_dir, 1);
2786
0
    git_dir = repo_get_git_dir(the_repository);
2787
0
    separate_git_dir(git_dir, original_git_dir);
2788
0
  }
2789
0
  else {
2790
0
    set_git_dir(git_dir, 1);
2791
0
    git_dir = repo_get_git_dir(the_repository);
2792
0
  }
2793
0
  startup_info->have_repository = 1;
2794
2795
  /*
2796
   * Check to see if the repository version is right.
2797
   * Note that a newly created repository does not have
2798
   * config file, so this will not fail.  What we are catching
2799
   * is an attempt to reinitialize new repository with an old tool.
2800
   */
2801
0
  check_repository_format(&repo_fmt);
2802
2803
0
  repository_format_configure(&repo_fmt, hash, ref_storage_format);
2804
2805
  /*
2806
   * Ensure `core.hidedotfiles` is processed. This must happen after we
2807
   * have set up the repository format such that we can evaluate
2808
   * includeIf conditions correctly in the case of re-initialization.
2809
   */
2810
0
  repo_config(the_repository, git_default_core_config, NULL);
2811
2812
0
  safe_create_dir(the_repository, git_dir, 0);
2813
2814
0
  reinit = create_default_files(template_dir, original_git_dir,
2815
0
              &repo_fmt, init_shared_repository);
2816
2817
0
  if (!(flags & INIT_DB_SKIP_REFDB))
2818
0
    create_reference_database(initial_branch, flags & INIT_DB_QUIET);
2819
0
  create_object_directory();
2820
2821
0
  if (repo_settings_get_shared_repository(the_repository)) {
2822
0
    char buf[10];
2823
    /* We do not spell "group" and such, so that
2824
     * the configuration can be read by older version
2825
     * of git. Note, we use octal numbers for new share modes,
2826
     * and compatibility values for PERM_GROUP and
2827
     * PERM_EVERYBODY.
2828
     */
2829
0
    if (repo_settings_get_shared_repository(the_repository) < 0)
2830
      /* force to the mode value */
2831
0
      xsnprintf(buf, sizeof(buf), "0%o", -repo_settings_get_shared_repository(the_repository));
2832
0
    else if (repo_settings_get_shared_repository(the_repository) == PERM_GROUP)
2833
0
      xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_GROUP);
2834
0
    else if (repo_settings_get_shared_repository(the_repository) == PERM_EVERYBODY)
2835
0
      xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_EVERYBODY);
2836
0
    else
2837
0
      BUG("invalid value for shared_repository");
2838
0
    repo_config_set(the_repository, "core.sharedrepository", buf);
2839
0
    repo_config_set(the_repository, "receive.denyNonFastforwards", "true");
2840
0
  }
2841
2842
0
  if (!(flags & INIT_DB_QUIET)) {
2843
0
    int len = strlen(git_dir);
2844
2845
0
    if (reinit)
2846
0
      printf(repo_settings_get_shared_repository(the_repository)
2847
0
             ? _("Reinitialized existing shared Git repository in %s%s\n")
2848
0
             : _("Reinitialized existing Git repository in %s%s\n"),
2849
0
             git_dir, len && git_dir[len-1] != '/' ? "/" : "");
2850
0
    else
2851
0
      printf(repo_settings_get_shared_repository(the_repository)
2852
0
             ? _("Initialized empty shared Git repository in %s%s\n")
2853
0
             : _("Initialized empty Git repository in %s%s\n"),
2854
0
             git_dir, len && git_dir[len-1] != '/' ? "/" : "");
2855
0
  }
2856
2857
0
  clear_repository_format(&repo_fmt);
2858
0
  free(original_git_dir);
2859
0
  return 0;
2860
0
}