Coverage Report

Created: 2023-11-19 07:08

/src/git/setup.c
Line
Count
Source (jump to first uncovered line)
1
#include "git-compat-util.h"
2
#include "abspath.h"
3
#include "copy.h"
4
#include "environment.h"
5
#include "exec-cmd.h"
6
#include "gettext.h"
7
#include "object-name.h"
8
#include "refs.h"
9
#include "repository.h"
10
#include "config.h"
11
#include "dir.h"
12
#include "setup.h"
13
#include "string-list.h"
14
#include "chdir-notify.h"
15
#include "path.h"
16
#include "promisor-remote.h"
17
#include "quote.h"
18
#include "trace2.h"
19
#include "worktree.h"
20
21
static int inside_git_dir = -1;
22
static int inside_work_tree = -1;
23
static int work_tree_config_is_bogus;
24
enum allowed_bare_repo {
25
  ALLOWED_BARE_REPO_EXPLICIT = 0,
26
  ALLOWED_BARE_REPO_ALL,
27
};
28
29
static struct startup_info the_startup_info;
30
struct startup_info *startup_info = &the_startup_info;
31
const char *tmp_original_cwd;
32
33
/*
34
 * The input parameter must contain an absolute path, and it must already be
35
 * normalized.
36
 *
37
 * Find the part of an absolute path that lies inside the work tree by
38
 * dereferencing symlinks outside the work tree, for example:
39
 * /dir1/repo/dir2/file   (work tree is /dir1/repo)      -> dir2/file
40
 * /dir/file              (work tree is /)               -> dir/file
41
 * /dir/symlink1/symlink2 (symlink1 points to work tree) -> symlink2
42
 * /dir/repolink/file     (repolink points to /dir/repo) -> file
43
 * /dir/repo              (exactly equal to work tree)   -> (empty string)
44
 */
45
static int abspath_part_inside_repo(char *path)
46
0
{
47
0
  size_t len;
48
0
  size_t wtlen;
49
0
  char *path0;
50
0
  int off;
51
0
  const char *work_tree = get_git_work_tree();
52
0
  struct strbuf realpath = STRBUF_INIT;
53
54
0
  if (!work_tree)
55
0
    return -1;
56
0
  wtlen = strlen(work_tree);
57
0
  len = strlen(path);
58
0
  off = offset_1st_component(path);
59
60
  /* check if work tree is already the prefix */
61
0
  if (wtlen <= len && !fspathncmp(path, work_tree, wtlen)) {
62
0
    if (path[wtlen] == '/') {
63
0
      memmove(path, path + wtlen + 1, len - wtlen);
64
0
      return 0;
65
0
    } else if (path[wtlen - 1] == '/' || path[wtlen] == '\0') {
66
      /* work tree is the root, or the whole path */
67
0
      memmove(path, path + wtlen, len - wtlen + 1);
68
0
      return 0;
69
0
    }
70
    /* work tree might match beginning of a symlink to work tree */
71
0
    off = wtlen;
72
0
  }
73
0
  path0 = path;
74
0
  path += off;
75
76
  /* check each '/'-terminated level */
77
0
  while (*path) {
78
0
    path++;
79
0
    if (*path == '/') {
80
0
      *path = '\0';
81
0
      strbuf_realpath(&realpath, path0, 1);
82
0
      if (fspathcmp(realpath.buf, work_tree) == 0) {
83
0
        memmove(path0, path + 1, len - (path - path0));
84
0
        strbuf_release(&realpath);
85
0
        return 0;
86
0
      }
87
0
      *path = '/';
88
0
    }
89
0
  }
90
91
  /* check whole path */
92
0
  strbuf_realpath(&realpath, path0, 1);
93
0
  if (fspathcmp(realpath.buf, work_tree) == 0) {
94
0
    *path0 = '\0';
95
0
    strbuf_release(&realpath);
96
0
    return 0;
97
0
  }
98
99
0
  strbuf_release(&realpath);
100
0
  return -1;
101
0
}
102
103
/*
104
 * Normalize "path", prepending the "prefix" for relative paths. If
105
 * remaining_prefix is not NULL, return the actual prefix still
106
 * remains in the path. For example, prefix = sub1/sub2/ and path is
107
 *
108
 *  foo          -> sub1/sub2/foo  (full prefix)
109
 *  ../foo       -> sub1/foo       (remaining prefix is sub1/)
110
 *  ../../bar    -> bar            (no remaining prefix)
111
 *  ../../sub1/sub2/foo -> sub1/sub2/foo (but no remaining prefix)
112
 *  `pwd`/../bar -> sub1/bar       (no remaining prefix)
113
 */
114
char *prefix_path_gently(const char *prefix, int len,
115
       int *remaining_prefix, const char *path)
116
23.1k
{
117
23.1k
  const char *orig = path;
118
23.1k
  char *sanitized;
119
23.1k
  if (is_absolute_path(orig)) {
120
0
    sanitized = xmallocz(strlen(path));
121
0
    if (remaining_prefix)
122
0
      *remaining_prefix = 0;
123
0
    if (normalize_path_copy_len(sanitized, path, remaining_prefix)) {
124
0
      free(sanitized);
125
0
      return NULL;
126
0
    }
127
0
    if (abspath_part_inside_repo(sanitized)) {
128
0
      free(sanitized);
129
0
      return NULL;
130
0
    }
131
23.1k
  } else {
132
23.1k
    sanitized = xstrfmt("%.*s%s", len, len ? prefix : "", path);
133
23.1k
    if (remaining_prefix)
134
18.6k
      *remaining_prefix = len;
135
23.1k
    if (normalize_path_copy_len(sanitized, sanitized, remaining_prefix)) {
136
0
      free(sanitized);
137
0
      return NULL;
138
0
    }
139
23.1k
  }
140
23.1k
  return sanitized;
141
23.1k
}
142
143
char *prefix_path(const char *prefix, int len, const char *path)
144
0
{
145
0
  char *r = prefix_path_gently(prefix, len, NULL, path);
146
0
  if (!r) {
147
0
    const char *hint_path = get_git_work_tree();
148
0
    if (!hint_path)
149
0
      hint_path = get_git_dir();
150
0
    die(_("'%s' is outside repository at '%s'"), path,
151
0
        absolute_path(hint_path));
152
0
  }
153
0
  return r;
154
0
}
155
156
int path_inside_repo(const char *prefix, const char *path)
157
4.49k
{
158
4.49k
  int len = prefix ? strlen(prefix) : 0;
159
4.49k
  char *r = prefix_path_gently(prefix, len, NULL, path);
160
4.49k
  if (r) {
161
4.49k
    free(r);
162
4.49k
    return 1;
163
4.49k
  }
164
0
  return 0;
165
4.49k
}
166
167
int check_filename(const char *prefix, const char *arg)
168
13.4k
{
169
13.4k
  char *to_free = NULL;
170
13.4k
  struct stat st;
171
172
13.4k
  if (skip_prefix(arg, ":/", &arg)) {
173
0
    if (!*arg) /* ":/" is root dir, always exists */
174
0
      return 1;
175
0
    prefix = NULL;
176
13.4k
  } else if (skip_prefix(arg, ":!", &arg) ||
177
13.4k
       skip_prefix(arg, ":^", &arg)) {
178
0
    if (!*arg) /* excluding everything is silly, but allowed */
179
0
      return 1;
180
0
  }
181
182
13.4k
  if (prefix)
183
3.37k
    arg = to_free = prefix_filename(prefix, arg);
184
185
13.4k
  if (!lstat(arg, &st)) {
186
6.74k
    free(to_free);
187
6.74k
    return 1; /* file exists */
188
6.74k
  }
189
6.74k
  if (is_missing_file_error(errno)) {
190
6.74k
    free(to_free);
191
6.74k
    return 0; /* file does not exist */
192
6.74k
  }
193
0
  die_errno(_("failed to stat '%s'"), arg);
194
6.74k
}
195
196
static void NORETURN die_verify_filename(struct repository *r,
197
           const char *prefix,
198
           const char *arg,
199
           int diagnose_misspelt_rev)
200
0
{
201
0
  if (!diagnose_misspelt_rev)
202
0
    die(_("%s: no such path in the working tree.\n"
203
0
          "Use 'git <command> -- <path>...' to specify paths that do not exist locally."),
204
0
        arg);
205
  /*
206
   * Saying "'(icase)foo' does not exist in the index" when the
207
   * user gave us ":(icase)foo" is just stupid.  A magic pathspec
208
   * begins with a colon and is followed by a non-alnum; do not
209
   * let maybe_die_on_misspelt_object_name() even trigger.
210
   */
211
0
  if (!(arg[0] == ':' && !isalnum(arg[1])))
212
0
    maybe_die_on_misspelt_object_name(r, arg, prefix);
213
214
  /* ... or fall back the most general message. */
215
0
  die(_("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
216
0
        "Use '--' to separate paths from revisions, like this:\n"
217
0
        "'git <command> [<revision>...] -- [<file>...]'"), arg);
218
219
0
}
220
221
/*
222
 * Check for arguments that don't resolve as actual files,
223
 * but which look sufficiently like pathspecs that we'll consider
224
 * them such for the purposes of rev/pathspec DWIM parsing.
225
 */
226
static int looks_like_pathspec(const char *arg)
227
6.74k
{
228
6.74k
  const char *p;
229
6.74k
  int escaped = 0;
230
231
  /*
232
   * Wildcard characters imply the user is looking to match pathspecs
233
   * that aren't in the filesystem. Note that this doesn't include
234
   * backslash even though it's a glob special; by itself it doesn't
235
   * cause any increase in the match. Likewise ignore backslash-escaped
236
   * wildcard characters.
237
   */
238
47.2k
  for (p = arg; *p; p++) {
239
40.4k
    if (escaped) {
240
0
      escaped = 0;
241
40.4k
    } else if (is_glob_special(*p)) {
242
0
      if (*p == '\\')
243
0
        escaped = 1;
244
0
      else
245
0
        return 1;
246
0
    }
247
40.4k
  }
248
249
  /* long-form pathspec magic */
250
6.74k
  if (starts_with(arg, ":("))
251
0
    return 1;
252
253
6.74k
  return 0;
254
6.74k
}
255
256
/*
257
 * Verify a filename that we got as an argument for a pathspec
258
 * entry. Note that a filename that begins with "-" never verifies
259
 * as true, because even if such a filename were to exist, we want
260
 * it to be preceded by the "--" marker (or we want the user to
261
 * use a format like "./-filename")
262
 *
263
 * The "diagnose_misspelt_rev" is used to provide a user-friendly
264
 * diagnosis when dying upon finding that "name" is not a pathname.
265
 * If set to 1, the diagnosis will try to diagnose "name" as an
266
 * invalid object name (e.g. HEAD:foo). If set to 0, the diagnosis
267
 * will only complain about an inexisting file.
268
 *
269
 * This function is typically called to check that a "file or rev"
270
 * argument is unambiguous. In this case, the caller will want
271
 * diagnose_misspelt_rev == 1 when verifying the first non-rev
272
 * argument (which could have been a revision), and
273
 * diagnose_misspelt_rev == 0 for the next ones (because we already
274
 * saw a filename, there's not ambiguity anymore).
275
 */
276
void verify_filename(const char *prefix,
277
         const char *arg,
278
         int diagnose_misspelt_rev)
279
6.74k
{
280
6.74k
  if (*arg == '-')
281
0
    die(_("option '%s' must come before non-option arguments"), arg);
282
6.74k
  if (looks_like_pathspec(arg) || check_filename(prefix, arg))
283
6.74k
    return;
284
0
  die_verify_filename(the_repository, prefix, arg, diagnose_misspelt_rev);
285
6.74k
}
286
287
/*
288
 * Opposite of the above: the command line did not have -- marker
289
 * and we parsed the arg as a refname.  It should not be interpretable
290
 * as a filename.
291
 */
292
void verify_non_filename(const char *prefix, const char *arg)
293
6.74k
{
294
6.74k
  if (!is_inside_work_tree() || is_inside_git_dir())
295
0
    return;
296
6.74k
  if (*arg == '-')
297
0
    return; /* flag */
298
6.74k
  if (!check_filename(prefix, arg))
299
6.74k
    return;
300
0
  die(_("ambiguous argument '%s': both revision and filename\n"
301
0
        "Use '--' to separate paths from revisions, like this:\n"
302
0
        "'git <command> [<revision>...] -- [<file>...]'"), arg);
303
6.74k
}
304
305
int get_common_dir(struct strbuf *sb, const char *gitdir)
306
21.4k
{
307
21.4k
  const char *git_env_common_dir = getenv(GIT_COMMON_DIR_ENVIRONMENT);
308
21.4k
  if (git_env_common_dir) {
309
0
    strbuf_addstr(sb, git_env_common_dir);
310
0
    return 1;
311
21.4k
  } else {
312
21.4k
    return get_common_dir_noenv(sb, gitdir);
313
21.4k
  }
314
21.4k
}
315
316
int get_common_dir_noenv(struct strbuf *sb, const char *gitdir)
317
32.7k
{
318
32.7k
  struct strbuf data = STRBUF_INIT;
319
32.7k
  struct strbuf path = STRBUF_INIT;
320
32.7k
  int ret = 0;
321
322
32.7k
  strbuf_addf(&path, "%s/commondir", gitdir);
323
32.7k
  if (file_exists(path.buf)) {
324
0
    if (strbuf_read_file(&data, path.buf, 0) <= 0)
325
0
      die_errno(_("failed to read %s"), path.buf);
326
0
    while (data.len && (data.buf[data.len - 1] == '\n' ||
327
0
            data.buf[data.len - 1] == '\r'))
328
0
      data.len--;
329
0
    data.buf[data.len] = '\0';
330
0
    strbuf_reset(&path);
331
0
    if (!is_absolute_path(data.buf))
332
0
      strbuf_addf(&path, "%s/", gitdir);
333
0
    strbuf_addbuf(&path, &data);
334
0
    strbuf_add_real_path(sb, path.buf);
335
0
    ret = 1;
336
32.7k
  } else {
337
32.7k
    strbuf_addstr(sb, gitdir);
338
32.7k
  }
339
340
32.7k
  strbuf_release(&data);
341
32.7k
  strbuf_release(&path);
342
32.7k
  return ret;
343
32.7k
}
344
345
/*
346
 * Test if it looks like we're at a git directory.
347
 * We want to see:
348
 *
349
 *  - either an objects/ directory _or_ the proper
350
 *    GIT_OBJECT_DIRECTORY environment variable
351
 *  - a refs/ directory
352
 *  - either a HEAD symlink or a HEAD file that is formatted as
353
 *    a proper "ref:", or a regular file HEAD that has a properly
354
 *    formatted sha1 object name.
355
 */
356
int is_git_directory(const char *suspect)
357
11.5k
{
358
11.5k
  struct strbuf path = STRBUF_INIT;
359
11.5k
  int ret = 0;
360
11.5k
  size_t len;
361
362
  /* Check worktree-related signatures */
363
11.5k
  strbuf_addstr(&path, suspect);
364
11.5k
  strbuf_complete(&path, '/');
365
11.5k
  strbuf_addstr(&path, "HEAD");
366
11.5k
  if (validate_headref(path.buf))
367
1.38k
    goto done;
368
369
10.1k
  strbuf_reset(&path);
370
10.1k
  get_common_dir(&path, suspect);
371
10.1k
  len = path.len;
372
373
  /* Check non-worktree-related signatures */
374
10.1k
  if (getenv(DB_ENVIRONMENT)) {
375
0
    if (access(getenv(DB_ENVIRONMENT), X_OK))
376
0
      goto done;
377
0
  }
378
10.1k
  else {
379
10.1k
    strbuf_setlen(&path, len);
380
10.1k
    strbuf_addstr(&path, "/objects");
381
10.1k
    if (access(path.buf, X_OK))
382
0
      goto done;
383
10.1k
  }
384
385
10.1k
  strbuf_setlen(&path, len);
386
10.1k
  strbuf_addstr(&path, "/refs");
387
10.1k
  if (access(path.buf, X_OK))
388
0
    goto done;
389
390
10.1k
  ret = 1;
391
11.5k
done:
392
11.5k
  strbuf_release(&path);
393
11.5k
  return ret;
394
10.1k
}
395
396
int is_nonbare_repository_dir(struct strbuf *path)
397
1.38k
{
398
1.38k
  int ret = 0;
399
1.38k
  int gitfile_error;
400
1.38k
  size_t orig_path_len = path->len;
401
1.38k
  assert(orig_path_len != 0);
402
1.38k
  strbuf_complete(path, '/');
403
1.38k
  strbuf_addstr(path, ".git");
404
1.38k
  if (read_gitfile_gently(path->buf, &gitfile_error) || is_git_directory(path->buf))
405
0
    ret = 1;
406
1.38k
  if (gitfile_error == READ_GITFILE_ERR_OPEN_FAILED ||
407
1.38k
      gitfile_error == READ_GITFILE_ERR_READ_FAILED)
408
0
    ret = 1;
409
1.38k
  strbuf_setlen(path, orig_path_len);
410
1.38k
  return ret;
411
1.38k
}
412
413
int is_inside_git_dir(void)
414
6.74k
{
415
6.74k
  if (inside_git_dir < 0)
416
1
    inside_git_dir = is_inside_dir(get_git_dir());
417
6.74k
  return inside_git_dir;
418
6.74k
}
419
420
int is_inside_work_tree(void)
421
6.74k
{
422
6.74k
  if (inside_work_tree < 0)
423
1
    inside_work_tree = is_inside_dir(get_git_work_tree());
424
6.74k
  return inside_work_tree;
425
6.74k
}
426
427
void setup_work_tree(void)
428
11.2k
{
429
11.2k
  const char *work_tree;
430
11.2k
  static int initialized = 0;
431
432
11.2k
  if (initialized)
433
11.2k
    return;
434
435
1
  if (work_tree_config_is_bogus)
436
0
    die(_("unable to set up work tree using invalid config"));
437
438
1
  work_tree = get_git_work_tree();
439
1
  if (!work_tree || chdir_notify(work_tree))
440
0
    die(_("this operation must be run in a work tree"));
441
442
  /*
443
   * Make sure subsequent git processes find correct worktree
444
   * if $GIT_WORK_TREE is set relative
445
   */
446
1
  if (getenv(GIT_WORK_TREE_ENVIRONMENT))
447
0
    setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
448
449
1
  initialized = 1;
450
1
}
451
452
static void setup_original_cwd(void)
453
10.1k
{
454
10.1k
  struct strbuf tmp = STRBUF_INIT;
455
10.1k
  const char *worktree = NULL;
456
10.1k
  int offset = -1;
457
458
10.1k
  if (!tmp_original_cwd)
459
10.1k
    return;
460
461
  /*
462
   * startup_info->original_cwd points to the current working
463
   * directory we inherited from our parent process, which is a
464
   * directory we want to avoid removing.
465
   *
466
   * For convience, we would like to have the path relative to the
467
   * worktree instead of an absolute path.
468
   *
469
   * Yes, startup_info->original_cwd is usually the same as 'prefix',
470
   * but differs in two ways:
471
   *   - prefix has a trailing '/'
472
   *   - if the user passes '-C' to git, that modifies the prefix but
473
   *     not startup_info->original_cwd.
474
   */
475
476
  /* Normalize the directory */
477
0
  if (!strbuf_realpath(&tmp, tmp_original_cwd, 0)) {
478
0
    trace2_data_string("setup", the_repository,
479
0
           "realpath-path", tmp_original_cwd);
480
0
    trace2_data_string("setup", the_repository,
481
0
           "realpath-failure", strerror(errno));
482
0
    free((char*)tmp_original_cwd);
483
0
    tmp_original_cwd = NULL;
484
0
    return;
485
0
  }
486
487
0
  free((char*)tmp_original_cwd);
488
0
  tmp_original_cwd = NULL;
489
0
  startup_info->original_cwd = strbuf_detach(&tmp, NULL);
490
491
  /*
492
   * Get our worktree; we only protect the current working directory
493
   * if it's in the worktree.
494
   */
495
0
  worktree = get_git_work_tree();
496
0
  if (!worktree)
497
0
    goto no_prevention_needed;
498
499
0
  offset = dir_inside_of(startup_info->original_cwd, worktree);
500
0
  if (offset >= 0) {
501
    /*
502
     * If startup_info->original_cwd == worktree, that is already
503
     * protected and we don't need original_cwd as a secondary
504
     * protection measure.
505
     */
506
0
    if (!*(startup_info->original_cwd + offset))
507
0
      goto no_prevention_needed;
508
509
    /*
510
     * original_cwd was inside worktree; precompose it just as
511
     * we do prefix so that built up paths will match
512
     */
513
0
    startup_info->original_cwd = \
514
0
      precompose_string_if_needed(startup_info->original_cwd
515
0
                + offset);
516
0
    return;
517
0
  }
518
519
0
no_prevention_needed:
520
0
  free((char*)startup_info->original_cwd);
521
0
  startup_info->original_cwd = NULL;
522
0
}
523
524
static int read_worktree_config(const char *var, const char *value,
525
        const struct config_context *ctx UNUSED,
526
        void *vdata)
527
30.3k
{
528
30.3k
  struct repository_format *data = vdata;
529
530
30.3k
  if (strcmp(var, "core.bare") == 0) {
531
10.1k
    data->is_bare = git_config_bool(var, value);
532
20.2k
  } else if (strcmp(var, "core.worktree") == 0) {
533
0
    if (!value)
534
0
      return config_error_nonbool(var);
535
0
    free(data->work_tree);
536
0
    data->work_tree = xstrdup(value);
537
0
  }
538
30.3k
  return 0;
539
30.3k
}
540
541
enum extension_result {
542
  EXTENSION_ERROR = -1, /* compatible with error(), etc */
543
  EXTENSION_UNKNOWN = 0,
544
  EXTENSION_OK = 1
545
};
546
547
/*
548
 * Do not add new extensions to this function. It handles extensions which are
549
 * respected even in v0-format repositories for historical compatibility.
550
 */
551
static enum extension_result handle_extension_v0(const char *var,
552
             const char *value,
553
             const char *ext,
554
             struct repository_format *data)
555
0
{
556
0
    if (!strcmp(ext, "noop")) {
557
0
      return EXTENSION_OK;
558
0
    } else if (!strcmp(ext, "preciousobjects")) {
559
0
      data->precious_objects = git_config_bool(var, value);
560
0
      return EXTENSION_OK;
561
0
    } else if (!strcmp(ext, "partialclone")) {
562
0
      data->partial_clone = xstrdup(value);
563
0
      return EXTENSION_OK;
564
0
    } else if (!strcmp(ext, "worktreeconfig")) {
565
0
      data->worktree_config = git_config_bool(var, value);
566
0
      return EXTENSION_OK;
567
0
    }
568
569
0
    return EXTENSION_UNKNOWN;
570
0
}
571
572
/*
573
 * Record any new extensions in this function.
574
 */
575
static enum extension_result handle_extension(const char *var,
576
                const char *value,
577
                const char *ext,
578
                struct repository_format *data)
579
0
{
580
0
  if (!strcmp(ext, "noop-v1")) {
581
0
    return EXTENSION_OK;
582
0
  } else if (!strcmp(ext, "objectformat")) {
583
0
    int format;
584
585
0
    if (!value)
586
0
      return config_error_nonbool(var);
587
0
    format = hash_algo_by_name(value);
588
0
    if (format == GIT_HASH_UNKNOWN)
589
0
      return error(_("invalid value for '%s': '%s'"),
590
0
             "extensions.objectformat", value);
591
0
    data->hash_algo = format;
592
0
    return EXTENSION_OK;
593
0
  }
594
0
  return EXTENSION_UNKNOWN;
595
0
}
596
597
static int check_repo_format(const char *var, const char *value,
598
           const struct config_context *ctx, void *vdata)
599
30.3k
{
600
30.3k
  struct repository_format *data = vdata;
601
30.3k
  const char *ext;
602
603
30.3k
  if (strcmp(var, "core.repositoryformatversion") == 0)
604
10.1k
    data->version = git_config_int(var, value, ctx->kvi);
605
20.2k
  else if (skip_prefix(var, "extensions.", &ext)) {
606
0
    switch (handle_extension_v0(var, value, ext, data)) {
607
0
    case EXTENSION_ERROR:
608
0
      return -1;
609
0
    case EXTENSION_OK:
610
0
      return 0;
611
0
    case EXTENSION_UNKNOWN:
612
0
      break;
613
0
    }
614
615
0
    switch (handle_extension(var, value, ext, data)) {
616
0
    case EXTENSION_ERROR:
617
0
      return -1;
618
0
    case EXTENSION_OK:
619
0
      string_list_append(&data->v1_only_extensions, ext);
620
0
      return 0;
621
0
    case EXTENSION_UNKNOWN:
622
0
      string_list_append(&data->unknown_extensions, ext);
623
0
      return 0;
624
0
    }
625
0
  }
626
627
30.3k
  return read_worktree_config(var, value, ctx, vdata);
628
30.3k
}
629
630
static int check_repository_format_gently(const char *gitdir, struct repository_format *candidate, int *nongit_ok)
631
11.3k
{
632
11.3k
  struct strbuf sb = STRBUF_INIT;
633
11.3k
  struct strbuf err = STRBUF_INIT;
634
11.3k
  int has_common;
635
636
11.3k
  has_common = get_common_dir(&sb, gitdir);
637
11.3k
  strbuf_addstr(&sb, "/config");
638
11.3k
  read_repository_format(candidate, sb.buf);
639
11.3k
  strbuf_release(&sb);
640
641
  /*
642
   * For historical use of check_repository_format() in git-init,
643
   * we treat a missing config as a silent "ok", even when nongit_ok
644
   * is unset.
645
   */
646
11.3k
  if (candidate->version < 0)
647
1.22k
    return 0;
648
649
10.1k
  if (verify_repository_format(candidate, &err) < 0) {
650
0
    if (nongit_ok) {
651
0
      warning("%s", err.buf);
652
0
      strbuf_release(&err);
653
0
      *nongit_ok = -1;
654
0
      return -1;
655
0
    }
656
0
    die("%s", err.buf);
657
0
  }
658
659
10.1k
  repository_format_precious_objects = candidate->precious_objects;
660
10.1k
  string_list_clear(&candidate->unknown_extensions, 0);
661
10.1k
  string_list_clear(&candidate->v1_only_extensions, 0);
662
663
10.1k
  if (candidate->worktree_config) {
664
    /*
665
     * pick up core.bare and core.worktree from per-worktree
666
     * config if present
667
     */
668
0
    strbuf_addf(&sb, "%s/config.worktree", gitdir);
669
0
    git_config_from_file(read_worktree_config, sb.buf, candidate);
670
0
    strbuf_release(&sb);
671
0
    has_common = 0;
672
0
  }
673
674
10.1k
  if (!has_common) {
675
10.1k
    if (candidate->is_bare != -1) {
676
10.1k
      is_bare_repository_cfg = candidate->is_bare;
677
10.1k
      if (is_bare_repository_cfg == 1)
678
0
        inside_work_tree = -1;
679
10.1k
    }
680
10.1k
    if (candidate->work_tree) {
681
0
      free(git_work_tree_cfg);
682
0
      git_work_tree_cfg = xstrdup(candidate->work_tree);
683
0
      inside_work_tree = -1;
684
0
    }
685
10.1k
  }
686
687
10.1k
  return 0;
688
10.1k
}
689
690
int upgrade_repository_format(int target_version)
691
0
{
692
0
  struct strbuf sb = STRBUF_INIT;
693
0
  struct strbuf err = STRBUF_INIT;
694
0
  struct strbuf repo_version = STRBUF_INIT;
695
0
  struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
696
0
  int ret;
697
698
0
  strbuf_git_common_path(&sb, the_repository, "config");
699
0
  read_repository_format(&repo_fmt, sb.buf);
700
0
  strbuf_release(&sb);
701
702
0
  if (repo_fmt.version >= target_version) {
703
0
    ret = 0;
704
0
    goto out;
705
0
  }
706
707
0
  if (verify_repository_format(&repo_fmt, &err) < 0) {
708
0
    ret = error("cannot upgrade repository format from %d to %d: %s",
709
0
          repo_fmt.version, target_version, err.buf);
710
0
    goto out;
711
0
  }
712
0
  if (!repo_fmt.version && repo_fmt.unknown_extensions.nr) {
713
0
    ret = error("cannot upgrade repository format: "
714
0
          "unknown extension %s",
715
0
          repo_fmt.unknown_extensions.items[0].string);
716
0
    goto out;
717
0
  }
718
719
0
  strbuf_addf(&repo_version, "%d", target_version);
720
0
  git_config_set("core.repositoryformatversion", repo_version.buf);
721
722
0
  ret = 1;
723
724
0
out:
725
0
  clear_repository_format(&repo_fmt);
726
0
  strbuf_release(&repo_version);
727
0
  strbuf_release(&err);
728
0
  return ret;
729
0
}
730
731
static void init_repository_format(struct repository_format *format)
732
28.7k
{
733
28.7k
  const struct repository_format fresh = REPOSITORY_FORMAT_INIT;
734
735
28.7k
  memcpy(format, &fresh, sizeof(fresh));
736
28.7k
}
737
738
int read_repository_format(struct repository_format *format, const char *path)
739
12.5k
{
740
12.5k
  clear_repository_format(format);
741
12.5k
  git_config_from_file(check_repo_format, path, format);
742
12.5k
  if (format->version == -1)
743
2.44k
    clear_repository_format(format);
744
12.5k
  return format->version;
745
12.5k
}
746
747
void clear_repository_format(struct repository_format *format)
748
28.7k
{
749
28.7k
  string_list_clear(&format->unknown_extensions, 0);
750
28.7k
  string_list_clear(&format->v1_only_extensions, 0);
751
28.7k
  free(format->work_tree);
752
28.7k
  free(format->partial_clone);
753
28.7k
  init_repository_format(format);
754
28.7k
}
755
756
int verify_repository_format(const struct repository_format *format,
757
           struct strbuf *err)
758
10.1k
{
759
10.1k
  if (GIT_REPO_VERSION_READ < format->version) {
760
0
    strbuf_addf(err, _("Expected git repo version <= %d, found %d"),
761
0
          GIT_REPO_VERSION_READ, format->version);
762
0
    return -1;
763
0
  }
764
765
10.1k
  if (format->version >= 1 && format->unknown_extensions.nr) {
766
0
    int i;
767
768
0
    strbuf_addstr(err, Q_("unknown repository extension found:",
769
0
              "unknown repository extensions found:",
770
0
              format->unknown_extensions.nr));
771
772
0
    for (i = 0; i < format->unknown_extensions.nr; i++)
773
0
      strbuf_addf(err, "\n\t%s",
774
0
            format->unknown_extensions.items[i].string);
775
0
    return -1;
776
0
  }
777
778
10.1k
  if (format->version == 0 && format->v1_only_extensions.nr) {
779
0
    int i;
780
781
0
    strbuf_addstr(err,
782
0
            Q_("repo version is 0, but v1-only extension found:",
783
0
         "repo version is 0, but v1-only extensions found:",
784
0
         format->v1_only_extensions.nr));
785
786
0
    for (i = 0; i < format->v1_only_extensions.nr; i++)
787
0
      strbuf_addf(err, "\n\t%s",
788
0
            format->v1_only_extensions.items[i].string);
789
0
    return -1;
790
0
  }
791
792
10.1k
  return 0;
793
10.1k
}
794
795
void read_gitfile_error_die(int error_code, const char *path, const char *dir)
796
21.4k
{
797
21.4k
  switch (error_code) {
798
1.22k
  case READ_GITFILE_ERR_STAT_FAILED:
799
21.4k
  case READ_GITFILE_ERR_NOT_A_FILE:
800
    /* non-fatal; follow return path */
801
21.4k
    break;
802
0
  case READ_GITFILE_ERR_OPEN_FAILED:
803
0
    die_errno(_("error opening '%s'"), path);
804
0
  case READ_GITFILE_ERR_TOO_LARGE:
805
0
    die(_("too large to be a .git file: '%s'"), path);
806
0
  case READ_GITFILE_ERR_READ_FAILED:
807
0
    die(_("error reading %s"), path);
808
0
  case READ_GITFILE_ERR_INVALID_FORMAT:
809
0
    die(_("invalid gitfile format: %s"), path);
810
0
  case READ_GITFILE_ERR_NO_PATH:
811
0
    die(_("no path in gitfile: %s"), path);
812
0
  case READ_GITFILE_ERR_NOT_A_REPO:
813
0
    die(_("not a git repository: %s"), dir);
814
0
  default:
815
0
    BUG("unknown error code");
816
21.4k
  }
817
21.4k
}
818
819
/*
820
 * Try to read the location of the git directory from the .git file,
821
 * return path to git directory if found. The return value comes from
822
 * a shared buffer.
823
 *
824
 * On failure, if return_error_code is not NULL, return_error_code
825
 * will be set to an error code and NULL will be returned. If
826
 * return_error_code is NULL the function will die instead (for most
827
 * cases).
828
 */
829
const char *read_gitfile_gently(const char *path, int *return_error_code)
830
22.8k
{
831
22.8k
  const int max_file_size = 1 << 20;  /* 1MB */
832
22.8k
  int error_code = 0;
833
22.8k
  char *buf = NULL;
834
22.8k
  char *dir = NULL;
835
22.8k
  const char *slash;
836
22.8k
  struct stat st;
837
22.8k
  int fd;
838
22.8k
  ssize_t len;
839
22.8k
  static struct strbuf realpath = STRBUF_INIT;
840
841
22.8k
  if (stat(path, &st)) {
842
    /* NEEDSWORK: discern between ENOENT vs other errors */
843
2.60k
    error_code = READ_GITFILE_ERR_STAT_FAILED;
844
2.60k
    goto cleanup_return;
845
2.60k
  }
846
20.2k
  if (!S_ISREG(st.st_mode)) {
847
20.2k
    error_code = READ_GITFILE_ERR_NOT_A_FILE;
848
20.2k
    goto cleanup_return;
849
20.2k
  }
850
0
  if (st.st_size > max_file_size) {
851
0
    error_code = READ_GITFILE_ERR_TOO_LARGE;
852
0
    goto cleanup_return;
853
0
  }
854
0
  fd = open(path, O_RDONLY);
855
0
  if (fd < 0) {
856
0
    error_code = READ_GITFILE_ERR_OPEN_FAILED;
857
0
    goto cleanup_return;
858
0
  }
859
0
  buf = xmallocz(st.st_size);
860
0
  len = read_in_full(fd, buf, st.st_size);
861
0
  close(fd);
862
0
  if (len != st.st_size) {
863
0
    error_code = READ_GITFILE_ERR_READ_FAILED;
864
0
    goto cleanup_return;
865
0
  }
866
0
  if (!starts_with(buf, "gitdir: ")) {
867
0
    error_code = READ_GITFILE_ERR_INVALID_FORMAT;
868
0
    goto cleanup_return;
869
0
  }
870
0
  while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
871
0
    len--;
872
0
  if (len < 9) {
873
0
    error_code = READ_GITFILE_ERR_NO_PATH;
874
0
    goto cleanup_return;
875
0
  }
876
0
  buf[len] = '\0';
877
0
  dir = buf + 8;
878
879
0
  if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) {
880
0
    size_t pathlen = slash+1 - path;
881
0
    dir = xstrfmt("%.*s%.*s", (int)pathlen, path,
882
0
            (int)(len - 8), buf + 8);
883
0
    free(buf);
884
0
    buf = dir;
885
0
  }
886
0
  if (!is_git_directory(dir)) {
887
0
    error_code = READ_GITFILE_ERR_NOT_A_REPO;
888
0
    goto cleanup_return;
889
0
  }
890
891
0
  strbuf_realpath(&realpath, dir, 1);
892
0
  path = realpath.buf;
893
894
22.8k
cleanup_return:
895
22.8k
  if (return_error_code)
896
1.38k
    *return_error_code = error_code;
897
21.4k
  else if (error_code)
898
21.4k
    read_gitfile_error_die(error_code, path, dir);
899
900
22.8k
  free(buf);
901
22.8k
  return error_code ? NULL : path;
902
0
}
903
904
static const char *setup_explicit_git_dir(const char *gitdirenv,
905
            struct strbuf *cwd,
906
            struct repository_format *repo_fmt,
907
            int *nongit_ok)
908
10.1k
{
909
10.1k
  const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
910
10.1k
  const char *worktree;
911
10.1k
  char *gitfile;
912
10.1k
  int offset;
913
914
10.1k
  if (PATH_MAX - 40 < strlen(gitdirenv))
915
0
    die(_("'$%s' too big"), GIT_DIR_ENVIRONMENT);
916
917
10.1k
  gitfile = (char*)read_gitfile(gitdirenv);
918
10.1k
  if (gitfile) {
919
0
    gitfile = xstrdup(gitfile);
920
0
    gitdirenv = gitfile;
921
0
  }
922
923
10.1k
  if (!is_git_directory(gitdirenv)) {
924
0
    if (nongit_ok) {
925
0
      *nongit_ok = 1;
926
0
      free(gitfile);
927
0
      return NULL;
928
0
    }
929
0
    die(_("not a git repository: '%s'"), gitdirenv);
930
0
  }
931
932
10.1k
  if (check_repository_format_gently(gitdirenv, repo_fmt, nongit_ok)) {
933
0
    free(gitfile);
934
0
    return NULL;
935
0
  }
936
937
  /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
938
10.1k
  if (work_tree_env)
939
0
    set_git_work_tree(work_tree_env);
940
10.1k
  else if (is_bare_repository_cfg > 0) {
941
0
    if (git_work_tree_cfg) {
942
      /* #22.2, #30 */
943
0
      warning("core.bare and core.worktree do not make sense");
944
0
      work_tree_config_is_bogus = 1;
945
0
    }
946
947
    /* #18, #26 */
948
0
    set_git_dir(gitdirenv, 0);
949
0
    free(gitfile);
950
0
    return NULL;
951
0
  }
952
10.1k
  else if (git_work_tree_cfg) { /* #6, #14 */
953
10.1k
    if (is_absolute_path(git_work_tree_cfg))
954
10.1k
      set_git_work_tree(git_work_tree_cfg);
955
0
    else {
956
0
      char *core_worktree;
957
0
      if (chdir(gitdirenv))
958
0
        die_errno(_("cannot chdir to '%s'"), gitdirenv);
959
0
      if (chdir(git_work_tree_cfg))
960
0
        die_errno(_("cannot chdir to '%s'"), git_work_tree_cfg);
961
0
      core_worktree = xgetcwd();
962
0
      if (chdir(cwd->buf))
963
0
        die_errno(_("cannot come back to cwd"));
964
0
      set_git_work_tree(core_worktree);
965
0
      free(core_worktree);
966
0
    }
967
10.1k
  }
968
0
  else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, 1)) {
969
    /* #16d */
970
0
    set_git_dir(gitdirenv, 0);
971
0
    free(gitfile);
972
0
    return NULL;
973
0
  }
974
0
  else /* #2, #10 */
975
0
    set_git_work_tree(".");
976
977
  /* set_git_work_tree() must have been called by now */
978
10.1k
  worktree = get_git_work_tree();
979
980
  /* both get_git_work_tree() and cwd are already normalized */
981
10.1k
  if (!strcmp(cwd->buf, worktree)) { /* cwd == worktree */
982
10.1k
    set_git_dir(gitdirenv, 0);
983
10.1k
    free(gitfile);
984
10.1k
    return NULL;
985
10.1k
  }
986
987
0
  offset = dir_inside_of(cwd->buf, worktree);
988
0
  if (offset >= 0) { /* cwd inside worktree? */
989
0
    set_git_dir(gitdirenv, 1);
990
0
    if (chdir(worktree))
991
0
      die_errno(_("cannot chdir to '%s'"), worktree);
992
0
    strbuf_addch(cwd, '/');
993
0
    free(gitfile);
994
0
    return cwd->buf + offset;
995
0
  }
996
997
  /* cwd outside worktree */
998
0
  set_git_dir(gitdirenv, 0);
999
0
  free(gitfile);
1000
0
  return NULL;
1001
0
}
1002
1003
static const char *setup_discovered_git_dir(const char *gitdir,
1004
              struct strbuf *cwd, int offset,
1005
              struct repository_format *repo_fmt,
1006
              int *nongit_ok)
1007
0
{
1008
0
  if (check_repository_format_gently(gitdir, repo_fmt, nongit_ok))
1009
0
    return NULL;
1010
1011
  /* --work-tree is set without --git-dir; use discovered one */
1012
0
  if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1013
0
    char *to_free = NULL;
1014
0
    const char *ret;
1015
1016
0
    if (offset != cwd->len && !is_absolute_path(gitdir))
1017
0
      gitdir = to_free = real_pathdup(gitdir, 1);
1018
0
    if (chdir(cwd->buf))
1019
0
      die_errno(_("cannot come back to cwd"));
1020
0
    ret = setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1021
0
    free(to_free);
1022
0
    return ret;
1023
0
  }
1024
1025
  /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
1026
0
  if (is_bare_repository_cfg > 0) {
1027
0
    set_git_dir(gitdir, (offset != cwd->len));
1028
0
    if (chdir(cwd->buf))
1029
0
      die_errno(_("cannot come back to cwd"));
1030
0
    return NULL;
1031
0
  }
1032
1033
  /* #0, #1, #5, #8, #9, #12, #13 */
1034
0
  set_git_work_tree(".");
1035
0
  if (strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT))
1036
0
    set_git_dir(gitdir, 0);
1037
0
  inside_git_dir = 0;
1038
0
  inside_work_tree = 1;
1039
0
  if (offset >= cwd->len)
1040
0
    return NULL;
1041
1042
  /* Make "offset" point past the '/' (already the case for root dirs) */
1043
0
  if (offset != offset_1st_component(cwd->buf))
1044
0
    offset++;
1045
  /* Add a '/' at the end */
1046
0
  strbuf_addch(cwd, '/');
1047
0
  return cwd->buf + offset;
1048
0
}
1049
1050
/* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
1051
static const char *setup_bare_git_dir(struct strbuf *cwd, int offset,
1052
              struct repository_format *repo_fmt,
1053
              int *nongit_ok)
1054
0
{
1055
0
  int root_len;
1056
1057
0
  if (check_repository_format_gently(".", repo_fmt, nongit_ok))
1058
0
    return NULL;
1059
1060
0
  setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, "0", 1);
1061
1062
  /* --work-tree is set without --git-dir; use discovered one */
1063
0
  if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1064
0
    static const char *gitdir;
1065
1066
0
    gitdir = offset == cwd->len ? "." : xmemdupz(cwd->buf, offset);
1067
0
    if (chdir(cwd->buf))
1068
0
      die_errno(_("cannot come back to cwd"));
1069
0
    return setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1070
0
  }
1071
1072
0
  inside_git_dir = 1;
1073
0
  inside_work_tree = 0;
1074
0
  if (offset != cwd->len) {
1075
0
    if (chdir(cwd->buf))
1076
0
      die_errno(_("cannot come back to cwd"));
1077
0
    root_len = offset_1st_component(cwd->buf);
1078
0
    strbuf_setlen(cwd, offset > root_len ? offset : root_len);
1079
0
    set_git_dir(cwd->buf, 0);
1080
0
  }
1081
0
  else
1082
0
    set_git_dir(".", 0);
1083
0
  return NULL;
1084
0
}
1085
1086
static dev_t get_device_or_die(const char *path, const char *prefix, int prefix_len)
1087
0
{
1088
0
  struct stat buf;
1089
0
  if (stat(path, &buf)) {
1090
0
    die_errno(_("failed to stat '%*s%s%s'"),
1091
0
        prefix_len,
1092
0
        prefix ? prefix : "",
1093
0
        prefix ? "/" : "", path);
1094
0
  }
1095
0
  return buf.st_dev;
1096
0
}
1097
1098
/*
1099
 * A "string_list_each_func_t" function that canonicalizes an entry
1100
 * from GIT_CEILING_DIRECTORIES using real_pathdup(), or
1101
 * discards it if unusable.  The presence of an empty entry in
1102
 * GIT_CEILING_DIRECTORIES turns off canonicalization for all
1103
 * subsequent entries.
1104
 */
1105
static int canonicalize_ceiling_entry(struct string_list_item *item,
1106
              void *cb_data)
1107
0
{
1108
0
  int *empty_entry_found = cb_data;
1109
0
  char *ceil = item->string;
1110
1111
0
  if (!*ceil) {
1112
0
    *empty_entry_found = 1;
1113
0
    return 0;
1114
0
  } else if (!is_absolute_path(ceil)) {
1115
0
    return 0;
1116
0
  } else if (*empty_entry_found) {
1117
    /* Keep entry but do not canonicalize it */
1118
0
    return 1;
1119
0
  } else {
1120
0
    char *real_path = real_pathdup(ceil, 0);
1121
0
    if (!real_path) {
1122
0
      return 0;
1123
0
    }
1124
0
    free(item->string);
1125
0
    item->string = real_path;
1126
0
    return 1;
1127
0
  }
1128
0
}
1129
1130
struct safe_directory_data {
1131
  const char *path;
1132
  int is_safe;
1133
};
1134
1135
static int safe_directory_cb(const char *key, const char *value,
1136
           const struct config_context *ctx UNUSED, void *d)
1137
0
{
1138
0
  struct safe_directory_data *data = d;
1139
1140
0
  if (strcmp(key, "safe.directory"))
1141
0
    return 0;
1142
1143
0
  if (!value || !*value) {
1144
0
    data->is_safe = 0;
1145
0
  } else if (!strcmp(value, "*")) {
1146
0
    data->is_safe = 1;
1147
0
  } else {
1148
0
    const char *interpolated = NULL;
1149
1150
0
    if (!git_config_pathname(&interpolated, key, value) &&
1151
0
        !fspathcmp(data->path, interpolated ? interpolated : value))
1152
0
      data->is_safe = 1;
1153
1154
0
    free((char *)interpolated);
1155
0
  }
1156
1157
0
  return 0;
1158
0
}
1159
1160
/*
1161
 * Check if a repository is safe, by verifying the ownership of the
1162
 * worktree (if any), the git directory, and the gitfile (if any).
1163
 *
1164
 * Exemptions for known-safe repositories can be added via `safe.directory`
1165
 * config settings; for non-bare repositories, their worktree needs to be
1166
 * added, for bare ones their git directory.
1167
 */
1168
static int ensure_valid_ownership(const char *gitfile,
1169
          const char *worktree, const char *gitdir,
1170
          struct strbuf *report)
1171
0
{
1172
0
  struct safe_directory_data data = {
1173
0
    .path = worktree ? worktree : gitdir
1174
0
  };
1175
1176
0
  if (!git_env_bool("GIT_TEST_ASSUME_DIFFERENT_OWNER", 0) &&
1177
0
      (!gitfile || is_path_owned_by_current_user(gitfile, report)) &&
1178
0
      (!worktree || is_path_owned_by_current_user(worktree, report)) &&
1179
0
      (!gitdir || is_path_owned_by_current_user(gitdir, report)))
1180
0
    return 1;
1181
1182
  /*
1183
   * data.path is the "path" that identifies the repository and it is
1184
   * constant regardless of what failed above. data.is_safe should be
1185
   * initialized to false, and might be changed by the callback.
1186
   */
1187
0
  git_protected_config(safe_directory_cb, &data);
1188
1189
0
  return data.is_safe;
1190
0
}
1191
1192
static int allowed_bare_repo_cb(const char *key, const char *value,
1193
        const struct config_context *ctx UNUSED,
1194
        void *d)
1195
0
{
1196
0
  enum allowed_bare_repo *allowed_bare_repo = d;
1197
1198
0
  if (strcasecmp(key, "safe.bareRepository"))
1199
0
    return 0;
1200
1201
0
  if (!strcmp(value, "explicit")) {
1202
0
    *allowed_bare_repo = ALLOWED_BARE_REPO_EXPLICIT;
1203
0
    return 0;
1204
0
  }
1205
0
  if (!strcmp(value, "all")) {
1206
0
    *allowed_bare_repo = ALLOWED_BARE_REPO_ALL;
1207
0
    return 0;
1208
0
  }
1209
0
  return -1;
1210
0
}
1211
1212
static enum allowed_bare_repo get_allowed_bare_repo(void)
1213
0
{
1214
0
  enum allowed_bare_repo result = ALLOWED_BARE_REPO_ALL;
1215
0
  git_protected_config(allowed_bare_repo_cb, &result);
1216
0
  return result;
1217
0
}
1218
1219
static const char *allowed_bare_repo_to_string(
1220
  enum allowed_bare_repo allowed_bare_repo)
1221
0
{
1222
0
  switch (allowed_bare_repo) {
1223
0
  case ALLOWED_BARE_REPO_EXPLICIT:
1224
0
    return "explicit";
1225
0
  case ALLOWED_BARE_REPO_ALL:
1226
0
    return "all";
1227
0
  default:
1228
0
    BUG("invalid allowed_bare_repo %d",
1229
0
        allowed_bare_repo);
1230
0
  }
1231
0
  return NULL;
1232
0
}
1233
1234
/*
1235
 * We cannot decide in this function whether we are in the work tree or
1236
 * not, since the config can only be read _after_ this function was called.
1237
 *
1238
 * Also, we avoid changing any global state (such as the current working
1239
 * directory) to allow early callers.
1240
 *
1241
 * The directory where the search should start needs to be passed in via the
1242
 * `dir` parameter; upon return, the `dir` buffer will contain the path of
1243
 * the directory where the search ended, and `gitdir` will contain the path of
1244
 * the discovered .git/ directory, if any. If `gitdir` is not absolute, it
1245
 * is relative to `dir` (i.e. *not* necessarily the cwd).
1246
 */
1247
static enum discovery_result setup_git_directory_gently_1(struct strbuf *dir,
1248
                struct strbuf *gitdir,
1249
                struct strbuf *report,
1250
                int die_on_error)
1251
10.1k
{
1252
10.1k
  const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
1253
10.1k
  struct string_list ceiling_dirs = STRING_LIST_INIT_DUP;
1254
10.1k
  const char *gitdirenv;
1255
10.1k
  int ceil_offset = -1, min_offset = offset_1st_component(dir->buf);
1256
10.1k
  dev_t current_device = 0;
1257
10.1k
  int one_filesystem = 1;
1258
1259
  /*
1260
   * If GIT_DIR is set explicitly, we're not going
1261
   * to do any discovery, but we still do repository
1262
   * validation.
1263
   */
1264
10.1k
  gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
1265
10.1k
  if (gitdirenv) {
1266
10.1k
    strbuf_addstr(gitdir, gitdirenv);
1267
10.1k
    return GIT_DIR_EXPLICIT;
1268
10.1k
  }
1269
1270
0
  if (env_ceiling_dirs) {
1271
0
    int empty_entry_found = 0;
1272
1273
0
    string_list_split(&ceiling_dirs, env_ceiling_dirs, PATH_SEP, -1);
1274
0
    filter_string_list(&ceiling_dirs, 0,
1275
0
           canonicalize_ceiling_entry, &empty_entry_found);
1276
0
    ceil_offset = longest_ancestor_length(dir->buf, &ceiling_dirs);
1277
0
    string_list_clear(&ceiling_dirs, 0);
1278
0
  }
1279
1280
0
  if (ceil_offset < 0)
1281
0
    ceil_offset = min_offset - 2;
1282
1283
0
  if (min_offset && min_offset == dir->len &&
1284
0
      !is_dir_sep(dir->buf[min_offset - 1])) {
1285
0
    strbuf_addch(dir, '/');
1286
0
    min_offset++;
1287
0
  }
1288
1289
  /*
1290
   * Test in the following order (relative to the dir):
1291
   * - .git (file containing "gitdir: <path>")
1292
   * - .git/
1293
   * - ./ (bare)
1294
   * - ../.git
1295
   * - ../.git/
1296
   * - ../ (bare)
1297
   * - ../../.git
1298
   *   etc.
1299
   */
1300
0
  one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
1301
0
  if (one_filesystem)
1302
0
    current_device = get_device_or_die(dir->buf, NULL, 0);
1303
0
  for (;;) {
1304
0
    int offset = dir->len, error_code = 0;
1305
0
    char *gitdir_path = NULL;
1306
0
    char *gitfile = NULL;
1307
1308
0
    if (offset > min_offset)
1309
0
      strbuf_addch(dir, '/');
1310
0
    strbuf_addstr(dir, DEFAULT_GIT_DIR_ENVIRONMENT);
1311
0
    gitdirenv = read_gitfile_gently(dir->buf, die_on_error ?
1312
0
            NULL : &error_code);
1313
0
    if (!gitdirenv) {
1314
0
      if (die_on_error ||
1315
0
          error_code == READ_GITFILE_ERR_NOT_A_FILE) {
1316
        /* NEEDSWORK: fail if .git is not file nor dir */
1317
0
        if (is_git_directory(dir->buf)) {
1318
0
          gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT;
1319
0
          gitdir_path = xstrdup(dir->buf);
1320
0
        }
1321
0
      } else if (error_code != READ_GITFILE_ERR_STAT_FAILED)
1322
0
        return GIT_DIR_INVALID_GITFILE;
1323
0
    } else
1324
0
      gitfile = xstrdup(dir->buf);
1325
    /*
1326
     * Earlier, we tentatively added DEFAULT_GIT_DIR_ENVIRONMENT
1327
     * to check that directory for a repository.
1328
     * Now trim that tentative addition away, because we want to
1329
     * focus on the real directory we are in.
1330
     */
1331
0
    strbuf_setlen(dir, offset);
1332
0
    if (gitdirenv) {
1333
0
      enum discovery_result ret;
1334
0
      const char *gitdir_candidate =
1335
0
        gitdir_path ? gitdir_path : gitdirenv;
1336
1337
0
      if (ensure_valid_ownership(gitfile, dir->buf,
1338
0
               gitdir_candidate, report)) {
1339
0
        strbuf_addstr(gitdir, gitdirenv);
1340
0
        ret = GIT_DIR_DISCOVERED;
1341
0
      } else
1342
0
        ret = GIT_DIR_INVALID_OWNERSHIP;
1343
1344
      /*
1345
       * Earlier, during discovery, we might have allocated
1346
       * string copies for gitdir_path or gitfile so make
1347
       * sure we don't leak by freeing them now, before
1348
       * leaving the loop and function.
1349
       *
1350
       * Note: gitdirenv will be non-NULL whenever these are
1351
       * allocated, therefore we need not take care of releasing
1352
       * them outside of this conditional block.
1353
       */
1354
0
      free(gitdir_path);
1355
0
      free(gitfile);
1356
1357
0
      return ret;
1358
0
    }
1359
1360
0
    if (is_git_directory(dir->buf)) {
1361
0
      trace2_data_string("setup", NULL, "implicit-bare-repository", dir->buf);
1362
0
      if (get_allowed_bare_repo() == ALLOWED_BARE_REPO_EXPLICIT)
1363
0
        return GIT_DIR_DISALLOWED_BARE;
1364
0
      if (!ensure_valid_ownership(NULL, NULL, dir->buf, report))
1365
0
        return GIT_DIR_INVALID_OWNERSHIP;
1366
0
      strbuf_addstr(gitdir, ".");
1367
0
      return GIT_DIR_BARE;
1368
0
    }
1369
1370
0
    if (offset <= min_offset)
1371
0
      return GIT_DIR_HIT_CEILING;
1372
1373
0
    while (--offset > ceil_offset && !is_dir_sep(dir->buf[offset]))
1374
0
      ; /* continue */
1375
0
    if (offset <= ceil_offset)
1376
0
      return GIT_DIR_HIT_CEILING;
1377
1378
0
    strbuf_setlen(dir, offset > min_offset ?  offset : min_offset);
1379
0
    if (one_filesystem &&
1380
0
        current_device != get_device_or_die(dir->buf, NULL, offset))
1381
0
      return GIT_DIR_HIT_MOUNT_POINT;
1382
0
  }
1383
0
}
1384
1385
enum discovery_result discover_git_directory_reason(struct strbuf *commondir,
1386
                struct strbuf *gitdir)
1387
0
{
1388
0
  struct strbuf dir = STRBUF_INIT, err = STRBUF_INIT;
1389
0
  size_t gitdir_offset = gitdir->len, cwd_len;
1390
0
  size_t commondir_offset = commondir->len;
1391
0
  struct repository_format candidate = REPOSITORY_FORMAT_INIT;
1392
0
  enum discovery_result result;
1393
1394
0
  if (strbuf_getcwd(&dir))
1395
0
    return GIT_DIR_CWD_FAILURE;
1396
1397
0
  cwd_len = dir.len;
1398
0
  result = setup_git_directory_gently_1(&dir, gitdir, NULL, 0);
1399
0
  if (result <= 0) {
1400
0
    strbuf_release(&dir);
1401
0
    return result;
1402
0
  }
1403
1404
  /*
1405
   * The returned gitdir is relative to dir, and if dir does not reflect
1406
   * the current working directory, we simply make the gitdir absolute.
1407
   */
1408
0
  if (dir.len < cwd_len && !is_absolute_path(gitdir->buf + gitdir_offset)) {
1409
    /* Avoid a trailing "/." */
1410
0
    if (!strcmp(".", gitdir->buf + gitdir_offset))
1411
0
      strbuf_setlen(gitdir, gitdir_offset);
1412
0
    else
1413
0
      strbuf_addch(&dir, '/');
1414
0
    strbuf_insert(gitdir, gitdir_offset, dir.buf, dir.len);
1415
0
  }
1416
1417
0
  get_common_dir(commondir, gitdir->buf + gitdir_offset);
1418
1419
0
  strbuf_reset(&dir);
1420
0
  strbuf_addf(&dir, "%s/config", commondir->buf + commondir_offset);
1421
0
  read_repository_format(&candidate, dir.buf);
1422
0
  strbuf_release(&dir);
1423
1424
0
  if (verify_repository_format(&candidate, &err) < 0) {
1425
0
    warning("ignoring git dir '%s': %s",
1426
0
      gitdir->buf + gitdir_offset, err.buf);
1427
0
    strbuf_release(&err);
1428
0
    strbuf_setlen(commondir, commondir_offset);
1429
0
    strbuf_setlen(gitdir, gitdir_offset);
1430
0
    clear_repository_format(&candidate);
1431
0
    return GIT_DIR_INVALID_FORMAT;
1432
0
  }
1433
1434
0
  clear_repository_format(&candidate);
1435
0
  return result;
1436
0
}
1437
1438
const char *setup_git_directory_gently(int *nongit_ok)
1439
10.1k
{
1440
10.1k
  static struct strbuf cwd = STRBUF_INIT;
1441
10.1k
  struct strbuf dir = STRBUF_INIT, gitdir = STRBUF_INIT, report = STRBUF_INIT;
1442
10.1k
  const char *prefix = NULL;
1443
10.1k
  struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1444
1445
  /*
1446
   * We may have read an incomplete configuration before
1447
   * setting-up the git directory. If so, clear the cache so
1448
   * that the next queries to the configuration reload complete
1449
   * configuration (including the per-repo config file that we
1450
   * ignored previously).
1451
   */
1452
10.1k
  git_config_clear();
1453
1454
  /*
1455
   * Let's assume that we are in a git repository.
1456
   * If it turns out later that we are somewhere else, the value will be
1457
   * updated accordingly.
1458
   */
1459
10.1k
  if (nongit_ok)
1460
10.1k
    *nongit_ok = 0;
1461
1462
10.1k
  if (strbuf_getcwd(&cwd))
1463
0
    die_errno(_("Unable to read current working directory"));
1464
10.1k
  strbuf_addbuf(&dir, &cwd);
1465
1466
10.1k
  switch (setup_git_directory_gently_1(&dir, &gitdir, &report, 1)) {
1467
10.1k
  case GIT_DIR_EXPLICIT:
1468
10.1k
    prefix = setup_explicit_git_dir(gitdir.buf, &cwd, &repo_fmt, nongit_ok);
1469
10.1k
    break;
1470
0
  case GIT_DIR_DISCOVERED:
1471
0
    if (dir.len < cwd.len && chdir(dir.buf))
1472
0
      die(_("cannot change to '%s'"), dir.buf);
1473
0
    prefix = setup_discovered_git_dir(gitdir.buf, &cwd, dir.len,
1474
0
              &repo_fmt, nongit_ok);
1475
0
    break;
1476
0
  case GIT_DIR_BARE:
1477
0
    if (dir.len < cwd.len && chdir(dir.buf))
1478
0
      die(_("cannot change to '%s'"), dir.buf);
1479
0
    prefix = setup_bare_git_dir(&cwd, dir.len, &repo_fmt, nongit_ok);
1480
0
    break;
1481
0
  case GIT_DIR_HIT_CEILING:
1482
0
    if (!nongit_ok)
1483
0
      die(_("not a git repository (or any of the parent directories): %s"),
1484
0
          DEFAULT_GIT_DIR_ENVIRONMENT);
1485
0
    *nongit_ok = 1;
1486
0
    break;
1487
0
  case GIT_DIR_HIT_MOUNT_POINT:
1488
0
    if (!nongit_ok)
1489
0
      die(_("not a git repository (or any parent up to mount point %s)\n"
1490
0
            "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."),
1491
0
          dir.buf);
1492
0
    *nongit_ok = 1;
1493
0
    break;
1494
0
  case GIT_DIR_INVALID_OWNERSHIP:
1495
0
    if (!nongit_ok) {
1496
0
      struct strbuf quoted = STRBUF_INIT;
1497
1498
0
      strbuf_complete(&report, '\n');
1499
0
      sq_quote_buf_pretty(&quoted, dir.buf);
1500
0
      die(_("detected dubious ownership in repository at '%s'\n"
1501
0
            "%s"
1502
0
            "To add an exception for this directory, call:\n"
1503
0
            "\n"
1504
0
            "\tgit config --global --add safe.directory %s"),
1505
0
          dir.buf, report.buf, quoted.buf);
1506
0
    }
1507
0
    *nongit_ok = 1;
1508
0
    break;
1509
0
  case GIT_DIR_DISALLOWED_BARE:
1510
0
    if (!nongit_ok) {
1511
0
      die(_("cannot use bare repository '%s' (safe.bareRepository is '%s')"),
1512
0
          dir.buf,
1513
0
          allowed_bare_repo_to_string(get_allowed_bare_repo()));
1514
0
    }
1515
0
    *nongit_ok = 1;
1516
0
    break;
1517
0
  case GIT_DIR_CWD_FAILURE:
1518
0
  case GIT_DIR_INVALID_FORMAT:
1519
    /*
1520
     * As a safeguard against setup_git_directory_gently_1 returning
1521
     * these values, fallthrough to BUG. Otherwise it is possible to
1522
     * set startup_info->have_repository to 1 when we did nothing to
1523
     * find a repository.
1524
     */
1525
0
  default:
1526
0
    BUG("unhandled setup_git_directory_gently_1() result");
1527
10.1k
  }
1528
1529
  /*
1530
   * At this point, nongit_ok is stable. If it is non-NULL and points
1531
   * to a non-zero value, then this means that we haven't found a
1532
   * repository and that the caller expects startup_info to reflect
1533
   * this.
1534
   *
1535
   * Regardless of the state of nongit_ok, startup_info->prefix and
1536
   * the GIT_PREFIX environment variable must always match. For details
1537
   * see Documentation/config/alias.txt.
1538
   */
1539
10.1k
  if (nongit_ok && *nongit_ok)
1540
0
    startup_info->have_repository = 0;
1541
10.1k
  else
1542
10.1k
    startup_info->have_repository = 1;
1543
1544
  /*
1545
   * Not all paths through the setup code will call 'set_git_dir()' (which
1546
   * directly sets up the environment) so in order to guarantee that the
1547
   * environment is in a consistent state after setup, explicitly setup
1548
   * the environment if we have a repository.
1549
   *
1550
   * NEEDSWORK: currently we allow bogus GIT_DIR values to be set in some
1551
   * code paths so we also need to explicitly setup the environment if
1552
   * the user has set GIT_DIR.  It may be beneficial to disallow bogus
1553
   * GIT_DIR values at some point in the future.
1554
   */
1555
10.1k
  if (/* GIT_DIR_EXPLICIT, GIT_DIR_DISCOVERED, GIT_DIR_BARE */
1556
10.1k
      startup_info->have_repository ||
1557
      /* GIT_DIR_EXPLICIT */
1558
10.1k
      getenv(GIT_DIR_ENVIRONMENT)) {
1559
10.1k
    if (!the_repository->gitdir) {
1560
0
      const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
1561
0
      if (!gitdir)
1562
0
        gitdir = DEFAULT_GIT_DIR_ENVIRONMENT;
1563
0
      setup_git_env(gitdir);
1564
0
    }
1565
10.1k
    if (startup_info->have_repository) {
1566
10.1k
      repo_set_hash_algo(the_repository, repo_fmt.hash_algo);
1567
10.1k
      the_repository->repository_format_worktree_config =
1568
10.1k
        repo_fmt.worktree_config;
1569
      /* take ownership of repo_fmt.partial_clone */
1570
10.1k
      the_repository->repository_format_partial_clone =
1571
10.1k
        repo_fmt.partial_clone;
1572
10.1k
      repo_fmt.partial_clone = NULL;
1573
10.1k
    }
1574
10.1k
  }
1575
  /*
1576
   * Since precompose_string_if_needed() needs to look at
1577
   * the core.precomposeunicode configuration, this
1578
   * has to happen after the above block that finds
1579
   * out where the repository is, i.e. a preparation
1580
   * for calling git_config_get_bool().
1581
   */
1582
10.1k
  if (prefix) {
1583
0
    prefix = precompose_string_if_needed(prefix);
1584
0
    startup_info->prefix = prefix;
1585
0
    setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);
1586
10.1k
  } else {
1587
10.1k
    startup_info->prefix = NULL;
1588
10.1k
    setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
1589
10.1k
  }
1590
1591
10.1k
  setup_original_cwd();
1592
1593
10.1k
  strbuf_release(&dir);
1594
10.1k
  strbuf_release(&gitdir);
1595
10.1k
  strbuf_release(&report);
1596
10.1k
  clear_repository_format(&repo_fmt);
1597
1598
10.1k
  return prefix;
1599
10.1k
}
1600
1601
int git_config_perm(const char *var, const char *value)
1602
0
{
1603
0
  int i;
1604
0
  char *endptr;
1605
1606
0
  if (!value)
1607
0
    return PERM_GROUP;
1608
1609
0
  if (!strcmp(value, "umask"))
1610
0
    return PERM_UMASK;
1611
0
  if (!strcmp(value, "group"))
1612
0
    return PERM_GROUP;
1613
0
  if (!strcmp(value, "all") ||
1614
0
      !strcmp(value, "world") ||
1615
0
      !strcmp(value, "everybody"))
1616
0
    return PERM_EVERYBODY;
1617
1618
  /* Parse octal numbers */
1619
0
  i = strtol(value, &endptr, 8);
1620
1621
  /* If not an octal number, maybe true/false? */
1622
0
  if (*endptr != 0)
1623
0
    return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
1624
1625
  /*
1626
   * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
1627
   * a chmod value to restrict to.
1628
   */
1629
0
  switch (i) {
1630
0
  case PERM_UMASK:               /* 0 */
1631
0
    return PERM_UMASK;
1632
0
  case OLD_PERM_GROUP:           /* 1 */
1633
0
    return PERM_GROUP;
1634
0
  case OLD_PERM_EVERYBODY:       /* 2 */
1635
0
    return PERM_EVERYBODY;
1636
0
  }
1637
1638
  /* A filemode value was given: 0xxx */
1639
1640
0
  if ((i & 0600) != 0600)
1641
0
    die(_("problem with core.sharedRepository filemode value "
1642
0
        "(0%.3o).\nThe owner of files must always have "
1643
0
        "read and write permissions."), i);
1644
1645
  /*
1646
   * Mask filemode value. Others can not get write permission.
1647
   * x flags for directories are handled separately.
1648
   */
1649
0
  return -(i & 0666);
1650
0
}
1651
1652
void check_repository_format(struct repository_format *fmt)
1653
1.22k
{
1654
1.22k
  struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1655
1.22k
  if (!fmt)
1656
0
    fmt = &repo_fmt;
1657
1.22k
  check_repository_format_gently(get_git_dir(), fmt, NULL);
1658
1.22k
  startup_info->have_repository = 1;
1659
1.22k
  repo_set_hash_algo(the_repository, fmt->hash_algo);
1660
1.22k
  the_repository->repository_format_worktree_config =
1661
1.22k
    fmt->worktree_config;
1662
1.22k
  the_repository->repository_format_partial_clone =
1663
1.22k
    xstrdup_or_null(fmt->partial_clone);
1664
1.22k
  clear_repository_format(&repo_fmt);
1665
1.22k
}
1666
1667
/*
1668
 * Returns the "prefix", a path to the current working directory
1669
 * relative to the work tree root, or NULL, if the current working
1670
 * directory is not a strict subdirectory of the work tree root. The
1671
 * prefix always ends with a '/' character.
1672
 */
1673
const char *setup_git_directory(void)
1674
0
{
1675
0
  return setup_git_directory_gently(NULL);
1676
0
}
1677
1678
const char *resolve_gitdir_gently(const char *suspect, int *return_error_code)
1679
0
{
1680
0
  if (is_git_directory(suspect))
1681
0
    return suspect;
1682
0
  return read_gitfile_gently(suspect, return_error_code);
1683
0
}
1684
1685
/* if any standard file descriptor is missing open it to /dev/null */
1686
void sanitize_stdfds(void)
1687
0
{
1688
0
  int fd = xopen("/dev/null", O_RDWR);
1689
0
  while (fd < 2)
1690
0
    fd = xdup(fd);
1691
0
  if (fd > 2)
1692
0
    close(fd);
1693
0
}
1694
1695
int daemonize(void)
1696
0
{
1697
#ifdef NO_POSIX_GOODIES
1698
  errno = ENOSYS;
1699
  return -1;
1700
#else
1701
0
  switch (fork()) {
1702
0
    case 0:
1703
0
      break;
1704
0
    case -1:
1705
0
      die_errno(_("fork failed"));
1706
0
    default:
1707
0
      exit(0);
1708
0
  }
1709
0
  if (setsid() == -1)
1710
0
    die_errno(_("setsid failed"));
1711
0
  close(0);
1712
0
  close(1);
1713
0
  close(2);
1714
0
  sanitize_stdfds();
1715
0
  return 0;
1716
0
#endif
1717
0
}
1718
1719
#ifdef NO_TRUSTABLE_FILEMODE
1720
#define TEST_FILEMODE 0
1721
#else
1722
3.66k
#define TEST_FILEMODE 1
1723
#endif
1724
1725
1.22k
#define GIT_DEFAULT_HASH_ENVIRONMENT "GIT_DEFAULT_HASH"
1726
1727
static void copy_templates_1(struct strbuf *path, struct strbuf *template_path,
1728
           DIR *dir)
1729
1.22k
{
1730
1.22k
  size_t path_baselen = path->len;
1731
1.22k
  size_t template_baselen = template_path->len;
1732
1.22k
  struct dirent *de;
1733
1734
  /* Note: if ".git/hooks" file exists in the repository being
1735
   * re-initialized, /etc/core-git/templates/hooks/update would
1736
   * cause "git init" to fail here.  I think this is sane but
1737
   * it means that the set of templates we ship by default, along
1738
   * with the way the namespace under .git/ is organized, should
1739
   * be really carefully chosen.
1740
   */
1741
1.22k
  safe_create_dir(path->buf, 1);
1742
3.66k
  while ((de = readdir(dir)) != NULL) {
1743
2.44k
    struct stat st_git, st_template;
1744
2.44k
    int exists = 0;
1745
1746
2.44k
    strbuf_setlen(path, path_baselen);
1747
2.44k
    strbuf_setlen(template_path, template_baselen);
1748
1749
2.44k
    if (de->d_name[0] == '.')
1750
2.44k
      continue;
1751
0
    strbuf_addstr(path, de->d_name);
1752
0
    strbuf_addstr(template_path, de->d_name);
1753
0
    if (lstat(path->buf, &st_git)) {
1754
0
      if (errno != ENOENT)
1755
0
        die_errno(_("cannot stat '%s'"), path->buf);
1756
0
    }
1757
0
    else
1758
0
      exists = 1;
1759
1760
0
    if (lstat(template_path->buf, &st_template))
1761
0
      die_errno(_("cannot stat template '%s'"), template_path->buf);
1762
1763
0
    if (S_ISDIR(st_template.st_mode)) {
1764
0
      DIR *subdir = opendir(template_path->buf);
1765
0
      if (!subdir)
1766
0
        die_errno(_("cannot opendir '%s'"), template_path->buf);
1767
0
      strbuf_addch(path, '/');
1768
0
      strbuf_addch(template_path, '/');
1769
0
      copy_templates_1(path, template_path, subdir);
1770
0
      closedir(subdir);
1771
0
    }
1772
0
    else if (exists)
1773
0
      continue;
1774
0
    else if (S_ISLNK(st_template.st_mode)) {
1775
0
      struct strbuf lnk = STRBUF_INIT;
1776
0
      if (strbuf_readlink(&lnk, template_path->buf,
1777
0
              st_template.st_size) < 0)
1778
0
        die_errno(_("cannot readlink '%s'"), template_path->buf);
1779
0
      if (symlink(lnk.buf, path->buf))
1780
0
        die_errno(_("cannot symlink '%s' '%s'"),
1781
0
            lnk.buf, path->buf);
1782
0
      strbuf_release(&lnk);
1783
0
    }
1784
0
    else if (S_ISREG(st_template.st_mode)) {
1785
0
      if (copy_file(path->buf, template_path->buf, st_template.st_mode))
1786
0
        die_errno(_("cannot copy '%s' to '%s'"),
1787
0
            template_path->buf, path->buf);
1788
0
    }
1789
0
    else
1790
0
      error(_("ignoring template %s"), template_path->buf);
1791
0
  }
1792
1.22k
}
1793
1794
static void copy_templates(const char *template_dir, const char *init_template_dir)
1795
1.22k
{
1796
1.22k
  struct strbuf path = STRBUF_INIT;
1797
1.22k
  struct strbuf template_path = STRBUF_INIT;
1798
1.22k
  size_t template_len;
1799
1.22k
  struct repository_format template_format = REPOSITORY_FORMAT_INIT;
1800
1.22k
  struct strbuf err = STRBUF_INIT;
1801
1.22k
  DIR *dir;
1802
1.22k
  char *to_free = NULL;
1803
1804
1.22k
  if (!template_dir)
1805
1.22k
    template_dir = getenv(TEMPLATE_DIR_ENVIRONMENT);
1806
1.22k
  if (!template_dir)
1807
0
    template_dir = init_template_dir;
1808
1.22k
  if (!template_dir)
1809
0
    template_dir = to_free = system_path(DEFAULT_GIT_TEMPLATE_DIR);
1810
1.22k
  if (!template_dir[0]) {
1811
0
    free(to_free);
1812
0
    return;
1813
0
  }
1814
1815
1.22k
  strbuf_addstr(&template_path, template_dir);
1816
1.22k
  strbuf_complete(&template_path, '/');
1817
1.22k
  template_len = template_path.len;
1818
1819
1.22k
  dir = opendir(template_path.buf);
1820
1.22k
  if (!dir) {
1821
0
    warning(_("templates not found in %s"), template_dir);
1822
0
    goto free_return;
1823
0
  }
1824
1825
  /* Make sure that template is from the correct vintage */
1826
1.22k
  strbuf_addstr(&template_path, "config");
1827
1.22k
  read_repository_format(&template_format, template_path.buf);
1828
1.22k
  strbuf_setlen(&template_path, template_len);
1829
1830
  /*
1831
   * No mention of version at all is OK, but anything else should be
1832
   * verified.
1833
   */
1834
1.22k
  if (template_format.version >= 0 &&
1835
1.22k
      verify_repository_format(&template_format, &err) < 0) {
1836
0
    warning(_("not copying templates from '%s': %s"),
1837
0
        template_dir, err.buf);
1838
0
    strbuf_release(&err);
1839
0
    goto close_free_return;
1840
0
  }
1841
1842
1.22k
  strbuf_addstr(&path, get_git_common_dir());
1843
1.22k
  strbuf_complete(&path, '/');
1844
1.22k
  copy_templates_1(&path, &template_path, dir);
1845
1.22k
close_free_return:
1846
1.22k
  closedir(dir);
1847
1.22k
free_return:
1848
1.22k
  free(to_free);
1849
1.22k
  strbuf_release(&path);
1850
1.22k
  strbuf_release(&template_path);
1851
1.22k
  clear_repository_format(&template_format);
1852
1.22k
}
1853
1854
/*
1855
 * If the git_dir is not directly inside the working tree, then git will not
1856
 * find it by default, and we need to set the worktree explicitly.
1857
 */
1858
static int needs_work_tree_config(const char *git_dir, const char *work_tree)
1859
1.22k
{
1860
1.22k
  if (!strcmp(work_tree, "/") && !strcmp(git_dir, "/.git"))
1861
0
    return 0;
1862
1.22k
  if (skip_prefix(git_dir, work_tree, &git_dir) &&
1863
1.22k
      !strcmp(git_dir, "/.git"))
1864
1.22k
    return 0;
1865
0
  return 1;
1866
1.22k
}
1867
1868
void initialize_repository_version(int hash_algo, int reinit)
1869
1.22k
{
1870
1.22k
  char repo_version_string[10];
1871
1.22k
  int repo_version = GIT_REPO_VERSION;
1872
1873
1.22k
  if (hash_algo != GIT_HASH_SHA1)
1874
0
    repo_version = GIT_REPO_VERSION_READ;
1875
1876
  /* This forces creation of new config file */
1877
1.22k
  xsnprintf(repo_version_string, sizeof(repo_version_string),
1878
1.22k
      "%d", repo_version);
1879
1.22k
  git_config_set("core.repositoryformatversion", repo_version_string);
1880
1881
1.22k
  if (hash_algo != GIT_HASH_SHA1)
1882
0
    git_config_set("extensions.objectformat",
1883
0
             hash_algos[hash_algo].name);
1884
1.22k
  else if (reinit)
1885
0
    git_config_set_gently("extensions.objectformat", NULL);
1886
1.22k
}
1887
1888
static int create_default_files(const char *template_path,
1889
        const char *original_git_dir,
1890
        const char *initial_branch,
1891
        const struct repository_format *fmt,
1892
        int prev_bare_repository,
1893
        int init_shared_repository,
1894
        int quiet)
1895
1.22k
{
1896
1.22k
  struct stat st1;
1897
1.22k
  struct strbuf buf = STRBUF_INIT;
1898
1.22k
  char *path;
1899
1.22k
  char junk[2];
1900
1.22k
  int reinit;
1901
1.22k
  int filemode;
1902
1.22k
  struct strbuf err = STRBUF_INIT;
1903
1.22k
  const char *init_template_dir = NULL;
1904
1.22k
  const char *work_tree = get_git_work_tree();
1905
1906
  /*
1907
   * First copy the templates -- we might have the default
1908
   * config file there, in which case we would want to read
1909
   * from it after installing.
1910
   *
1911
   * Before reading that config, we also need to clear out any cached
1912
   * values (since we've just potentially changed what's available on
1913
   * disk).
1914
   */
1915
1.22k
  git_config_get_pathname("init.templatedir", &init_template_dir);
1916
1.22k
  copy_templates(template_path, init_template_dir);
1917
1.22k
  free((char *)init_template_dir);
1918
1.22k
  git_config_clear();
1919
1.22k
  reset_shared_repository();
1920
1.22k
  git_config(git_default_config, NULL);
1921
1922
  /*
1923
   * We must make sure command-line options continue to override any
1924
   * values we might have just re-read from the config.
1925
   */
1926
1.22k
  if (init_shared_repository != -1)
1927
0
    set_shared_repository(init_shared_repository);
1928
  /*
1929
   * TODO: heed core.bare from config file in templates if no
1930
   *       command-line override given
1931
   */
1932
1.22k
  is_bare_repository_cfg = prev_bare_repository || !work_tree;
1933
  /* TODO (continued):
1934
   *
1935
   * Unfortunately, the line above is equivalent to
1936
   *    is_bare_repository_cfg = !work_tree;
1937
   * which ignores the config entirely even if no `--[no-]bare`
1938
   * command line option was present.
1939
   *
1940
   * To see why, note that before this function, there was this call:
1941
   *    prev_bare_repository = is_bare_repository()
1942
   * expanding the right hand side:
1943
   *                 = is_bare_repository_cfg && !get_git_work_tree()
1944
   *                 = is_bare_repository_cfg && !work_tree
1945
   * note that the last simplification above is valid because nothing
1946
   * calls repo_init() or set_git_work_tree() between any of the
1947
   * relevant calls in the code, and thus the !get_git_work_tree()
1948
   * calls will return the same result each time.  So, what we are
1949
   * interested in computing is the right hand side of the line of
1950
   * code just above this comment:
1951
   *     prev_bare_repository || !work_tree
1952
   *        = is_bare_repository_cfg && !work_tree || !work_tree
1953
   *        = !work_tree
1954
   * because "A && !B || !B == !B" for all boolean values of A & B.
1955
   */
1956
1957
  /*
1958
   * We would have created the above under user's umask -- under
1959
   * shared-repository settings, we would need to fix them up.
1960
   */
1961
1.22k
  if (get_shared_repository()) {
1962
0
    adjust_shared_perm(get_git_dir());
1963
0
  }
1964
1965
  /*
1966
   * We need to create a "refs" dir in any case so that older
1967
   * versions of git can tell that this is a repository.
1968
   */
1969
1.22k
  safe_create_dir(git_path("refs"), 1);
1970
1.22k
  adjust_shared_perm(git_path("refs"));
1971
1972
1.22k
  if (refs_init_db(&err))
1973
0
    die("failed to set up refs db: %s", err.buf);
1974
1975
  /*
1976
   * Point the HEAD symref to the initial branch with if HEAD does
1977
   * not yet exist.
1978
   */
1979
1.22k
  path = git_path_buf(&buf, "HEAD");
1980
1.22k
  reinit = (!access(path, R_OK)
1981
1.22k
      || readlink(path, junk, sizeof(junk)-1) != -1);
1982
1.22k
  if (!reinit) {
1983
1.22k
    char *ref;
1984
1985
1.22k
    if (!initial_branch)
1986
1.22k
      initial_branch = git_default_branch_name(quiet);
1987
1988
1.22k
    ref = xstrfmt("refs/heads/%s", initial_branch);
1989
1.22k
    if (check_refname_format(ref, 0) < 0)
1990
0
      die(_("invalid initial branch name: '%s'"),
1991
0
          initial_branch);
1992
1993
1.22k
    if (create_symref("HEAD", ref, NULL) < 0)
1994
0
      exit(1);
1995
1.22k
    free(ref);
1996
1.22k
  }
1997
1998
1.22k
  initialize_repository_version(fmt->hash_algo, 0);
1999
2000
  /* Check filemode trustability */
2001
1.22k
  path = git_path_buf(&buf, "config");
2002
1.22k
  filemode = TEST_FILEMODE;
2003
1.22k
  if (TEST_FILEMODE && !lstat(path, &st1)) {
2004
1.22k
    struct stat st2;
2005
1.22k
    filemode = (!chmod(path, st1.st_mode ^ S_IXUSR) &&
2006
1.22k
        !lstat(path, &st2) &&
2007
1.22k
        st1.st_mode != st2.st_mode &&
2008
1.22k
        !chmod(path, st1.st_mode));
2009
1.22k
    if (filemode && !reinit && (st1.st_mode & S_IXUSR))
2010
0
      filemode = 0;
2011
1.22k
  }
2012
1.22k
  git_config_set("core.filemode", filemode ? "true" : "false");
2013
2014
1.22k
  if (is_bare_repository())
2015
0
    git_config_set("core.bare", "true");
2016
1.22k
  else {
2017
1.22k
    git_config_set("core.bare", "false");
2018
    /* allow template config file to override the default */
2019
1.22k
    if (log_all_ref_updates == LOG_REFS_UNSET)
2020
1
      git_config_set("core.logallrefupdates", "true");
2021
1.22k
    if (needs_work_tree_config(original_git_dir, work_tree))
2022
0
      git_config_set("core.worktree", work_tree);
2023
1.22k
  }
2024
2025
1.22k
  if (!reinit) {
2026
    /* Check if symlink is supported in the work tree */
2027
1.22k
    path = git_path_buf(&buf, "tXXXXXX");
2028
1.22k
    if (!close(xmkstemp(path)) &&
2029
1.22k
        !unlink(path) &&
2030
1.22k
        !symlink("testing", path) &&
2031
1.22k
        !lstat(path, &st1) &&
2032
1.22k
        S_ISLNK(st1.st_mode))
2033
1.22k
      unlink(path); /* good */
2034
0
    else
2035
0
      git_config_set("core.symlinks", "false");
2036
2037
    /* Check if the filesystem is case-insensitive */
2038
1.22k
    path = git_path_buf(&buf, "CoNfIg");
2039
1.22k
    if (!access(path, F_OK))
2040
0
      git_config_set("core.ignorecase", "true");
2041
1.22k
    probe_utf8_pathname_composition();
2042
1.22k
  }
2043
2044
1.22k
  strbuf_release(&buf);
2045
1.22k
  return reinit;
2046
1.22k
}
2047
2048
static void create_object_directory(void)
2049
1.22k
{
2050
1.22k
  struct strbuf path = STRBUF_INIT;
2051
1.22k
  size_t baselen;
2052
2053
1.22k
  strbuf_addstr(&path, get_object_directory());
2054
1.22k
  baselen = path.len;
2055
2056
1.22k
  safe_create_dir(path.buf, 1);
2057
2058
1.22k
  strbuf_setlen(&path, baselen);
2059
1.22k
  strbuf_addstr(&path, "/pack");
2060
1.22k
  safe_create_dir(path.buf, 1);
2061
2062
1.22k
  strbuf_setlen(&path, baselen);
2063
1.22k
  strbuf_addstr(&path, "/info");
2064
1.22k
  safe_create_dir(path.buf, 1);
2065
2066
1.22k
  strbuf_release(&path);
2067
1.22k
}
2068
2069
static void separate_git_dir(const char *git_dir, const char *git_link)
2070
0
{
2071
0
  struct stat st;
2072
2073
0
  if (!stat(git_link, &st)) {
2074
0
    const char *src;
2075
2076
0
    if (S_ISREG(st.st_mode))
2077
0
      src = read_gitfile(git_link);
2078
0
    else if (S_ISDIR(st.st_mode))
2079
0
      src = git_link;
2080
0
    else
2081
0
      die(_("unable to handle file type %d"), (int)st.st_mode);
2082
2083
0
    if (rename(src, git_dir))
2084
0
      die_errno(_("unable to move %s to %s"), src, git_dir);
2085
0
    repair_worktrees(NULL, NULL);
2086
0
  }
2087
2088
0
  write_file(git_link, "gitdir: %s", git_dir);
2089
0
}
2090
2091
static void validate_hash_algorithm(struct repository_format *repo_fmt, int hash)
2092
1.22k
{
2093
1.22k
  const char *env = getenv(GIT_DEFAULT_HASH_ENVIRONMENT);
2094
  /*
2095
   * If we already have an initialized repo, don't allow the user to
2096
   * specify a different algorithm, as that could cause corruption.
2097
   * Otherwise, if the user has specified one on the command line, use it.
2098
   */
2099
1.22k
  if (repo_fmt->version >= 0 && hash != GIT_HASH_UNKNOWN && hash != repo_fmt->hash_algo)
2100
0
    die(_("attempt to reinitialize repository with different hash"));
2101
1.22k
  else if (hash != GIT_HASH_UNKNOWN)
2102
0
    repo_fmt->hash_algo = hash;
2103
1.22k
  else if (env) {
2104
0
    int env_algo = hash_algo_by_name(env);
2105
0
    if (env_algo == GIT_HASH_UNKNOWN)
2106
0
      die(_("unknown hash algorithm '%s'"), env);
2107
0
    repo_fmt->hash_algo = env_algo;
2108
0
  }
2109
1.22k
}
2110
2111
int init_db(const char *git_dir, const char *real_git_dir,
2112
      const char *template_dir, int hash, const char *initial_branch,
2113
      int init_shared_repository, unsigned int flags)
2114
1.22k
{
2115
1.22k
  int reinit;
2116
1.22k
  int exist_ok = flags & INIT_DB_EXIST_OK;
2117
1.22k
  char *original_git_dir = real_pathdup(git_dir, 1);
2118
1.22k
  struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
2119
1.22k
  int prev_bare_repository;
2120
2121
1.22k
  if (real_git_dir) {
2122
0
    struct stat st;
2123
2124
0
    if (!exist_ok && !stat(git_dir, &st))
2125
0
      die(_("%s already exists"), git_dir);
2126
2127
0
    if (!exist_ok && !stat(real_git_dir, &st))
2128
0
      die(_("%s already exists"), real_git_dir);
2129
2130
0
    set_git_dir(real_git_dir, 1);
2131
0
    git_dir = get_git_dir();
2132
0
    separate_git_dir(git_dir, original_git_dir);
2133
0
  }
2134
1.22k
  else {
2135
1.22k
    set_git_dir(git_dir, 1);
2136
1.22k
    git_dir = get_git_dir();
2137
1.22k
  }
2138
1.22k
  startup_info->have_repository = 1;
2139
2140
  /* Ensure `core.hidedotfiles` is processed */
2141
1.22k
  git_config(platform_core_config, NULL);
2142
2143
1.22k
  safe_create_dir(git_dir, 0);
2144
2145
1.22k
  prev_bare_repository = is_bare_repository();
2146
2147
  /* Check to see if the repository version is right.
2148
   * Note that a newly created repository does not have
2149
   * config file, so this will not fail.  What we are catching
2150
   * is an attempt to reinitialize new repository with an old tool.
2151
   */
2152
1.22k
  check_repository_format(&repo_fmt);
2153
2154
1.22k
  validate_hash_algorithm(&repo_fmt, hash);
2155
2156
1.22k
  reinit = create_default_files(template_dir, original_git_dir,
2157
1.22k
              initial_branch, &repo_fmt,
2158
1.22k
              prev_bare_repository,
2159
1.22k
              init_shared_repository,
2160
1.22k
              flags & INIT_DB_QUIET);
2161
1.22k
  if (reinit && initial_branch)
2162
0
    warning(_("re-init: ignored --initial-branch=%s"),
2163
0
      initial_branch);
2164
2165
1.22k
  create_object_directory();
2166
2167
1.22k
  if (get_shared_repository()) {
2168
0
    char buf[10];
2169
    /* We do not spell "group" and such, so that
2170
     * the configuration can be read by older version
2171
     * of git. Note, we use octal numbers for new share modes,
2172
     * and compatibility values for PERM_GROUP and
2173
     * PERM_EVERYBODY.
2174
     */
2175
0
    if (get_shared_repository() < 0)
2176
      /* force to the mode value */
2177
0
      xsnprintf(buf, sizeof(buf), "0%o", -get_shared_repository());
2178
0
    else if (get_shared_repository() == PERM_GROUP)
2179
0
      xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_GROUP);
2180
0
    else if (get_shared_repository() == PERM_EVERYBODY)
2181
0
      xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_EVERYBODY);
2182
0
    else
2183
0
      BUG("invalid value for shared_repository");
2184
0
    git_config_set("core.sharedrepository", buf);
2185
0
    git_config_set("receive.denyNonFastforwards", "true");
2186
0
  }
2187
2188
1.22k
  if (!(flags & INIT_DB_QUIET)) {
2189
1.22k
    int len = strlen(git_dir);
2190
2191
1.22k
    if (reinit)
2192
0
      printf(get_shared_repository()
2193
0
             ? _("Reinitialized existing shared Git repository in %s%s\n")
2194
0
             : _("Reinitialized existing Git repository in %s%s\n"),
2195
0
             git_dir, len && git_dir[len-1] != '/' ? "/" : "");
2196
1.22k
    else
2197
1.22k
      printf(get_shared_repository()
2198
1.22k
             ? _("Initialized empty shared Git repository in %s%s\n")
2199
1.22k
             : _("Initialized empty Git repository in %s%s\n"),
2200
1.22k
             git_dir, len && git_dir[len-1] != '/' ? "/" : "");
2201
1.22k
  }
2202
2203
1.22k
  clear_repository_format(&repo_fmt);
2204
1.22k
  free(original_git_dir);
2205
1.22k
  return 0;
2206
1.22k
}