Coverage Report

Created: 2026-12-01 06:58

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