Coverage Report

Created: 2026-02-26 06:44

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/git/path.c
Line
Count
Source
1
/*
2
 * Utilities for paths and pathnames
3
 */
4
5
#include "git-compat-util.h"
6
#include "abspath.h"
7
#include "environment.h"
8
#include "gettext.h"
9
#include "repository.h"
10
#include "strbuf.h"
11
#include "string-list.h"
12
#include "dir.h"
13
#include "worktree.h"
14
#include "setup.h"
15
#include "submodule-config.h"
16
#include "path.h"
17
#include "packfile.h"
18
#include "odb.h"
19
#include "lockfile.h"
20
#include "exec-cmd.h"
21
22
static int get_st_mode_bits(const char *path, int *mode)
23
0
{
24
0
  struct stat st;
25
0
  if (lstat(path, &st) < 0)
26
0
    return -1;
27
0
  *mode = st.st_mode;
28
0
  return 0;
29
0
}
30
31
static struct strbuf *get_pathname(void)
32
0
{
33
0
  static struct strbuf pathname_array[4] = {
34
0
    STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
35
0
  };
36
0
  static int index;
37
0
  struct strbuf *sb = &pathname_array[index];
38
0
  index = (index + 1) % ARRAY_SIZE(pathname_array);
39
0
  strbuf_reset(sb);
40
0
  return sb;
41
0
}
42
43
static const char *cleanup_path(const char *path)
44
0
{
45
  /* Clean it up */
46
0
  if (skip_prefix(path, "./", &path)) {
47
0
    while (*path == '/')
48
0
      path++;
49
0
  }
50
0
  return path;
51
0
}
52
53
static void strbuf_cleanup_path(struct strbuf *sb)
54
0
{
55
0
  const char *path = cleanup_path(sb->buf);
56
0
  if (path > sb->buf)
57
0
    strbuf_remove(sb, 0, path - sb->buf);
58
0
}
59
60
static int dir_prefix(const char *buf, const char *dir)
61
0
{
62
0
  int len = strlen(dir);
63
0
  return !strncmp(buf, dir, len) &&
64
0
    (is_dir_sep(buf[len]) || buf[len] == '\0');
65
0
}
66
67
/* $buf =~ m|$dir/+$file| but without regex */
68
static int is_dir_file(const char *buf, const char *dir, const char *file)
69
0
{
70
0
  int len = strlen(dir);
71
0
  if (strncmp(buf, dir, len) || !is_dir_sep(buf[len]))
72
0
    return 0;
73
0
  while (is_dir_sep(buf[len]))
74
0
    len++;
75
0
  return !strcmp(buf + len, file);
76
0
}
77
78
static void replace_dir(struct strbuf *buf, int len, const char *newdir)
79
0
{
80
0
  int newlen = strlen(newdir);
81
0
  int need_sep = (buf->buf[len] && !is_dir_sep(buf->buf[len])) &&
82
0
    !is_dir_sep(newdir[newlen - 1]);
83
0
  if (need_sep)
84
0
    len--;  /* keep one char, to be replaced with '/'  */
85
0
  strbuf_splice(buf, 0, len, newdir, newlen);
86
0
  if (need_sep)
87
0
    buf->buf[newlen] = '/';
88
0
}
89
90
struct common_dir {
91
  /* Not considered garbage for report_linked_checkout_garbage */
92
  unsigned ignore_garbage:1;
93
  unsigned is_dir:1;
94
  /* Belongs to the common dir, though it may contain paths that don't */
95
  unsigned is_common:1;
96
  const char *path;
97
};
98
99
static struct common_dir common_list[] = {
100
  { 0, 1, 1, "branches" },
101
  { 0, 1, 1, "common" },
102
  { 0, 1, 1, "hooks" },
103
  { 0, 1, 1, "info" },
104
  { 0, 0, 0, "info/sparse-checkout" },
105
  { 1, 1, 1, "logs" },
106
  { 1, 0, 0, "logs/HEAD" },
107
  { 0, 1, 0, "logs/refs/bisect" },
108
  { 0, 1, 0, "logs/refs/rewritten" },
109
  { 0, 1, 0, "logs/refs/worktree" },
110
  { 0, 1, 1, "lost-found" },
111
  { 0, 1, 1, "objects" },
112
  { 0, 1, 1, "refs" },
113
  { 0, 1, 0, "refs/bisect" },
114
  { 0, 1, 0, "refs/rewritten" },
115
  { 0, 1, 0, "refs/worktree" },
116
  { 0, 1, 1, "remotes" },
117
  { 0, 1, 1, "worktrees" },
118
  { 0, 1, 1, "rr-cache" },
119
  { 0, 1, 1, "svn" },
120
  { 0, 0, 1, "config" },
121
  { 1, 0, 1, "gc.pid" },
122
  { 0, 0, 1, "packed-refs" },
123
  { 0, 0, 1, "shallow" },
124
  { 0, 0, 0, NULL }
125
};
126
127
/*
128
 * A compressed trie.  A trie node consists of zero or more characters that
129
 * are common to all elements with this prefix, optionally followed by some
130
 * children.  If value is not NULL, the trie node is a terminal node.
131
 *
132
 * For example, consider the following set of strings:
133
 * abc
134
 * def
135
 * definite
136
 * definition
137
 *
138
 * The trie would look like:
139
 * root: len = 0, children a and d non-NULL, value = NULL.
140
 *    a: len = 2, contents = bc, value = (data for "abc")
141
 *    d: len = 2, contents = ef, children i non-NULL, value = (data for "def")
142
 *       i: len = 3, contents = nit, children e and i non-NULL, value = NULL
143
 *           e: len = 0, children all NULL, value = (data for "definite")
144
 *           i: len = 2, contents = on, children all NULL,
145
 *              value = (data for "definition")
146
 */
147
struct trie {
148
  struct trie *children[256];
149
  int len;
150
  char *contents;
151
  void *value;
152
};
153
154
static struct trie *make_trie_node(const char *key, void *value)
155
0
{
156
0
  struct trie *new_node = xcalloc(1, sizeof(*new_node));
157
0
  new_node->len = strlen(key);
158
0
  if (new_node->len) {
159
0
    new_node->contents = xmalloc(new_node->len);
160
0
    memcpy(new_node->contents, key, new_node->len);
161
0
  }
162
0
  new_node->value = value;
163
0
  return new_node;
164
0
}
165
166
/*
167
 * Add a key/value pair to a trie.  The key is assumed to be \0-terminated.
168
 * If there was an existing value for this key, return it.
169
 */
170
static void *add_to_trie(struct trie *root, const char *key, void *value)
171
0
{
172
0
  struct trie *child;
173
0
  void *old;
174
0
  int i;
175
176
0
  if (!*key) {
177
    /* we have reached the end of the key */
178
0
    old = root->value;
179
0
    root->value = value;
180
0
    return old;
181
0
  }
182
183
0
  for (i = 0; i < root->len; i++) {
184
0
    if (root->contents[i] == key[i])
185
0
      continue;
186
187
    /*
188
     * Split this node: child will contain this node's
189
     * existing children.
190
     */
191
0
    child = xmalloc(sizeof(*child));
192
0
    memcpy(child->children, root->children, sizeof(root->children));
193
194
0
    child->len = root->len - i - 1;
195
0
    if (child->len) {
196
0
      child->contents = xstrndup(root->contents + i + 1,
197
0
               child->len);
198
0
    }
199
0
    child->value = root->value;
200
0
    root->value = NULL;
201
0
    root->len = i;
202
203
0
    memset(root->children, 0, sizeof(root->children));
204
0
    root->children[(unsigned char)root->contents[i]] = child;
205
206
    /* This is the newly-added child. */
207
0
    root->children[(unsigned char)key[i]] =
208
0
      make_trie_node(key + i + 1, value);
209
0
    return NULL;
210
0
  }
211
212
  /* We have matched the entire compressed section */
213
0
  if (key[i]) {
214
0
    child = root->children[(unsigned char)key[root->len]];
215
0
    if (child) {
216
0
      return add_to_trie(child, key + root->len + 1, value);
217
0
    } else {
218
0
      child = make_trie_node(key + root->len + 1, value);
219
0
      root->children[(unsigned char)key[root->len]] = child;
220
0
      return NULL;
221
0
    }
222
0
  }
223
224
0
  old = root->value;
225
0
  root->value = value;
226
0
  return old;
227
0
}
228
229
typedef int (*match_fn)(const char *unmatched, void *value, void *baton);
230
231
/*
232
 * Search a trie for some key.  Find the longest /-or-\0-terminated
233
 * prefix of the key for which the trie contains a value.  If there is
234
 * no such prefix, return -1.  Otherwise call fn with the unmatched
235
 * portion of the key and the found value.  If fn returns 0 or
236
 * positive, then return its return value.  If fn returns negative,
237
 * then call fn with the next-longest /-terminated prefix of the key
238
 * (i.e. a parent directory) for which the trie contains a value, and
239
 * handle its return value the same way.  If there is no shorter
240
 * /-terminated prefix with a value left, then return the negative
241
 * return value of the most recent fn invocation.
242
 *
243
 * The key is partially normalized: consecutive slashes are skipped.
244
 *
245
 * For example, consider the trie containing only [logs,
246
 * logs/refs/bisect], both with values, but not logs/refs.
247
 *
248
 * | key                | unmatched      | prefix to node   | return value |
249
 * |--------------------|----------------|------------------|--------------|
250
 * | a                  | not called     | n/a              | -1           |
251
 * | logstore           | not called     | n/a              | -1           |
252
 * | logs               | \0             | logs             | as per fn    |
253
 * | logs/              | /              | logs             | as per fn    |
254
 * | logs/refs          | /refs          | logs             | as per fn    |
255
 * | logs/refs/         | /refs/         | logs             | as per fn    |
256
 * | logs/refs/b        | /refs/b        | logs             | as per fn    |
257
 * | logs/refs/bisected | /refs/bisected | logs             | as per fn    |
258
 * | logs/refs/bisect   | \0             | logs/refs/bisect | as per fn    |
259
 * | logs/refs/bisect/  | /              | logs/refs/bisect | as per fn    |
260
 * | logs/refs/bisect/a | /a             | logs/refs/bisect | as per fn    |
261
 * | (If fn in the previous line returns -1, then fn is called once more:) |
262
 * | logs/refs/bisect/a | /refs/bisect/a | logs             | as per fn    |
263
 * |--------------------|----------------|------------------|--------------|
264
 */
265
static int trie_find(struct trie *root, const char *key, match_fn fn,
266
         void *baton)
267
0
{
268
0
  int i;
269
0
  int result;
270
0
  struct trie *child;
271
272
0
  if (!*key) {
273
    /* we have reached the end of the key */
274
0
    if (root->value && !root->len)
275
0
      return fn(key, root->value, baton);
276
0
    else
277
0
      return -1;
278
0
  }
279
280
0
  for (i = 0; i < root->len; i++) {
281
    /* Partial path normalization: skip consecutive slashes. */
282
0
    if (key[i] == '/' && key[i+1] == '/') {
283
0
      key++;
284
0
      continue;
285
0
    }
286
0
    if (root->contents[i] != key[i])
287
0
      return -1;
288
0
  }
289
290
  /* Matched the entire compressed section */
291
0
  key += i;
292
0
  if (!*key) {
293
    /* End of key */
294
0
    if (root->value)
295
0
      return fn(key, root->value, baton);
296
0
    else
297
0
      return -1;
298
0
  }
299
300
  /* Partial path normalization: skip consecutive slashes */
301
0
  while (key[0] == '/' && key[1] == '/')
302
0
    key++;
303
304
0
  child = root->children[(unsigned char)*key];
305
0
  if (child)
306
0
    result = trie_find(child, key + 1, fn, baton);
307
0
  else
308
0
    result = -1;
309
310
0
  if (result >= 0 || (*key != '/' && *key != 0))
311
0
    return result;
312
0
  if (root->value)
313
0
    return fn(key, root->value, baton);
314
0
  else
315
0
    return -1;
316
0
}
317
318
static struct trie common_trie;
319
static int common_trie_done_setup;
320
321
static void init_common_trie(void)
322
0
{
323
0
  struct common_dir *p;
324
325
0
  if (common_trie_done_setup)
326
0
    return;
327
328
0
  for (p = common_list; p->path; p++)
329
0
    add_to_trie(&common_trie, p->path, p);
330
331
0
  common_trie_done_setup = 1;
332
0
}
333
334
/*
335
 * Helper function for update_common_dir: returns 1 if the dir
336
 * prefix is common.
337
 */
338
static int check_common(const char *unmatched, void *value,
339
      void *baton UNUSED)
340
0
{
341
0
  struct common_dir *dir = value;
342
343
0
  if (dir->is_dir && (unmatched[0] == 0 || unmatched[0] == '/'))
344
0
    return dir->is_common;
345
346
0
  if (!dir->is_dir && unmatched[0] == 0)
347
0
    return dir->is_common;
348
349
0
  return 0;
350
0
}
351
352
static void update_common_dir(struct strbuf *buf, int git_dir_len,
353
            const char *common_dir)
354
0
{
355
0
  char *base = buf->buf + git_dir_len;
356
0
  int has_lock_suffix = strbuf_strip_suffix(buf, LOCK_SUFFIX);
357
358
0
  init_common_trie();
359
0
  if (trie_find(&common_trie, base, check_common, NULL) > 0)
360
0
    replace_dir(buf, git_dir_len, common_dir);
361
362
0
  if (has_lock_suffix)
363
0
    strbuf_addstr(buf, LOCK_SUFFIX);
364
0
}
365
366
void report_linked_checkout_garbage(struct repository *r)
367
0
{
368
0
  struct strbuf sb = STRBUF_INIT;
369
0
  const struct common_dir *p;
370
0
  int len;
371
372
0
  if (!r->different_commondir)
373
0
    return;
374
0
  strbuf_addf(&sb, "%s/", r->gitdir);
375
0
  len = sb.len;
376
0
  for (p = common_list; p->path; p++) {
377
0
    const char *path = p->path;
378
0
    if (p->ignore_garbage)
379
0
      continue;
380
0
    strbuf_setlen(&sb, len);
381
0
    strbuf_addstr(&sb, path);
382
0
    if (file_exists(sb.buf))
383
0
      report_garbage(PACKDIR_FILE_GARBAGE, sb.buf);
384
0
  }
385
0
  strbuf_release(&sb);
386
0
}
387
388
static void adjust_git_path(struct repository *repo,
389
          struct strbuf *buf, int git_dir_len)
390
0
{
391
0
  const char *base = buf->buf + git_dir_len;
392
393
0
  if (is_dir_file(base, "info", "grafts"))
394
0
    strbuf_splice(buf, 0, buf->len,
395
0
            repo->graft_file, strlen(repo->graft_file));
396
0
  else if (!strcmp(base, "index"))
397
0
    strbuf_splice(buf, 0, buf->len,
398
0
            repo->index_file, strlen(repo->index_file));
399
0
  else if (dir_prefix(base, "objects"))
400
0
    replace_dir(buf, git_dir_len + 7, repo->objects->sources->path);
401
0
  else if (repo_settings_get_hooks_path(repo) && dir_prefix(base, "hooks"))
402
0
    replace_dir(buf, git_dir_len + 5, repo_settings_get_hooks_path(repo));
403
0
  else if (repo->different_commondir)
404
0
    update_common_dir(buf, git_dir_len, repo->commondir);
405
0
}
406
407
static void strbuf_worktree_gitdir(struct strbuf *buf,
408
           const struct repository *repo,
409
           const struct worktree *wt)
410
0
{
411
0
  if (!wt)
412
0
    strbuf_addstr(buf, repo->gitdir);
413
0
  else if (!wt->id)
414
0
    strbuf_addstr(buf, repo->commondir);
415
0
  else
416
0
    repo_common_path_append(repo, buf, "worktrees/%s", wt->id);
417
0
}
418
419
static void repo_git_pathv(struct repository *repo,
420
         const struct worktree *wt, struct strbuf *buf,
421
         const char *fmt, va_list args)
422
0
{
423
0
  int gitdir_len;
424
0
  strbuf_worktree_gitdir(buf, repo, wt);
425
0
  if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
426
0
    strbuf_addch(buf, '/');
427
0
  gitdir_len = buf->len;
428
0
  strbuf_vaddf(buf, fmt, args);
429
0
  if (!wt)
430
0
    adjust_git_path(repo, buf, gitdir_len);
431
0
  strbuf_cleanup_path(buf);
432
0
}
433
434
char *repo_git_path(struct repository *repo,
435
        const char *fmt, ...)
436
0
{
437
0
  struct strbuf path = STRBUF_INIT;
438
0
  va_list args;
439
0
  va_start(args, fmt);
440
0
  repo_git_pathv(repo, NULL, &path, fmt, args);
441
0
  va_end(args);
442
0
  return strbuf_detach(&path, NULL);
443
0
}
444
445
const char *repo_git_path_append(struct repository *repo,
446
         struct strbuf *sb,
447
         const char *fmt, ...)
448
0
{
449
0
  va_list args;
450
0
  va_start(args, fmt);
451
0
  repo_git_pathv(repo, NULL, sb, fmt, args);
452
0
  va_end(args);
453
0
  return sb->buf;
454
0
}
455
456
const char *repo_git_path_replace(struct repository *repo,
457
          struct strbuf *sb,
458
          const char *fmt, ...)
459
0
{
460
0
  va_list args;
461
0
  strbuf_reset(sb);
462
0
  va_start(args, fmt);
463
0
  repo_git_pathv(repo, NULL, sb, fmt, args);
464
0
  va_end(args);
465
0
  return sb->buf;
466
0
}
467
468
char *mkpathdup(const char *fmt, ...)
469
0
{
470
0
  struct strbuf sb = STRBUF_INIT;
471
0
  va_list args;
472
0
  va_start(args, fmt);
473
0
  strbuf_vaddf(&sb, fmt, args);
474
0
  va_end(args);
475
0
  strbuf_cleanup_path(&sb);
476
0
  return strbuf_detach(&sb, NULL);
477
0
}
478
479
const char *mkpath(const char *fmt, ...)
480
0
{
481
0
  va_list args;
482
0
  struct strbuf *pathname = get_pathname();
483
0
  va_start(args, fmt);
484
0
  strbuf_vaddf(pathname, fmt, args);
485
0
  va_end(args);
486
0
  return cleanup_path(pathname->buf);
487
0
}
488
489
const char *worktree_git_path(struct repository *r,
490
            const struct worktree *wt, const char *fmt, ...)
491
0
{
492
0
  struct strbuf *pathname = get_pathname();
493
0
  va_list args;
494
495
0
  if (wt && wt->repo != r)
496
0
    BUG("worktree not connected to expected repository");
497
498
0
  va_start(args, fmt);
499
0
  repo_git_pathv(r, wt, pathname, fmt, args);
500
0
  va_end(args);
501
0
  return pathname->buf;
502
0
}
503
504
static void do_worktree_path(const struct repository *repo,
505
           struct strbuf *buf,
506
           const char *fmt, va_list args)
507
0
{
508
0
  strbuf_addstr(buf, repo->worktree);
509
0
  if(buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
510
0
    strbuf_addch(buf, '/');
511
512
0
  strbuf_vaddf(buf, fmt, args);
513
0
  strbuf_cleanup_path(buf);
514
0
}
515
516
char *repo_worktree_path(const struct repository *repo, const char *fmt, ...)
517
0
{
518
0
  struct strbuf path = STRBUF_INIT;
519
0
  va_list args;
520
521
0
  va_start(args, fmt);
522
0
  do_worktree_path(repo, &path, fmt, args);
523
0
  va_end(args);
524
525
0
  return strbuf_detach(&path, NULL);
526
0
}
527
528
const char *repo_worktree_path_append(const struct repository *repo,
529
              struct strbuf *sb,
530
              const char *fmt, ...)
531
0
{
532
0
  va_list args;
533
534
0
  if (!repo->worktree)
535
0
    return NULL;
536
537
0
  va_start(args, fmt);
538
0
  do_worktree_path(repo, sb, fmt, args);
539
0
  va_end(args);
540
541
0
  return sb->buf;
542
0
}
543
544
const char *repo_worktree_path_replace(const struct repository *repo,
545
               struct strbuf *sb,
546
               const char *fmt, ...)
547
0
{
548
0
  va_list args;
549
550
0
  strbuf_reset(sb);
551
0
  if (!repo->worktree)
552
0
    return NULL;
553
554
0
  va_start(args, fmt);
555
0
  do_worktree_path(repo, sb, fmt, args);
556
0
  va_end(args);
557
558
0
  return sb->buf;
559
0
}
560
561
/* Returns 0 on success, negative on failure. */
562
static int do_submodule_path(struct repository *repo,
563
           struct strbuf *buf, const char *path,
564
           const char *fmt, va_list args)
565
0
{
566
0
  struct strbuf git_submodule_common_dir = STRBUF_INIT;
567
0
  struct strbuf git_submodule_dir = STRBUF_INIT;
568
0
  int ret;
569
570
0
  ret = submodule_to_gitdir(repo, &git_submodule_dir, path);
571
0
  if (ret)
572
0
    goto cleanup;
573
574
0
  strbuf_complete(&git_submodule_dir, '/');
575
0
  strbuf_addbuf(buf, &git_submodule_dir);
576
0
  strbuf_vaddf(buf, fmt, args);
577
578
0
  if (get_common_dir_noenv(&git_submodule_common_dir, git_submodule_dir.buf))
579
0
    update_common_dir(buf, git_submodule_dir.len, git_submodule_common_dir.buf);
580
581
0
  strbuf_cleanup_path(buf);
582
583
0
cleanup:
584
0
  strbuf_release(&git_submodule_dir);
585
0
  strbuf_release(&git_submodule_common_dir);
586
0
  return ret;
587
0
}
588
589
char *repo_submodule_path(struct repository *repo,
590
        const char *path, const char *fmt, ...)
591
0
{
592
0
  int err;
593
0
  va_list args;
594
0
  struct strbuf buf = STRBUF_INIT;
595
0
  va_start(args, fmt);
596
0
  err = do_submodule_path(repo, &buf, path, fmt, args);
597
0
  va_end(args);
598
0
  if (err) {
599
0
    strbuf_release(&buf);
600
0
    return NULL;
601
0
  }
602
0
  return strbuf_detach(&buf, NULL);
603
0
}
604
605
const char *repo_submodule_path_append(struct repository *repo,
606
               struct strbuf *buf,
607
               const char *path,
608
               const char *fmt, ...)
609
0
{
610
0
  int err;
611
0
  va_list args;
612
0
  va_start(args, fmt);
613
0
  err = do_submodule_path(repo, buf, path, fmt, args);
614
0
  va_end(args);
615
0
  if (err)
616
0
    return NULL;
617
0
  return buf->buf;
618
0
}
619
620
const char *repo_submodule_path_replace(struct repository *repo,
621
          struct strbuf *buf,
622
          const char *path,
623
          const char *fmt, ...)
624
0
{
625
0
  int err;
626
0
  va_list args;
627
0
  strbuf_reset(buf);
628
0
  va_start(args, fmt);
629
0
  err = do_submodule_path(repo, buf, path, fmt, args);
630
0
  va_end(args);
631
0
  if (err)
632
0
    return NULL;
633
0
  return buf->buf;
634
0
}
635
636
static void repo_common_pathv(const struct repository *repo,
637
            struct strbuf *sb,
638
            const char *fmt,
639
            va_list args)
640
0
{
641
0
  strbuf_addstr(sb, repo->commondir);
642
0
  if (sb->len && !is_dir_sep(sb->buf[sb->len - 1]))
643
0
    strbuf_addch(sb, '/');
644
0
  strbuf_vaddf(sb, fmt, args);
645
0
  strbuf_cleanup_path(sb);
646
0
}
647
648
char *repo_common_path(const struct repository *repo,
649
           const char *fmt, ...)
650
0
{
651
0
  struct strbuf sb = STRBUF_INIT;
652
0
  va_list args;
653
0
  va_start(args, fmt);
654
0
  repo_common_pathv(repo, &sb, fmt, args);
655
0
  va_end(args);
656
0
  return strbuf_detach(&sb, NULL);
657
0
}
658
659
const char *repo_common_path_append(const struct repository *repo,
660
            struct strbuf *sb,
661
            const char *fmt, ...)
662
0
{
663
0
  va_list args;
664
0
  va_start(args, fmt);
665
0
  repo_common_pathv(repo, sb, fmt, args);
666
0
  va_end(args);
667
0
  return sb->buf;
668
0
}
669
670
const char *repo_common_path_replace(const struct repository *repo,
671
             struct strbuf *sb,
672
             const char *fmt, ...)
673
0
{
674
0
  va_list args;
675
0
  strbuf_reset(sb);
676
0
  va_start(args, fmt);
677
0
  repo_common_pathv(repo, sb, fmt, args);
678
0
  va_end(args);
679
0
  return sb->buf;
680
0
}
681
682
static struct passwd *getpw_str(const char *username, size_t len)
683
0
{
684
0
  struct passwd *pw;
685
0
  char *username_z = xmemdupz(username, len);
686
0
  pw = getpwnam(username_z);
687
0
  free(username_z);
688
0
  return pw;
689
0
}
690
691
/*
692
 * Return a string with ~ and ~user expanded via getpw*. Returns NULL on getpw
693
 * failure or if path is NULL.
694
 *
695
 * If real_home is true, strbuf_realpath($HOME) is used in the `~/` expansion.
696
 *
697
 * If the path starts with `%(prefix)/`, the remainder is interpreted as
698
 * relative to where Git is installed, and expanded to the absolute path.
699
 */
700
char *interpolate_path(const char *path, int real_home)
701
0
{
702
0
  struct strbuf user_path = STRBUF_INIT;
703
0
  const char *to_copy = path;
704
705
0
  if (!path)
706
0
    goto return_null;
707
708
0
  if (skip_prefix(path, "%(prefix)/", &path))
709
0
    return system_path(path);
710
711
0
  if (path[0] == '~') {
712
0
    const char *first_slash = strchrnul(path, '/');
713
0
    const char *username = path + 1;
714
0
    size_t username_len = first_slash - username;
715
0
    if (username_len == 0) {
716
0
      const char *home = getenv("HOME");
717
0
      if (!home)
718
0
        goto return_null;
719
0
      if (real_home)
720
0
        strbuf_add_real_path(&user_path, home);
721
0
      else
722
0
        strbuf_addstr(&user_path, home);
723
#ifdef GIT_WINDOWS_NATIVE
724
      convert_slashes(user_path.buf);
725
#endif
726
0
    } else {
727
0
      struct passwd *pw = getpw_str(username, username_len);
728
0
      if (!pw)
729
0
        goto return_null;
730
0
      strbuf_addstr(&user_path, pw->pw_dir);
731
0
    }
732
0
    to_copy = first_slash;
733
0
  }
734
0
  strbuf_addstr(&user_path, to_copy);
735
0
  return strbuf_detach(&user_path, NULL);
736
0
return_null:
737
0
  strbuf_release(&user_path);
738
0
  return NULL;
739
0
}
740
741
int calc_shared_perm(struct repository *repo,
742
         int mode)
743
0
{
744
0
  int tweak;
745
746
0
  if (repo_settings_get_shared_repository(repo) < 0)
747
0
    tweak = -repo_settings_get_shared_repository(repo);
748
0
  else
749
0
    tweak = repo_settings_get_shared_repository(repo);
750
751
0
  if (!(mode & S_IWUSR))
752
0
    tweak &= ~0222;
753
0
  if (mode & S_IXUSR)
754
    /* Copy read bits to execute bits */
755
0
    tweak |= (tweak & 0444) >> 2;
756
0
  if (repo_settings_get_shared_repository(repo) < 0)
757
0
    mode = (mode & ~0777) | tweak;
758
0
  else
759
0
    mode |= tweak;
760
761
0
  return mode;
762
0
}
763
764
int adjust_shared_perm(struct repository *repo,
765
           const char *path)
766
0
{
767
0
  int old_mode, new_mode;
768
769
0
  if (!repo_settings_get_shared_repository(repo))
770
0
    return 0;
771
0
  if (get_st_mode_bits(path, &old_mode) < 0)
772
0
    return -1;
773
774
0
  new_mode = calc_shared_perm(repo, old_mode);
775
0
  if (S_ISDIR(old_mode)) {
776
    /* Copy read bits to execute bits */
777
0
    new_mode |= (new_mode & 0444) >> 2;
778
779
    /*
780
     * g+s matters only if any extra access is granted
781
     * based on group membership.
782
     */
783
0
    if (FORCE_DIR_SET_GID && (new_mode & 060))
784
0
      new_mode |= FORCE_DIR_SET_GID;
785
0
  }
786
787
0
  if (((old_mode ^ new_mode) & ~S_IFMT) &&
788
0
      chmod(path, (new_mode & ~S_IFMT)) < 0)
789
0
    return -2;
790
0
  return 0;
791
0
}
792
793
void safe_create_dir(struct repository *repo, const char *dir, int share)
794
0
{
795
0
  if (mkdir(dir, 0777) < 0) {
796
0
    if (errno != EEXIST) {
797
0
      perror(dir);
798
0
      exit(1);
799
0
    }
800
0
  }
801
0
  else if (share && adjust_shared_perm(repo, dir))
802
0
    die(_("Could not make %s writable by group"), dir);
803
0
}
804
805
int safe_create_dir_in_gitdir(struct repository *repo, const char *path)
806
0
{
807
0
  if (mkdir(path, 0777)) {
808
0
    int saved_errno = errno;
809
0
    struct stat st;
810
0
    struct strbuf sb = STRBUF_INIT;
811
812
0
    if (errno != EEXIST)
813
0
      return -1;
814
    /*
815
     * Are we looking at a path in a symlinked worktree
816
     * whose original repository does not yet have it?
817
     * e.g. .git/rr-cache pointing at its original
818
     * repository in which the user hasn't performed any
819
     * conflict resolution yet?
820
     */
821
0
    if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
822
0
        strbuf_readlink(&sb, path, st.st_size) ||
823
0
        !is_absolute_path(sb.buf) ||
824
0
        mkdir(sb.buf, 0777)) {
825
0
      strbuf_release(&sb);
826
0
      errno = saved_errno;
827
0
      return -1;
828
0
    }
829
0
    strbuf_release(&sb);
830
0
  }
831
0
  return adjust_shared_perm(repo, path);
832
0
}
833
834
static enum scld_error safe_create_leading_directories_1(struct repository *repo,
835
               char *path)
836
0
{
837
0
  char *next_component = path + offset_1st_component(path);
838
0
  enum scld_error ret = SCLD_OK;
839
840
0
  while (ret == SCLD_OK && next_component) {
841
0
    struct stat st;
842
0
    char *slash = next_component, slash_character;
843
844
0
    while (*slash && !is_dir_sep(*slash))
845
0
      slash++;
846
847
0
    if (!*slash)
848
0
      break;
849
850
0
    next_component = slash + 1;
851
0
    while (is_dir_sep(*next_component))
852
0
      next_component++;
853
0
    if (!*next_component)
854
0
      break;
855
856
0
    slash_character = *slash;
857
0
    *slash = '\0';
858
0
    if (!stat(path, &st)) {
859
      /* path exists */
860
0
      if (!S_ISDIR(st.st_mode)) {
861
0
        errno = ENOTDIR;
862
0
        ret = SCLD_EXISTS;
863
0
      }
864
0
    } else if (mkdir(path, 0777)) {
865
0
      if (errno == EEXIST &&
866
0
          !stat(path, &st) && S_ISDIR(st.st_mode))
867
0
        ; /* somebody created it since we checked */
868
0
      else if (errno == ENOENT)
869
        /*
870
         * Either mkdir() failed because
871
         * somebody just pruned the containing
872
         * directory, or stat() failed because
873
         * the file that was in our way was
874
         * just removed.  Either way, inform
875
         * the caller that it might be worth
876
         * trying again:
877
         */
878
0
        ret = SCLD_VANISHED;
879
0
      else
880
0
        ret = SCLD_FAILED;
881
0
    } else if (repo && adjust_shared_perm(repo, path)) {
882
0
      ret = SCLD_PERMS;
883
0
    }
884
0
    *slash = slash_character;
885
0
  }
886
0
  return ret;
887
0
}
888
889
enum scld_error safe_create_leading_directories(struct repository *repo,
890
            char *path)
891
0
{
892
0
  return safe_create_leading_directories_1(repo, path);
893
0
}
894
895
enum scld_error safe_create_leading_directories_no_share(char *path)
896
0
{
897
0
  return safe_create_leading_directories_1(NULL, path);
898
0
}
899
900
enum scld_error safe_create_leading_directories_const(struct repository *repo,
901
                  const char *path)
902
0
{
903
0
  int save_errno;
904
  /* path points to cache entries, so xstrdup before messing with it */
905
0
  char *buf = xstrdup(path);
906
0
  enum scld_error result = safe_create_leading_directories(repo, buf);
907
908
0
  save_errno = errno;
909
0
  free(buf);
910
0
  errno = save_errno;
911
0
  return result;
912
0
}
913
914
int safe_create_file_with_leading_directories(struct repository *repo,
915
                const char *path)
916
0
{
917
0
  int fd;
918
919
0
  fd = open(path, O_RDWR|O_CREAT|O_EXCL, 0600);
920
0
  if (0 <= fd)
921
0
    return fd;
922
923
  /* slow path */
924
0
  safe_create_leading_directories_const(repo, path);
925
0
  return open(path, O_RDWR|O_CREAT|O_EXCL, 0600);
926
0
}
927
928
static int have_same_root(const char *path1, const char *path2)
929
0
{
930
0
  int is_abs1, is_abs2;
931
932
0
  is_abs1 = is_absolute_path(path1);
933
0
  is_abs2 = is_absolute_path(path2);
934
0
  return (is_abs1 && is_abs2 && tolower(path1[0]) == tolower(path2[0])) ||
935
0
         (!is_abs1 && !is_abs2);
936
0
}
937
938
/*
939
 * Give path as relative to prefix.
940
 *
941
 * The strbuf may or may not be used, so do not assume it contains the
942
 * returned path.
943
 */
944
const char *relative_path(const char *in, const char *prefix,
945
        struct strbuf *sb)
946
0
{
947
0
  int in_len = in ? strlen(in) : 0;
948
0
  int prefix_len = prefix ? strlen(prefix) : 0;
949
0
  int in_off = 0;
950
0
  int prefix_off = 0;
951
0
  int i = 0, j = 0;
952
953
0
  if (!in_len)
954
0
    return "./";
955
0
  else if (!prefix_len)
956
0
    return in;
957
958
0
  if (have_same_root(in, prefix))
959
    /* bypass dos_drive, for "c:" is identical to "C:" */
960
0
    i = j = has_dos_drive_prefix(in);
961
0
  else {
962
0
    return in;
963
0
  }
964
965
0
  while (i < prefix_len && j < in_len && prefix[i] == in[j]) {
966
0
    if (is_dir_sep(prefix[i])) {
967
0
      while (is_dir_sep(prefix[i]))
968
0
        i++;
969
0
      while (is_dir_sep(in[j]))
970
0
        j++;
971
0
      prefix_off = i;
972
0
      in_off = j;
973
0
    } else {
974
0
      i++;
975
0
      j++;
976
0
    }
977
0
  }
978
979
0
  if (
980
      /* "prefix" seems like prefix of "in" */
981
0
      i >= prefix_len &&
982
      /*
983
       * but "/foo" is not a prefix of "/foobar"
984
       * (i.e. prefix not end with '/')
985
       */
986
0
      prefix_off < prefix_len) {
987
0
    if (j >= in_len) {
988
      /* in="/a/b", prefix="/a/b" */
989
0
      in_off = in_len;
990
0
    } else if (is_dir_sep(in[j])) {
991
      /* in="/a/b/c", prefix="/a/b" */
992
0
      while (is_dir_sep(in[j]))
993
0
        j++;
994
0
      in_off = j;
995
0
    } else {
996
      /* in="/a/bbb/c", prefix="/a/b" */
997
0
      i = prefix_off;
998
0
    }
999
0
  } else if (
1000
       /* "in" is short than "prefix" */
1001
0
       j >= in_len &&
1002
       /* "in" not end with '/' */
1003
0
       in_off < in_len) {
1004
0
    if (is_dir_sep(prefix[i])) {
1005
      /* in="/a/b", prefix="/a/b/c/" */
1006
0
      while (is_dir_sep(prefix[i]))
1007
0
        i++;
1008
0
      in_off = in_len;
1009
0
    }
1010
0
  }
1011
0
  in += in_off;
1012
0
  in_len -= in_off;
1013
1014
0
  if (i >= prefix_len) {
1015
0
    if (!in_len)
1016
0
      return "./";
1017
0
    else
1018
0
      return in;
1019
0
  }
1020
1021
0
  strbuf_reset(sb);
1022
0
  strbuf_grow(sb, in_len);
1023
1024
0
  while (i < prefix_len) {
1025
0
    if (is_dir_sep(prefix[i])) {
1026
0
      strbuf_addstr(sb, "../");
1027
0
      while (is_dir_sep(prefix[i]))
1028
0
        i++;
1029
0
      continue;
1030
0
    }
1031
0
    i++;
1032
0
  }
1033
0
  if (!is_dir_sep(prefix[prefix_len - 1]))
1034
0
    strbuf_addstr(sb, "../");
1035
1036
0
  strbuf_addstr(sb, in);
1037
1038
0
  return sb->buf;
1039
0
}
1040
1041
/*
1042
 * A simpler implementation of relative_path
1043
 *
1044
 * Get relative path by removing "prefix" from "in". This function
1045
 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
1046
 * to increase performance when traversing the path to work_tree.
1047
 */
1048
const char *remove_leading_path(const char *in, const char *prefix)
1049
0
{
1050
0
  static struct strbuf buf = STRBUF_INIT;
1051
0
  int i = 0, j = 0;
1052
1053
0
  if (!prefix || !prefix[0])
1054
0
    return in;
1055
0
  while (prefix[i]) {
1056
0
    if (is_dir_sep(prefix[i])) {
1057
0
      if (!is_dir_sep(in[j]))
1058
0
        return in;
1059
0
      while (is_dir_sep(prefix[i]))
1060
0
        i++;
1061
0
      while (is_dir_sep(in[j]))
1062
0
        j++;
1063
0
      continue;
1064
0
    } else if (in[j] != prefix[i]) {
1065
0
      return in;
1066
0
    }
1067
0
    i++;
1068
0
    j++;
1069
0
  }
1070
0
  if (
1071
      /* "/foo" is a prefix of "/foo" */
1072
0
      in[j] &&
1073
      /* "/foo" is not a prefix of "/foobar" */
1074
0
      !is_dir_sep(prefix[i-1]) && !is_dir_sep(in[j])
1075
0
     )
1076
0
    return in;
1077
0
  while (is_dir_sep(in[j]))
1078
0
    j++;
1079
1080
0
  strbuf_reset(&buf);
1081
0
  if (!in[j])
1082
0
    strbuf_addstr(&buf, ".");
1083
0
  else
1084
0
    strbuf_addstr(&buf, in + j);
1085
0
  return buf.buf;
1086
0
}
1087
1088
/*
1089
 * It is okay if dst == src, but they should not overlap otherwise.
1090
 * The "dst" buffer must be at least as long as "src"; normalizing may shrink
1091
 * the size of the path, but will never grow it.
1092
 *
1093
 * Performs the following normalizations on src, storing the result in dst:
1094
 * - Ensures that components are separated by '/' (Windows only)
1095
 * - Squashes sequences of '/' except "//server/share" on Windows
1096
 * - Removes "." components.
1097
 * - Removes ".." components, and the components the precede them.
1098
 * Returns failure (non-zero) if a ".." component appears as first path
1099
 * component anytime during the normalization. Otherwise, returns success (0).
1100
 *
1101
 * Note that this function is purely textual.  It does not follow symlinks,
1102
 * verify the existence of the path, or make any system calls.
1103
 *
1104
 * prefix_len != NULL is for a specific case of prefix_pathspec():
1105
 * assume that src == dst and src[0..prefix_len-1] is already
1106
 * normalized, any time "../" eats up to the prefix_len part,
1107
 * prefix_len is reduced. In the end prefix_len is the remaining
1108
 * prefix that has not been overridden by user pathspec.
1109
 *
1110
 * NEEDSWORK: This function doesn't perform normalization w.r.t. trailing '/'.
1111
 * For everything but the root folder itself, the normalized path should not
1112
 * end with a '/', then the callers need to be fixed up accordingly.
1113
 *
1114
 */
1115
int normalize_path_copy_len(char *dst, const char *src, int *prefix_len)
1116
0
{
1117
0
  char *dst0;
1118
0
  const char *end;
1119
1120
  /*
1121
   * Copy initial part of absolute path: "/", "C:/", "//server/share/".
1122
   */
1123
0
  end = src + offset_1st_component(src);
1124
0
  while (src < end) {
1125
0
    char c = *src++;
1126
0
    if (is_dir_sep(c))
1127
0
      c = '/';
1128
0
    *dst++ = c;
1129
0
  }
1130
0
  dst0 = dst;
1131
1132
0
  while (is_dir_sep(*src))
1133
0
    src++;
1134
1135
0
  for (;;) {
1136
0
    char c = *src;
1137
1138
    /*
1139
     * A path component that begins with . could be
1140
     * special:
1141
     * (1) "." and ends   -- ignore and terminate.
1142
     * (2) "./"           -- ignore them, eat slash and continue.
1143
     * (3) ".." and ends  -- strip one and terminate.
1144
     * (4) "../"          -- strip one, eat slash and continue.
1145
     */
1146
0
    if (c == '.') {
1147
0
      if (!src[1]) {
1148
        /* (1) */
1149
0
        src++;
1150
0
      } else if (is_dir_sep(src[1])) {
1151
        /* (2) */
1152
0
        src += 2;
1153
0
        while (is_dir_sep(*src))
1154
0
          src++;
1155
0
        continue;
1156
0
      } else if (src[1] == '.') {
1157
0
        if (!src[2]) {
1158
          /* (3) */
1159
0
          src += 2;
1160
0
          goto up_one;
1161
0
        } else if (is_dir_sep(src[2])) {
1162
          /* (4) */
1163
0
          src += 3;
1164
0
          while (is_dir_sep(*src))
1165
0
            src++;
1166
0
          goto up_one;
1167
0
        }
1168
0
      }
1169
0
    }
1170
1171
    /* copy up to the next '/', and eat all '/' */
1172
0
    while ((c = *src++) != '\0' && !is_dir_sep(c))
1173
0
      *dst++ = c;
1174
0
    if (is_dir_sep(c)) {
1175
0
      *dst++ = '/';
1176
0
      while (is_dir_sep(c))
1177
0
        c = *src++;
1178
0
      src--;
1179
0
    } else if (!c)
1180
0
      break;
1181
0
    continue;
1182
1183
0
  up_one:
1184
    /*
1185
     * dst0..dst is prefix portion, and dst[-1] is '/';
1186
     * go up one level.
1187
     */
1188
0
    dst--;  /* go to trailing '/' */
1189
0
    if (dst <= dst0)
1190
0
      return -1;
1191
    /* Windows: dst[-1] cannot be backslash anymore */
1192
0
    while (dst0 < dst && dst[-1] != '/')
1193
0
      dst--;
1194
0
    if (prefix_len && *prefix_len > dst - dst0)
1195
0
      *prefix_len = dst - dst0;
1196
0
  }
1197
0
  *dst = '\0';
1198
0
  return 0;
1199
0
}
1200
1201
int normalize_path_copy(char *dst, const char *src)
1202
0
{
1203
0
  return normalize_path_copy_len(dst, src, NULL);
1204
0
}
1205
1206
int strbuf_normalize_path(struct strbuf *src)
1207
0
{
1208
0
  struct strbuf dst = STRBUF_INIT;
1209
1210
0
  strbuf_grow(&dst, src->len);
1211
0
  if (normalize_path_copy(dst.buf, src->buf) < 0) {
1212
0
    strbuf_release(&dst);
1213
0
    return -1;
1214
0
  }
1215
1216
  /*
1217
   * normalize_path does not tell us the new length, so we have to
1218
   * compute it by looking for the new NUL it placed
1219
   */
1220
0
  strbuf_setlen(&dst, strlen(dst.buf));
1221
0
  strbuf_swap(src, &dst);
1222
0
  strbuf_release(&dst);
1223
0
  return 0;
1224
0
}
1225
1226
/*
1227
 * path = Canonical absolute path
1228
 * prefixes = string_list containing normalized, absolute paths without
1229
 * trailing slashes (except for the root directory, which is denoted by "/").
1230
 *
1231
 * Determines, for each path in prefixes, whether the "prefix"
1232
 * is an ancestor directory of path.  Returns the length of the longest
1233
 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
1234
 * is an ancestor.  (Note that this means 0 is returned if prefixes is
1235
 * ["/"].) "/foo" is not considered an ancestor of "/foobar".  Directories
1236
 * are not considered to be their own ancestors.  path must be in a
1237
 * canonical form: empty components, or "." or ".." components are not
1238
 * allowed.
1239
 */
1240
int longest_ancestor_length(const char *path, struct string_list *prefixes)
1241
0
{
1242
0
  int max_len = -1;
1243
1244
0
  if (!strcmp(path, "/"))
1245
0
    return -1;
1246
1247
0
  for (size_t i = 0; i < prefixes->nr; i++) {
1248
0
    const char *ceil = prefixes->items[i].string;
1249
0
    int len = strlen(ceil);
1250
1251
    /*
1252
     * For root directories (`/`, `C:/`, `//server/share/`)
1253
     * adjust the length to exclude the trailing slash.
1254
     */
1255
0
    if (len > 0 && ceil[len - 1] == '/')
1256
0
      len--;
1257
1258
0
    if (strncmp(path, ceil, len) ||
1259
0
        path[len] != '/' || !path[len + 1])
1260
0
      continue; /* no match */
1261
1262
0
    if (len > max_len)
1263
0
      max_len = len;
1264
0
  }
1265
1266
0
  return max_len;
1267
0
}
1268
1269
/* strip arbitrary amount of directory separators at end of path */
1270
static inline int chomp_trailing_dir_sep(const char *path, int len)
1271
0
{
1272
0
  while (len && is_dir_sep(path[len - 1]))
1273
0
    len--;
1274
0
  return len;
1275
0
}
1276
1277
/*
1278
 * If path ends with suffix (complete path components), returns the offset of
1279
 * the last character in the path before the suffix (sans trailing directory
1280
 * separators), and -1 otherwise.
1281
 */
1282
static ssize_t stripped_path_suffix_offset(const char *path, const char *suffix)
1283
0
{
1284
0
  int path_len = strlen(path), suffix_len = strlen(suffix);
1285
1286
0
  while (suffix_len) {
1287
0
    if (!path_len)
1288
0
      return -1;
1289
1290
0
    if (is_dir_sep(path[path_len - 1])) {
1291
0
      if (!is_dir_sep(suffix[suffix_len - 1]))
1292
0
        return -1;
1293
0
      path_len = chomp_trailing_dir_sep(path, path_len);
1294
0
      suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
1295
0
    }
1296
0
    else if (path[--path_len] != suffix[--suffix_len])
1297
0
      return -1;
1298
0
  }
1299
1300
0
  if (path_len && !is_dir_sep(path[path_len - 1]))
1301
0
    return -1;
1302
0
  return chomp_trailing_dir_sep(path, path_len);
1303
0
}
1304
1305
/*
1306
 * Returns true if the path ends with components, considering only complete path
1307
 * components, and false otherwise.
1308
 */
1309
int ends_with_path_components(const char *path, const char *components)
1310
0
{
1311
0
  return stripped_path_suffix_offset(path, components) != -1;
1312
0
}
1313
1314
/*
1315
 * If path ends with suffix (complete path components), returns the
1316
 * part before suffix (sans trailing directory separators).
1317
 * Otherwise returns NULL.
1318
 */
1319
char *strip_path_suffix(const char *path, const char *suffix)
1320
0
{
1321
0
  ssize_t offset = stripped_path_suffix_offset(path, suffix);
1322
1323
0
  return offset == -1 ? NULL : xstrndup(path, offset);
1324
0
}
1325
1326
int daemon_avoid_alias(const char *p)
1327
0
{
1328
0
  int sl, ndot;
1329
1330
  /*
1331
   * This resurrects the belts and suspenders paranoia check by HPA
1332
   * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
1333
   * does not do getcwd() based path canonicalization.
1334
   *
1335
   * sl becomes true immediately after seeing '/' and continues to
1336
   * be true as long as dots continue after that without intervening
1337
   * non-dot character.
1338
   */
1339
0
  if (!p || (*p != '/' && *p != '~'))
1340
0
    return -1;
1341
0
  sl = 1; ndot = 0;
1342
0
  p++;
1343
1344
0
  while (1) {
1345
0
    char ch = *p++;
1346
0
    if (sl) {
1347
0
      if (ch == '.')
1348
0
        ndot++;
1349
0
      else if (ch == '/') {
1350
0
        if (ndot < 3)
1351
          /* reject //, /./ and /../ */
1352
0
          return -1;
1353
0
        ndot = 0;
1354
0
      }
1355
0
      else if (ch == 0) {
1356
0
        if (0 < ndot && ndot < 3)
1357
          /* reject /.$ and /..$ */
1358
0
          return -1;
1359
0
        return 0;
1360
0
      }
1361
0
      else
1362
0
        sl = ndot = 0;
1363
0
    }
1364
0
    else if (ch == 0)
1365
0
      return 0;
1366
0
    else if (ch == '/') {
1367
0
      sl = 1;
1368
0
      ndot = 0;
1369
0
    }
1370
0
  }
1371
0
}
1372
1373
/*
1374
 * On NTFS, we need to be careful to disallow certain synonyms of the `.git/`
1375
 * directory:
1376
 *
1377
 * - For historical reasons, file names that end in spaces or periods are
1378
 *   automatically trimmed. Therefore, `.git . . ./` is a valid way to refer
1379
 *   to `.git/`.
1380
 *
1381
 * - For other historical reasons, file names that do not conform to the 8.3
1382
 *   format (up to eight characters for the basename, three for the file
1383
 *   extension, certain characters not allowed such as `+`, etc) are associated
1384
 *   with a so-called "short name", at least on the `C:` drive by default.
1385
 *   Which means that `git~1/` is a valid way to refer to `.git/`.
1386
 *
1387
 *   Note: Technically, `.git/` could receive the short name `git~2` if the
1388
 *   short name `git~1` were already used. In Git, however, we guarantee that
1389
 *   `.git` is the first item in a directory, therefore it will be associated
1390
 *   with the short name `git~1` (unless short names are disabled).
1391
 *
1392
 * - For yet other historical reasons, NTFS supports so-called "Alternate Data
1393
 *   Streams", i.e. metadata associated with a given file, referred to via
1394
 *   `<filename>:<stream-name>:<stream-type>`. There exists a default stream
1395
 *   type for directories, allowing `.git/` to be accessed via
1396
 *   `.git::$INDEX_ALLOCATION/`.
1397
 *
1398
 * When this function returns 1, it indicates that the specified file/directory
1399
 * name refers to a `.git` file or directory, or to any of these synonyms, and
1400
 * Git should therefore not track it.
1401
 *
1402
 * For performance reasons, _all_ Alternate Data Streams of `.git/` are
1403
 * forbidden, not just `::$INDEX_ALLOCATION`.
1404
 *
1405
 * This function is intended to be used by `git fsck` even on platforms where
1406
 * the backslash is a regular filename character, therefore it needs to handle
1407
 * backlash characters in the provided `name` specially: they are interpreted
1408
 * as directory separators.
1409
 */
1410
int is_ntfs_dotgit(const char *name)
1411
0
{
1412
0
  char c;
1413
1414
  /*
1415
   * Note that when we don't find `.git` or `git~1` we end up with `name`
1416
   * advanced partway through the string. That's okay, though, as we
1417
   * return immediately in those cases, without looking at `name` any
1418
   * further.
1419
   */
1420
0
  c = *(name++);
1421
0
  if (c == '.') {
1422
    /* .git */
1423
0
    if (((c = *(name++)) != 'g' && c != 'G') ||
1424
0
        ((c = *(name++)) != 'i' && c != 'I') ||
1425
0
        ((c = *(name++)) != 't' && c != 'T'))
1426
0
      return 0;
1427
0
  } else if (c == 'g' || c == 'G') {
1428
    /* git ~1 */
1429
0
    if (((c = *(name++)) != 'i' && c != 'I') ||
1430
0
        ((c = *(name++)) != 't' && c != 'T') ||
1431
0
        *(name++) != '~' ||
1432
0
        *(name++) != '1')
1433
0
      return 0;
1434
0
  } else
1435
0
    return 0;
1436
1437
0
  for (;;) {
1438
0
    c = *(name++);
1439
0
    if (!c || is_xplatform_dir_sep(c) || c == ':')
1440
0
      return 1;
1441
0
    if (c != '.' && c != ' ')
1442
0
      return 0;
1443
0
  }
1444
0
}
1445
1446
static int is_ntfs_dot_generic(const char *name,
1447
             const char *dotgit_name,
1448
             size_t len,
1449
             const char *dotgit_ntfs_shortname_prefix)
1450
0
{
1451
0
  int saw_tilde;
1452
0
  size_t i;
1453
1454
0
  if ((name[0] == '.' && !strncasecmp(name + 1, dotgit_name, len))) {
1455
0
    i = len + 1;
1456
0
only_spaces_and_periods:
1457
0
    for (;;) {
1458
0
      char c = name[i++];
1459
0
      if (!c || c == ':')
1460
0
        return 1;
1461
0
      if (c != ' ' && c != '.')
1462
0
        return 0;
1463
0
    }
1464
0
  }
1465
1466
  /*
1467
   * Is it a regular NTFS short name, i.e. shortened to 6 characters,
1468
   * followed by ~1, ... ~4?
1469
   */
1470
0
  if (!strncasecmp(name, dotgit_name, 6) && name[6] == '~' &&
1471
0
      name[7] >= '1' && name[7] <= '4') {
1472
0
    i = 8;
1473
0
    goto only_spaces_and_periods;
1474
0
  }
1475
1476
  /*
1477
   * Is it a fall-back NTFS short name (for details, see
1478
   * https://en.wikipedia.org/wiki/8.3_filename?
1479
   */
1480
0
  for (i = 0, saw_tilde = 0; i < 8; i++)
1481
0
    if (name[i] == '\0')
1482
0
      return 0;
1483
0
    else if (saw_tilde) {
1484
0
      if (name[i] < '0' || name[i] > '9')
1485
0
        return 0;
1486
0
    } else if (name[i] == '~') {
1487
0
      if (name[++i] < '1' || name[i] > '9')
1488
0
        return 0;
1489
0
      saw_tilde = 1;
1490
0
    } else if (i >= 6)
1491
0
      return 0;
1492
0
    else if (name[i] & 0x80) {
1493
      /*
1494
       * We know our needles contain only ASCII, so we clamp
1495
       * here to make the results of tolower() sane.
1496
       */
1497
0
      return 0;
1498
0
    } else if (tolower(name[i]) != dotgit_ntfs_shortname_prefix[i])
1499
0
      return 0;
1500
1501
0
  goto only_spaces_and_periods;
1502
0
}
1503
1504
/*
1505
 * Inline helper to make sure compiler resolves strlen() on literals at
1506
 * compile time.
1507
 */
1508
static inline int is_ntfs_dot_str(const char *name, const char *dotgit_name,
1509
          const char *dotgit_ntfs_shortname_prefix)
1510
0
{
1511
0
  return is_ntfs_dot_generic(name, dotgit_name, strlen(dotgit_name),
1512
0
           dotgit_ntfs_shortname_prefix);
1513
0
}
1514
1515
int is_ntfs_dotgitmodules(const char *name)
1516
0
{
1517
0
  return is_ntfs_dot_str(name, "gitmodules", "gi7eba");
1518
0
}
1519
1520
int is_ntfs_dotgitignore(const char *name)
1521
0
{
1522
0
  return is_ntfs_dot_str(name, "gitignore", "gi250a");
1523
0
}
1524
1525
int is_ntfs_dotgitattributes(const char *name)
1526
0
{
1527
0
  return is_ntfs_dot_str(name, "gitattributes", "gi7d29");
1528
0
}
1529
1530
int is_ntfs_dotmailmap(const char *name)
1531
0
{
1532
0
  return is_ntfs_dot_str(name, "mailmap", "maba30");
1533
0
}
1534
1535
int looks_like_command_line_option(const char *str)
1536
0
{
1537
0
  return str && str[0] == '-';
1538
0
}
1539
1540
char *xdg_config_home_for(const char *subdir, const char *filename)
1541
0
{
1542
0
  const char *home, *config_home;
1543
1544
0
  assert(subdir);
1545
0
  assert(filename);
1546
0
  config_home = getenv("XDG_CONFIG_HOME");
1547
0
  if (config_home && *config_home)
1548
0
    return mkpathdup("%s/%s/%s", config_home, subdir, filename);
1549
1550
0
  home = getenv("HOME");
1551
0
  if (home)
1552
0
    return mkpathdup("%s/.config/%s/%s", home, subdir, filename);
1553
1554
0
  return NULL;
1555
0
}
1556
1557
char *xdg_config_home(const char *filename)
1558
0
{
1559
0
  return xdg_config_home_for("git", filename);
1560
0
}
1561
1562
char *xdg_cache_home(const char *filename)
1563
0
{
1564
0
  const char *home, *cache_home;
1565
1566
0
  assert(filename);
1567
0
  cache_home = getenv("XDG_CACHE_HOME");
1568
0
  if (cache_home && *cache_home)
1569
0
    return mkpathdup("%s/git/%s", cache_home, filename);
1570
1571
0
  home = getenv("HOME");
1572
0
  if (home)
1573
0
    return mkpathdup("%s/.cache/git/%s", home, filename);
1574
0
  return NULL;
1575
0
}
1576
1577
REPO_GIT_PATH_FUNC(squash_msg, "SQUASH_MSG")
1578
REPO_GIT_PATH_FUNC(merge_msg, "MERGE_MSG")
1579
REPO_GIT_PATH_FUNC(merge_rr, "MERGE_RR")
1580
REPO_GIT_PATH_FUNC(merge_mode, "MERGE_MODE")
1581
REPO_GIT_PATH_FUNC(merge_head, "MERGE_HEAD")
1582
REPO_GIT_PATH_FUNC(fetch_head, "FETCH_HEAD")
1583
REPO_GIT_PATH_FUNC(shallow, "shallow")