Coverage Report

Created: 2026-12-01 06:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libgit2/src/util/fs_path.c
Line
Count
Source
1
/*
2
 * Copyright (C) the libgit2 contributors. All rights reserved.
3
 *
4
 * This file is part of libgit2, distributed under the GNU GPL v2 with
5
 * a Linking Exception. For full terms see the included COPYING file.
6
 */
7
8
#include "fs_path.h"
9
10
#include "git2_util.h"
11
#include "futils.h"
12
#include "posix.h"
13
#ifdef GIT_WIN32
14
#include "win32/posix.h"
15
#include "win32/w32_buffer.h"
16
#include "win32/w32_util.h"
17
#include "win32/version.h"
18
#include <aclapi.h>
19
#else
20
#include <dirent.h>
21
#endif
22
#include <stdio.h>
23
#include <ctype.h>
24
25
0
#define ensure_error_set(code) do { \
26
0
    const git_error *e = git_error_last(); \
27
0
    if (!e || !e->message) \
28
0
      git_error_set(e ? e->klass : GIT_ERROR_CALLBACK, \
29
0
        "filesystem callback returned %d", code); \
30
0
  } while(0)
31
32
static int dos_drive_prefix_length(const char *path)
33
48.8k
{
34
48.8k
  int i;
35
36
  /*
37
   * Does it start with an ASCII letter (i.e. highest bit not set),
38
   * followed by a colon?
39
   */
40
48.8k
  if (!(0x80 & (unsigned char)*path))
41
48.8k
    return *path && path[1] == ':' ? 2 : 0;
42
43
  /*
44
   * While drive letters must be letters of the English alphabet, it is
45
   * possible to assign virtually _any_ Unicode character via `subst` as
46
   * a drive letter to "virtual drives". Even `1`, or `ä`. Or fun stuff
47
   * like this:
48
   *
49
   *  subst ֍: %USERPROFILE%\Desktop
50
   */
51
0
  for (i = 1; i < 4 && (0x80 & (unsigned char)path[i]); i++)
52
0
    ; /* skip first UTF-8 character */
53
0
  return path[i] == ':' ? i + 1 : 0;
54
48.8k
}
55
56
#ifdef GIT_WIN32
57
static bool looks_like_network_computer_name(const char *path, int pos)
58
{
59
  if (pos < 3)
60
    return false;
61
62
  if (path[0] != '/' || path[1] != '/')
63
    return false;
64
65
  while (pos-- > 2) {
66
    if (path[pos] == '/')
67
      return false;
68
  }
69
70
  return true;
71
}
72
#endif
73
74
/*
75
 * Based on the Android implementation, BSD licensed.
76
 * http://android.git.kernel.org/
77
 *
78
 * Copyright (C) 2008 The Android Open Source Project
79
 * All rights reserved.
80
 *
81
 * Redistribution and use in source and binary forms, with or without
82
 * modification, are permitted provided that the following conditions
83
 * are met:
84
 * * Redistributions of source code must retain the above copyright
85
 *   notice, this list of conditions and the following disclaimer.
86
 * * Redistributions in binary form must reproduce the above copyright
87
 *   notice, this list of conditions and the following disclaimer in
88
 *   the documentation and/or other materials provided with the
89
 *   distribution.
90
 *
91
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
92
 * AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
93
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
94
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
95
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
96
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
97
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
98
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
99
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
100
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
101
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
102
 * SUCH DAMAGE.
103
 */
104
int git_fs_path_basename_r(git_str *buffer, const char *path)
105
0
{
106
0
  const char *endp, *startp;
107
0
  int len, result;
108
109
  /* Empty or NULL string gets treated as "." */
110
0
  if (path == NULL || *path == '\0') {
111
0
    startp = ".";
112
0
    len = 1;
113
0
    goto Exit;
114
0
  }
115
116
  /* Strip trailing slashes */
117
0
  endp = path + strlen(path) - 1;
118
0
  while (endp > path && *endp == '/')
119
0
    endp--;
120
121
  /* All slashes becomes "/" */
122
0
  if (endp == path && *endp == '/') {
123
0
    startp = "/";
124
0
    len = 1;
125
0
    goto Exit;
126
0
  }
127
128
  /* Find the start of the base */
129
0
  startp = endp;
130
0
  while (startp > path && *(startp - 1) != '/')
131
0
    startp--;
132
133
  /* Cast is safe because max path < max int */
134
0
  len = (int)(endp - startp + 1);
135
136
0
Exit:
137
0
  result = len;
138
139
0
  if (buffer != NULL && git_str_set(buffer, startp, len) < 0)
140
0
    return -1;
141
142
0
  return result;
143
0
}
144
145
/*
146
 * Determine if the path is a Windows prefix and, if so, returns
147
 * its actual length. If it is not a prefix, returns -1.
148
 */
149
static int win32_prefix_length(const char *path, int len)
150
32
{
151
32
#ifndef GIT_WIN32
152
32
  GIT_UNUSED(path);
153
32
  GIT_UNUSED(len);
154
#else
155
  /*
156
   * Mimic unix behavior where '/.git' returns '/': 'C:/.git'
157
   * will return 'C:/' here
158
   */
159
  if (dos_drive_prefix_length(path) == len)
160
    return len;
161
162
  /*
163
   * Similarly checks if we're dealing with a network computer name
164
   * '//computername/.git' will return '//computername/'
165
   */
166
  if (looks_like_network_computer_name(path, len))
167
    return len;
168
#endif
169
170
32
  return -1;
171
32
}
172
173
/*
174
 * Based on the Android implementation, BSD licensed.
175
 * Check http://android.git.kernel.org/
176
 */
177
int git_fs_path_dirname_r(git_str *buffer, const char *path)
178
16
{
179
16
  const char *endp;
180
16
  int is_prefix = 0, len;
181
182
  /* Empty or NULL string gets treated as "." */
183
16
  if (path == NULL || *path == '\0') {
184
0
    path = ".";
185
0
    len = 1;
186
0
    goto Exit;
187
0
  }
188
189
  /* Strip trailing slashes */
190
16
  endp = path + strlen(path) - 1;
191
18
  while (endp > path && *endp == '/')
192
2
    endp--;
193
194
16
  if (endp - path + 1 > INT_MAX) {
195
0
    git_error_set(GIT_ERROR_INVALID, "path too long");
196
0
    return -1;
197
0
  }
198
199
16
  if ((len = win32_prefix_length(path, (int)(endp - path + 1))) > 0) {
200
0
    is_prefix = 1;
201
0
    goto Exit;
202
0
  }
203
204
  /* Find the start of the dir */
205
124
  while (endp > path && *endp != '/')
206
108
    endp--;
207
208
  /* Either the dir is "/" or there are no slashes */
209
16
  if (endp == path) {
210
0
    path = (*endp == '/') ? "/" : ".";
211
0
    len = 1;
212
0
    goto Exit;
213
0
  }
214
215
16
  do {
216
16
    endp--;
217
16
  } while (endp > path && *endp == '/');
218
219
16
  if (endp - path + 1 > INT_MAX) {
220
0
    git_error_set(GIT_ERROR_INVALID, "path too long");
221
0
    return -1;
222
0
  }
223
224
16
  if ((len = win32_prefix_length(path, (int)(endp - path + 1))) > 0) {
225
0
    is_prefix = 1;
226
0
    goto Exit;
227
0
  }
228
229
  /* Cast is safe because max path < max int */
230
16
  len = (int)(endp - path + 1);
231
232
16
Exit:
233
16
  if (buffer) {
234
16
    if (git_str_set(buffer, path, len) < 0)
235
0
      return -1;
236
16
    if (is_prefix && git_str_putc(buffer, '/') < 0)
237
0
      return -1;
238
16
  }
239
240
16
  return len;
241
16
}
242
243
244
char *git_fs_path_dirname(const char *path)
245
0
{
246
0
  git_str buf = GIT_STR_INIT;
247
0
  char *dirname;
248
249
0
  git_fs_path_dirname_r(&buf, path);
250
0
  dirname = git_str_detach(&buf);
251
0
  git_str_dispose(&buf); /* avoid memleak if error occurs */
252
253
0
  return dirname;
254
0
}
255
256
char *git_fs_path_basename(const char *path)
257
0
{
258
0
  git_str buf = GIT_STR_INIT;
259
0
  char *basename;
260
261
0
  git_fs_path_basename_r(&buf, path);
262
0
  basename = git_str_detach(&buf);
263
0
  git_str_dispose(&buf); /* avoid memleak if error occurs */
264
265
0
  return basename;
266
0
}
267
268
size_t git_fs_path_basename_offset(git_str *buffer)
269
0
{
270
0
  ssize_t slash;
271
272
0
  if (!buffer || buffer->size <= 0)
273
0
    return 0;
274
275
0
  slash = git_str_rfind_next(buffer, '/');
276
277
0
  if (slash >= 0 && buffer->ptr[slash] == '/')
278
0
    return (size_t)(slash + 1);
279
280
0
  return 0;
281
0
}
282
283
int git_fs_path_root(const char *path)
284
48.8k
{
285
48.8k
  int offset = 0, prefix_len;
286
287
  /* Does the root of the path look like a windows drive ? */
288
48.8k
  if ((prefix_len = dos_drive_prefix_length(path)))
289
0
    offset += prefix_len;
290
291
#ifdef GIT_WIN32
292
  /* Are we dealing with a windows network path? */
293
  else if ((path[0] == '/' && path[1] == '/' && path[2] != '/') ||
294
    (path[0] == '\\' && path[1] == '\\' && path[2] != '\\'))
295
  {
296
    offset += 2;
297
298
    /* Skip the computer name segment */
299
    while (path[offset] && path[offset] != '/' && path[offset] != '\\')
300
      offset++;
301
  }
302
303
  if (path[offset] == '\\')
304
    return offset;
305
#endif
306
307
48.8k
  if (path[offset] == '/')
308
48.8k
    return offset;
309
310
15
  return -1; /* Not a real error - signals that path is not rooted */
311
48.8k
}
312
313
static void path_trim_slashes(git_str *path)
314
48.7k
{
315
48.7k
  int ceiling = git_fs_path_root(path->ptr) + 1;
316
317
48.7k
  if (ceiling < 0)
318
0
    return;
319
320
97.5k
  while (path->size > (size_t)ceiling) {
321
97.5k
    if (path->ptr[path->size-1] != '/')
322
48.7k
      break;
323
324
48.7k
    path->ptr[path->size-1] = '\0';
325
48.7k
    path->size--;
326
48.7k
  }
327
48.7k
}
328
329
int git_fs_path_join_unrooted(
330
  git_str *path_out, const char *path, const char *base, ssize_t *root_at)
331
15
{
332
15
  ssize_t root;
333
334
15
  GIT_ASSERT_ARG(path_out);
335
15
  GIT_ASSERT_ARG(path);
336
337
15
  root = (ssize_t)git_fs_path_root(path);
338
339
15
  if (base != NULL && root < 0) {
340
15
    if (git_str_joinpath(path_out, base, path) < 0)
341
0
      return -1;
342
343
15
    root = (ssize_t)strlen(base);
344
15
  } else {
345
0
    if (git_str_sets(path_out, path) < 0)
346
0
      return -1;
347
348
0
    if (root < 0)
349
0
      root = 0;
350
0
    else if (base)
351
0
      git_fs_path_equal_or_prefixed(base, path, &root);
352
0
  }
353
354
15
  if (root_at)
355
15
    *root_at = root;
356
357
15
  return 0;
358
15
}
359
360
void git_fs_path_squash_slashes(git_str *path)
361
0
{
362
0
  char *p, *q;
363
364
0
  if (path->size == 0)
365
0
    return;
366
367
0
  for (p = path->ptr, q = path->ptr; *q; p++, q++) {
368
0
    *p = *q;
369
370
0
    while (*q == '/' && *(q+1) == '/') {
371
0
      path->size--;
372
0
      q++;
373
0
    }
374
0
  }
375
376
0
  *p = '\0';
377
0
}
378
379
int git_fs_path_prettify(git_str *path_out, const char *path, const char *base)
380
4
{
381
4
  char buf[GIT_PATH_MAX];
382
383
4
  GIT_ASSERT_ARG(path_out);
384
4
  GIT_ASSERT_ARG(path);
385
386
  /* construct path if needed */
387
4
  if (base != NULL && git_fs_path_root(path) < 0) {
388
0
    if (git_str_joinpath(path_out, base, path) < 0)
389
0
      return -1;
390
0
    path = path_out->ptr;
391
0
  }
392
393
4
  if (p_realpath(path, buf) == NULL) {
394
    /* git_error_set resets the errno when dealing with a GIT_ERROR_OS kind of error */
395
0
    int error = (errno == ENOENT || errno == ENOTDIR) ? GIT_ENOTFOUND : -1;
396
0
    git_error_set(GIT_ERROR_OS, "failed to resolve path '%s'", path);
397
398
0
    git_str_clear(path_out);
399
400
0
    return error;
401
0
  }
402
403
4
  return git_str_sets(path_out, buf);
404
4
}
405
406
int git_fs_path_prettify_dir(git_str *path_out, const char *path, const char *base)
407
2
{
408
2
  int error = git_fs_path_prettify(path_out, path, base);
409
2
  return (error < 0) ? error : git_fs_path_to_dir(path_out);
410
2
}
411
412
int git_fs_path_to_dir(git_str *path)
413
70
{
414
70
  if (path->asize > 0 &&
415
70
    git_str_len(path) > 0 &&
416
70
    path->ptr[git_str_len(path) - 1] != '/')
417
40
    git_str_putc(path, '/');
418
419
70
  return git_str_oom(path) ? -1 : 0;
420
70
}
421
422
size_t git_fs_path_dirlen(const char *path)
423
0
{
424
0
  size_t len = strlen(path);
425
426
0
  while (len > 1 && path[len - 1] == '/')
427
0
    len--;
428
429
0
  return len;
430
0
}
431
432
void git_fs_path_string_to_dir(char *path, size_t size)
433
0
{
434
0
  size_t end = strlen(path);
435
436
0
  if (end && path[end - 1] != '/' && end < size) {
437
0
    path[end] = '/';
438
0
    path[end + 1] = '\0';
439
0
  }
440
0
}
441
442
int git__percent_decode(git_str *decoded_out, const char *input)
443
0
{
444
0
  int len, hi, lo, i;
445
446
0
  GIT_ASSERT_ARG(decoded_out);
447
0
  GIT_ASSERT_ARG(input);
448
449
0
  len = (int)strlen(input);
450
0
  git_str_clear(decoded_out);
451
452
0
  for(i = 0; i < len; i++)
453
0
  {
454
0
    char c = input[i];
455
456
0
    if (c != '%')
457
0
      goto append;
458
459
0
    if (i >= len - 2)
460
0
      goto append;
461
462
0
    hi = git__fromhex(input[i + 1]);
463
0
    lo = git__fromhex(input[i + 2]);
464
465
0
    if (hi < 0 || lo < 0)
466
0
      goto append;
467
468
0
    c = (char)(hi << 4 | lo);
469
0
    i += 2;
470
471
0
append:
472
0
    if (git_str_putc(decoded_out, c) < 0)
473
0
      return -1;
474
0
  }
475
476
0
  return 0;
477
0
}
478
479
static int error_invalid_local_file_uri(const char *uri)
480
0
{
481
0
  git_error_set(GIT_ERROR_CONFIG, "'%s' is not a valid local file URI", uri);
482
0
  return -1;
483
0
}
484
485
static int local_file_url_prefixlen(const char *file_url)
486
0
{
487
0
  int len = -1;
488
489
0
  if (git__prefixcmp(file_url, "file://") == 0) {
490
0
    if (file_url[7] == '/')
491
0
      len = 8;
492
0
    else if (git__prefixcmp(file_url + 7, "localhost/") == 0)
493
0
      len = 17;
494
0
  }
495
496
0
  return len;
497
0
}
498
499
bool git_fs_path_is_local_file_url(const char *file_url)
500
0
{
501
0
  return (local_file_url_prefixlen(file_url) > 0);
502
0
}
503
504
int git_fs_path_fromurl(git_str *local_path_out, const char *file_url)
505
0
{
506
0
  int offset;
507
508
0
  GIT_ASSERT_ARG(local_path_out);
509
0
  GIT_ASSERT_ARG(file_url);
510
511
0
  if ((offset = local_file_url_prefixlen(file_url)) < 0 ||
512
0
    file_url[offset] == '\0' || file_url[offset] == '/')
513
0
    return error_invalid_local_file_uri(file_url);
514
515
0
#ifndef GIT_WIN32
516
0
  offset--; /* A *nix absolute path starts with a forward slash */
517
0
#endif
518
519
0
  git_str_clear(local_path_out);
520
0
  return git__percent_decode(local_path_out, file_url + offset);
521
0
}
522
523
int git_fs_path_walk_up(
524
  git_str *path,
525
  const char *ceiling,
526
  int (*cb)(void *data, const char *),
527
  void *data)
528
0
{
529
0
  int error = 0;
530
0
  git_str iter;
531
0
  ssize_t stop = 0, scan;
532
0
  char oldc = '\0';
533
534
0
  GIT_ASSERT_ARG(path);
535
0
  GIT_ASSERT_ARG(cb);
536
537
0
  if (ceiling != NULL) {
538
0
    if (git__prefixcmp(path->ptr, ceiling) == 0)
539
0
      stop = (ssize_t)strlen(ceiling);
540
0
    else
541
0
      stop = git_str_len(path);
542
0
  }
543
0
  scan = git_str_len(path);
544
545
  /* empty path: yield only once */
546
0
  if (!scan) {
547
0
    error = cb(data, "");
548
0
    if (error)
549
0
      ensure_error_set(error);
550
0
    return error;
551
0
  }
552
553
0
  iter.ptr = path->ptr;
554
0
  iter.size = git_str_len(path);
555
0
  iter.asize = path->asize;
556
557
0
  while (scan >= stop) {
558
0
    error = cb(data, iter.ptr);
559
0
    iter.ptr[scan] = oldc;
560
561
0
    if (error) {
562
0
      ensure_error_set(error);
563
0
      break;
564
0
    }
565
566
0
    scan = git_str_rfind_next(&iter, '/');
567
0
    if (scan >= 0) {
568
0
      scan++;
569
0
      oldc = iter.ptr[scan];
570
0
      iter.size = scan;
571
0
      iter.ptr[scan] = '\0';
572
0
    }
573
0
  }
574
575
0
  if (scan >= 0)
576
0
    iter.ptr[scan] = oldc;
577
578
  /* relative path: yield for the last component */
579
0
  if (!error && stop == 0 && iter.ptr[0] != '/') {
580
0
    error = cb(data, "");
581
0
    if (error)
582
0
      ensure_error_set(error);
583
0
  }
584
585
0
  return error;
586
0
}
587
588
bool git_fs_path_exists(const char *path)
589
44
{
590
44
  GIT_ASSERT_ARG_WITH_RETVAL(path, false);
591
44
  return p_access(path, F_OK) == 0;
592
44
}
593
594
bool git_fs_path_isdir(const char *path)
595
28
{
596
28
  struct stat st;
597
28
  if (p_stat(path, &st) < 0)
598
17
    return false;
599
600
11
  return S_ISDIR(st.st_mode) != 0;
601
28
}
602
603
bool git_fs_path_isfile(const char *path)
604
10
{
605
10
  struct stat st;
606
607
10
  GIT_ASSERT_ARG_WITH_RETVAL(path, false);
608
10
  if (p_stat(path, &st) < 0)
609
8
    return false;
610
611
2
  return S_ISREG(st.st_mode) != 0;
612
10
}
613
614
#ifdef GIT_WIN32
615
616
bool git_fs_path_isexecutable(const char *path)
617
{
618
  struct stat st;
619
620
  GIT_ASSERT_ARG_WITH_RETVAL(path, false);
621
622
  if (git__suffixcmp_icase(path, ".exe") != 0 &&
623
      git__suffixcmp_icase(path, ".cmd") != 0)
624
    return false;
625
626
  return (p_stat(path, &st) == 0);
627
}
628
629
#else
630
631
bool git_fs_path_isexecutable(const char *path)
632
0
{
633
0
  struct stat st;
634
635
0
  GIT_ASSERT_ARG_WITH_RETVAL(path, false);
636
0
  if (p_stat(path, &st) < 0)
637
0
    return false;
638
639
0
  return S_ISREG(st.st_mode) != 0 &&
640
0
         ((st.st_mode & S_IXUSR) != 0);
641
0
}
642
643
#endif
644
645
bool git_fs_path_islink(const char *path)
646
0
{
647
0
  struct stat st;
648
649
0
  GIT_ASSERT_ARG_WITH_RETVAL(path, false);
650
0
  if (p_lstat(path, &st) < 0)
651
0
    return false;
652
653
0
  return S_ISLNK(st.st_mode) != 0;
654
0
}
655
656
#ifdef GIT_WIN32
657
658
bool git_fs_path_is_empty_dir(const char *path)
659
{
660
  git_win32_path filter_w;
661
  bool empty = false;
662
663
  if (git_win32__findfirstfile_filter(filter_w, path)) {
664
    WIN32_FIND_DATAW findData;
665
    HANDLE hFind = FindFirstFileW(filter_w, &findData);
666
667
    /* FindFirstFile will fail if there are no children to the given
668
     * path, which can happen if the given path is a file (and obviously
669
     * has no children) or if the given path is an empty mount point.
670
     * (Most directories have at least directory entries '.' and '..',
671
     * but ridiculously another volume mounted in another drive letter's
672
     * path space do not, and thus have nothing to enumerate.)  If
673
     * FindFirstFile fails, check if this is a directory-like thing
674
     * (a mount point).
675
     */
676
    if (hFind == INVALID_HANDLE_VALUE)
677
      return git_fs_path_isdir(path);
678
679
    /* If the find handle was created successfully, then it's a directory */
680
    empty = true;
681
682
    do {
683
      /* Allow the enumeration to return . and .. and still be considered
684
       * empty. In the special case of drive roots (i.e. C:\) where . and
685
       * .. do not occur, we can still consider the path to be an empty
686
       * directory if there's nothing there. */
687
      if (!git_fs_path_is_dot_or_dotdotW(findData.cFileName)) {
688
        empty = false;
689
        break;
690
      }
691
    } while (FindNextFileW(hFind, &findData));
692
693
    FindClose(hFind);
694
  }
695
696
  return empty;
697
}
698
699
#else
700
701
static int path_found_entry(void *payload, git_str *path)
702
0
{
703
0
  GIT_UNUSED(payload);
704
0
  return !git_fs_path_is_dot_or_dotdot(path->ptr);
705
0
}
706
707
bool git_fs_path_is_empty_dir(const char *path)
708
0
{
709
0
  int error;
710
0
  git_str dir = GIT_STR_INIT;
711
712
0
  if (!git_fs_path_isdir(path))
713
0
    return false;
714
715
0
  if ((error = git_str_sets(&dir, path)) != 0)
716
0
    git_error_clear();
717
0
  else
718
0
    error = git_fs_path_direach(&dir, 0, path_found_entry, NULL);
719
720
0
  git_str_dispose(&dir);
721
722
0
  return !error;
723
0
}
724
725
#endif
726
727
int git_fs_path_set_error(int errno_value, const char *path, const char *action)
728
13.9k
{
729
13.9k
  switch (errno_value) {
730
13.8k
  case ENOENT:
731
13.8k
  case ENOTDIR:
732
13.8k
    git_error_set(GIT_ERROR_OS, "could not find '%s' to %s", path, action);
733
13.8k
    return GIT_ENOTFOUND;
734
735
0
  case EINVAL:
736
11
  case ENAMETOOLONG:
737
11
    git_error_set(GIT_ERROR_OS, "invalid path for filesystem '%s'", path);
738
11
    return GIT_EINVALIDSPEC;
739
740
0
  case EEXIST:
741
0
    git_error_set(GIT_ERROR_OS, "failed %s - '%s' already exists", action, path);
742
0
    return GIT_EEXISTS;
743
744
0
  case EACCES:
745
0
    git_error_set(GIT_ERROR_OS, "failed %s - '%s' is locked", action, path);
746
0
    return GIT_ELOCKED;
747
748
0
  default:
749
0
    git_error_set(GIT_ERROR_OS, "could not %s '%s'", action, path);
750
0
    return -1;
751
13.9k
  }
752
13.9k
}
753
754
int git_fs_path_lstat(const char *path, struct stat *st)
755
32.5k
{
756
32.5k
  if (p_lstat(path, st) == 0)
757
32.5k
    return 0;
758
759
0
  return git_fs_path_set_error(errno, path, "stat");
760
32.5k
}
761
762
static bool _check_dir_contents(
763
  git_str *dir,
764
  const char *sub,
765
  bool (*predicate)(const char *))
766
12
{
767
12
  bool result;
768
12
  size_t dir_size = git_str_len(dir);
769
12
  size_t sub_size = strlen(sub);
770
12
  size_t alloc_size;
771
772
  /* leave base valid even if we could not make space for subdir */
773
12
  if (GIT_ADD_SIZET_OVERFLOW(&alloc_size, dir_size, sub_size) ||
774
12
    GIT_ADD_SIZET_OVERFLOW(&alloc_size, alloc_size, 2) ||
775
12
    git_str_try_grow(dir, alloc_size, false) < 0)
776
0
    return false;
777
778
  /* save excursion */
779
12
  if (git_str_joinpath(dir, dir->ptr, sub) < 0)
780
0
    return false;
781
782
12
  result = predicate(dir->ptr);
783
784
  /* restore path */
785
12
  git_str_truncate(dir, dir_size);
786
12
  return result;
787
12
}
788
789
bool git_fs_path_contains(git_str *dir, const char *item)
790
0
{
791
0
  return _check_dir_contents(dir, item, &git_fs_path_exists);
792
0
}
793
794
bool git_fs_path_contains_dir(git_str *base, const char *subdir)
795
4
{
796
4
  return _check_dir_contents(base, subdir, &git_fs_path_isdir);
797
4
}
798
799
bool git_fs_path_contains_file(git_str *base, const char *file)
800
8
{
801
8
  return _check_dir_contents(base, file, &git_fs_path_isfile);
802
8
}
803
804
int git_fs_path_find_dir(git_str *dir)
805
0
{
806
0
  int error = 0;
807
0
  char buf[GIT_PATH_MAX];
808
809
0
  if (p_realpath(dir->ptr, buf) != NULL)
810
0
    error = git_str_sets(dir, buf);
811
812
  /* call dirname if this is not a directory */
813
0
  if (!error) /* && git_fs_path_isdir(dir->ptr) == false) */
814
0
    error = (git_fs_path_dirname_r(dir, dir->ptr) < 0) ? -1 : 0;
815
816
0
  if (!error)
817
0
    error = git_fs_path_to_dir(dir);
818
819
0
  return error;
820
0
}
821
822
int git_fs_path_resolve_relative(git_str *path, size_t ceiling)
823
0
{
824
0
  char *base, *to, *from, *next;
825
0
  size_t len;
826
827
0
  GIT_ERROR_CHECK_ALLOC_STR(path);
828
829
0
  if (ceiling > path->size)
830
0
    ceiling = path->size;
831
832
  /* recognize drive prefixes, etc. that should not be backed over */
833
0
  if (ceiling == 0)
834
0
    ceiling = git_fs_path_root(path->ptr) + 1;
835
836
  /* recognize URL prefixes that should not be backed over */
837
0
  if (ceiling == 0) {
838
0
    for (next = path->ptr; *next && git__isalpha(*next); ++next);
839
0
    if (next[0] == ':' && next[1] == '/' && next[2] == '/')
840
0
      ceiling = (next + 3) - path->ptr;
841
0
  }
842
843
0
  base = to = from = path->ptr + ceiling;
844
845
0
  while (*from) {
846
0
    for (next = from; *next && *next != '/'; ++next);
847
848
0
    len = next - from;
849
850
0
    if (len == 1 && from[0] == '.')
851
0
      /* do nothing with singleton dot */;
852
853
0
    else if (len == 2 && from[0] == '.' && from[1] == '.') {
854
      /* error out if trying to up one from a hard base */
855
0
      if (to == base && ceiling != 0) {
856
0
        git_error_set(GIT_ERROR_INVALID,
857
0
          "cannot strip root component off url");
858
0
        return -1;
859
0
      }
860
861
      /* no more path segments to strip,
862
       * use '../' as a new base path */
863
0
      if (to == base) {
864
0
        if (*next == '/')
865
0
          len++;
866
867
0
        if (to != from)
868
0
          memmove(to, from, len);
869
870
0
        to += len;
871
        /* this is now the base, can't back up from a
872
         * relative prefix */
873
0
        base = to;
874
0
      } else {
875
        /* back up a path segment */
876
0
        while (to > base && to[-1] == '/') to--;
877
0
        while (to > base && to[-1] != '/') to--;
878
0
      }
879
0
    } else {
880
0
      if (*next == '/' && *from != '/')
881
0
        len++;
882
883
0
      if (to != from)
884
0
        memmove(to, from, len);
885
886
0
      to += len;
887
0
    }
888
889
0
    from += len;
890
891
0
    while (*from == '/') from++;
892
0
  }
893
894
0
  *to = '\0';
895
896
0
  path->size = to - path->ptr;
897
898
0
  return 0;
899
0
}
900
901
int git_fs_path_apply_relative(git_str *target, const char *relpath)
902
0
{
903
0
  return git_str_joinpath(target, git_str_cstr(target), relpath) ||
904
0
      git_fs_path_resolve_relative(target, 0);
905
0
}
906
907
int git_fs_path_cmp(
908
  const char *name1, size_t len1, int isdir1,
909
  const char *name2, size_t len2, int isdir2,
910
  int (*compare)(const char *, const char *, size_t))
911
0
{
912
0
  unsigned char c1, c2;
913
0
  size_t len = len1 < len2 ? len1 : len2;
914
0
  int cmp;
915
916
0
  cmp = compare(name1, name2, len);
917
0
  if (cmp)
918
0
    return cmp;
919
920
0
  c1 = name1[len];
921
0
  c2 = name2[len];
922
923
0
  if (c1 == '\0' && isdir1)
924
0
    c1 = '/';
925
926
0
  if (c2 == '\0' && isdir2)
927
0
    c2 = '/';
928
929
0
  return (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
930
0
}
931
932
size_t git_fs_path_common_dirlen(const char *one, const char *two)
933
0
{
934
0
  const char *p, *q, *dirsep = NULL;
935
936
0
  for (p = one, q = two; *p && *q; p++, q++) {
937
0
    if (*p == '/' && *q == '/')
938
0
      dirsep = p;
939
0
    else if (*p != *q)
940
0
      break;
941
0
  }
942
943
0
  return dirsep ? (dirsep - one) + 1 : 0;
944
0
}
945
946
int git_fs_path_make_relative(git_str *path, const char *parent)
947
0
{
948
0
  const char *p, *q, *p_dirsep, *q_dirsep;
949
0
  size_t plen = path->size, newlen, alloclen, depth = 1, i, offset;
950
951
0
  for (p_dirsep = p = path->ptr, q_dirsep = q = parent; *p && *q; p++, q++) {
952
0
    if (*p == '/' && *q == '/') {
953
0
      p_dirsep = p;
954
0
      q_dirsep = q;
955
0
    }
956
0
    else if (*p != *q)
957
0
      break;
958
0
  }
959
960
  /* need at least 1 common path segment */
961
0
  if ((p_dirsep == path->ptr || q_dirsep == parent) &&
962
0
    (*p_dirsep != '/' || *q_dirsep != '/')) {
963
0
    git_error_set(GIT_ERROR_INVALID,
964
0
      "%s is not a parent of %s", parent, path->ptr);
965
0
    return GIT_ENOTFOUND;
966
0
  }
967
968
0
  if (*p == '/' && !*q)
969
0
    p++;
970
0
  else if (!*p && *q == '/')
971
0
    q++;
972
0
  else if (!*p && !*q)
973
0
    return git_str_clear(path), 0;
974
0
  else {
975
0
    p = p_dirsep + 1;
976
0
    q = q_dirsep + 1;
977
0
  }
978
979
0
  plen -= (p - path->ptr);
980
981
0
  if (!*q)
982
0
    return git_str_set(path, p, plen);
983
984
0
  for (; (q = strchr(q, '/')) && *(q + 1); q++)
985
0
    depth++;
986
987
0
  GIT_ERROR_CHECK_ALLOC_MULTIPLY(&newlen, depth, 3);
988
0
  GIT_ERROR_CHECK_ALLOC_ADD(&newlen, newlen, plen);
989
990
0
  GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, newlen, 1);
991
992
  /* save the offset as we might realllocate the pointer */
993
0
  offset = p - path->ptr;
994
0
  if (git_str_try_grow(path, alloclen, 1) < 0)
995
0
    return -1;
996
0
  p = path->ptr + offset;
997
998
0
  memmove(path->ptr + (depth * 3), p, plen + 1);
999
1000
0
  for (i = 0; i < depth; i++)
1001
0
    memcpy(path->ptr + (i * 3), "../", 3);
1002
1003
0
  path->size = newlen;
1004
0
  return 0;
1005
0
}
1006
1007
bool git_fs_path_has_non_ascii(const char *path, size_t pathlen)
1008
0
{
1009
0
  const uint8_t *scan = (const uint8_t *)path, *end;
1010
1011
0
  for (end = scan + pathlen; scan < end; ++scan)
1012
0
    if (*scan & 0x80)
1013
0
      return true;
1014
1015
0
  return false;
1016
0
}
1017
1018
#ifdef GIT_I18N_ICONV
1019
1020
int git_fs_path_iconv_init_precompose(git_fs_path_iconv_t *ic)
1021
{
1022
  git_str_init(&ic->buf, 0);
1023
  ic->map = iconv_open(GIT_PATH_REPO_ENCODING, GIT_PATH_NATIVE_ENCODING);
1024
  return 0;
1025
}
1026
1027
void git_fs_path_iconv_clear(git_fs_path_iconv_t *ic)
1028
{
1029
  if (ic) {
1030
    if (ic->map != (iconv_t)-1)
1031
      iconv_close(ic->map);
1032
    git_str_dispose(&ic->buf);
1033
  }
1034
}
1035
1036
int git_fs_path_iconv(git_fs_path_iconv_t *ic, const char **in, size_t *inlen)
1037
{
1038
  char *nfd = (char*)*in, *nfc;
1039
  size_t nfdlen = *inlen, nfclen, wantlen = nfdlen, alloclen, rv;
1040
  int retry = 1;
1041
1042
  if (!ic || ic->map == (iconv_t)-1 ||
1043
    !git_fs_path_has_non_ascii(*in, *inlen))
1044
    return 0;
1045
1046
  git_str_clear(&ic->buf);
1047
1048
  while (1) {
1049
    GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, wantlen, 1);
1050
    if (git_str_grow(&ic->buf, alloclen) < 0)
1051
      return -1;
1052
1053
    nfc    = ic->buf.ptr   + ic->buf.size;
1054
    nfclen = ic->buf.asize - ic->buf.size;
1055
1056
    rv = iconv(ic->map, &nfd, &nfdlen, &nfc, &nfclen);
1057
1058
    ic->buf.size = (nfc - ic->buf.ptr);
1059
1060
    if (rv != (size_t)-1)
1061
      break;
1062
1063
    /* if we cannot convert the data (probably because iconv thinks
1064
     * it is not valid UTF-8 source data), then use original data
1065
     */
1066
    if (errno != E2BIG)
1067
      return 0;
1068
1069
    /* make space for 2x the remaining data to be converted
1070
     * (with per retry overhead to avoid infinite loops)
1071
     */
1072
    wantlen = ic->buf.size + max(nfclen, nfdlen) * 2 + (size_t)(retry * 4);
1073
1074
    if (retry++ > 4)
1075
      goto fail;
1076
  }
1077
1078
  ic->buf.ptr[ic->buf.size] = '\0';
1079
1080
  *in    = ic->buf.ptr;
1081
  *inlen = ic->buf.size;
1082
1083
  return 0;
1084
1085
fail:
1086
  git_error_set(GIT_ERROR_OS, "unable to convert unicode path data");
1087
  return -1;
1088
}
1089
1090
static const char *nfc_file = "\xC3\x85\x73\x74\x72\xC3\xB6\x6D";
1091
static const char *nfd_file = "\x41\xCC\x8A\x73\x74\x72\x6F\xCC\x88\x6D";
1092
1093
/* Check if the platform is decomposing unicode data for us.  We will
1094
 * emulate core Git and prefer to use precomposed unicode data internally
1095
 * on these platforms, composing the decomposed unicode on the fly.
1096
 *
1097
 * This mainly happens on the Mac where HDFS stores filenames as
1098
 * decomposed unicode.  Even on VFAT and SAMBA file systems, the Mac will
1099
 * return decomposed unicode from readdir() even when the actual
1100
 * filesystem is storing precomposed unicode.
1101
 */
1102
bool git_fs_path_does_decompose_unicode(const char *root)
1103
{
1104
  git_str nfc_path = GIT_STR_INIT;
1105
  git_str nfd_path = GIT_STR_INIT;
1106
  int fd;
1107
  bool found_decomposed = false;
1108
  size_t orig_len;
1109
  const char *trailer;
1110
1111
  /* Create a file using a precomposed path and then try to find it
1112
   * using the decomposed name.  If the lookup fails, then we will mark
1113
   * that we should precompose unicode for this repository.
1114
   */
1115
  if (git_str_joinpath(&nfc_path, root, nfc_file) < 0)
1116
    goto done;
1117
1118
  /* record original path length before trailer */
1119
  orig_len = nfc_path.size;
1120
1121
  if ((fd = git_futils_mktmp(&nfc_path, nfc_path.ptr, 0666)) < 0)
1122
    goto done;
1123
  p_close(fd);
1124
1125
  trailer = nfc_path.ptr + orig_len;
1126
1127
  /* try to look up as NFD path */
1128
  if (git_str_joinpath(&nfd_path, root, nfd_file) < 0 ||
1129
      git_str_puts(&nfd_path, trailer) < 0)
1130
    goto done;
1131
1132
  found_decomposed = git_fs_path_exists(nfd_path.ptr);
1133
1134
  /* remove temporary file (using original precomposed path) */
1135
  (void)p_unlink(nfc_path.ptr);
1136
1137
done:
1138
  git_str_dispose(&nfc_path);
1139
  git_str_dispose(&nfd_path);
1140
  return found_decomposed;
1141
}
1142
1143
#else
1144
1145
bool git_fs_path_does_decompose_unicode(const char *root)
1146
0
{
1147
0
  GIT_UNUSED(root);
1148
0
  return false;
1149
0
}
1150
1151
#endif
1152
1153
#if defined(__sun) || defined(__GNU__)
1154
typedef char path_dirent_data[sizeof(struct dirent) + FILENAME_MAX + 1];
1155
#else
1156
typedef struct dirent path_dirent_data;
1157
#endif
1158
1159
int git_fs_path_direach(
1160
  git_str *path,
1161
  uint32_t flags,
1162
  int (*fn)(void *, git_str *),
1163
  void *arg)
1164
29
{
1165
29
  int error = 0;
1166
29
  ssize_t wd_len;
1167
29
  DIR *dir;
1168
29
  struct dirent *de;
1169
1170
#ifdef GIT_I18N_ICONV
1171
  git_fs_path_iconv_t ic = GIT_PATH_ICONV_INIT;
1172
#endif
1173
1174
29
  GIT_UNUSED(flags);
1175
1176
29
  if (git_fs_path_to_dir(path) < 0)
1177
0
    return -1;
1178
1179
29
  wd_len = git_str_len(path);
1180
1181
29
  if ((dir = opendir(path->ptr)) == NULL) {
1182
0
    git_error_set(GIT_ERROR_OS, "failed to open directory '%s'", path->ptr);
1183
0
    if (errno == ENOENT)
1184
0
      return GIT_ENOTFOUND;
1185
1186
0
    return -1;
1187
0
  }
1188
1189
#ifdef GIT_I18N_ICONV
1190
  if ((flags & GIT_FS_PATH_DIR_PRECOMPOSE_UNICODE) != 0)
1191
    (void)git_fs_path_iconv_init_precompose(&ic);
1192
#endif
1193
1194
87
  while ((de = readdir(dir)) != NULL) {
1195
58
    const char *de_path = de->d_name;
1196
58
    size_t de_len = strlen(de_path);
1197
1198
58
    if (git_fs_path_is_dot_or_dotdot(de_path))
1199
58
      continue;
1200
1201
#ifdef GIT_I18N_ICONV
1202
    if ((error = git_fs_path_iconv(&ic, &de_path, &de_len)) < 0)
1203
      break;
1204
#endif
1205
1206
0
    if ((error = git_str_put(path, de_path, de_len)) < 0)
1207
0
      break;
1208
1209
0
    git_error_clear();
1210
0
    error = fn(arg, path);
1211
1212
0
    git_str_truncate(path, wd_len); /* restore path */
1213
1214
    /* Only set our own error if the callback did not set one already */
1215
0
    if (error != 0) {
1216
0
      if (!git_error_last())
1217
0
        ensure_error_set(error);
1218
1219
0
      break;
1220
0
    }
1221
0
  }
1222
1223
29
  closedir(dir);
1224
1225
#ifdef GIT_I18N_ICONV
1226
  git_fs_path_iconv_clear(&ic);
1227
#endif
1228
1229
29
  return error;
1230
29
}
1231
1232
#if defined(GIT_WIN32) && !defined(__MINGW32__)
1233
1234
/* Using _FIND_FIRST_EX_LARGE_FETCH may increase performance in Windows 7
1235
 * and better.
1236
 */
1237
#ifndef FIND_FIRST_EX_LARGE_FETCH
1238
# define FIND_FIRST_EX_LARGE_FETCH 2
1239
#endif
1240
1241
int git_fs_path_diriter_init(
1242
  git_fs_path_diriter *diriter,
1243
  const char *path,
1244
  unsigned int flags)
1245
{
1246
  git_win32_path path_filter;
1247
1248
  static int is_win7_or_later = -1;
1249
  if (is_win7_or_later < 0)
1250
    is_win7_or_later = git_has_win32_version(6, 1, 0);
1251
1252
  GIT_ASSERT_ARG(diriter);
1253
  GIT_ASSERT_ARG(path);
1254
1255
  memset(diriter, 0, sizeof(git_fs_path_diriter));
1256
  diriter->handle = INVALID_HANDLE_VALUE;
1257
1258
  if (git_str_puts(&diriter->path_utf8, path) < 0)
1259
    return -1;
1260
1261
  path_trim_slashes(&diriter->path_utf8);
1262
1263
  if (diriter->path_utf8.size == 0) {
1264
    git_error_set(GIT_ERROR_FILESYSTEM, "could not open directory '%s'", path);
1265
    return -1;
1266
  }
1267
1268
  if ((diriter->parent_len = git_win32_path_from_utf8(diriter->path, diriter->path_utf8.ptr)) < 0 ||
1269
      !git_win32__findfirstfile_filter(path_filter, diriter->path_utf8.ptr)) {
1270
    git_error_set(GIT_ERROR_OS, "could not parse the directory path '%s'", path);
1271
    return -1;
1272
  }
1273
1274
  diriter->handle = FindFirstFileExW(
1275
    path_filter,
1276
    is_win7_or_later ? FindExInfoBasic : FindExInfoStandard,
1277
    &diriter->current,
1278
    FindExSearchNameMatch,
1279
    NULL,
1280
    is_win7_or_later ? FIND_FIRST_EX_LARGE_FETCH : 0);
1281
1282
  if (diriter->handle == INVALID_HANDLE_VALUE) {
1283
    git_error_set(GIT_ERROR_OS, "could not open directory '%s'", path);
1284
    return -1;
1285
  }
1286
1287
  diriter->parent_utf8_len = diriter->path_utf8.size;
1288
  diriter->flags = flags;
1289
  return 0;
1290
}
1291
1292
static int diriter_update_paths(git_fs_path_diriter *diriter)
1293
{
1294
  size_t filename_len, path_len;
1295
1296
  filename_len = wcslen(diriter->current.cFileName);
1297
1298
  if (GIT_ADD_SIZET_OVERFLOW(&path_len, diriter->parent_len, filename_len) ||
1299
    GIT_ADD_SIZET_OVERFLOW(&path_len, path_len, 2))
1300
    return -1;
1301
1302
  if (path_len > GIT_WIN_PATH_UTF16) {
1303
    git_error_set(GIT_ERROR_FILESYSTEM,
1304
      "invalid path '%.*ls\\%ls' (path too long)",
1305
      diriter->parent_len, diriter->path, diriter->current.cFileName);
1306
    return -1;
1307
  }
1308
1309
  diriter->path[diriter->parent_len] = L'\\';
1310
  memcpy(&diriter->path[diriter->parent_len+1],
1311
    diriter->current.cFileName, filename_len * sizeof(wchar_t));
1312
  diriter->path[path_len-1] = L'\0';
1313
1314
  git_str_truncate(&diriter->path_utf8, diriter->parent_utf8_len);
1315
1316
  if (diriter->parent_utf8_len > 0 &&
1317
    diriter->path_utf8.ptr[diriter->parent_utf8_len-1] != '/')
1318
    git_str_putc(&diriter->path_utf8, '/');
1319
1320
  git_str_put_w(&diriter->path_utf8, diriter->current.cFileName, filename_len);
1321
1322
  if (git_str_oom(&diriter->path_utf8))
1323
    return -1;
1324
1325
  return 0;
1326
}
1327
1328
int git_fs_path_diriter_next(git_fs_path_diriter *diriter)
1329
{
1330
  bool skip_dot = !(diriter->flags & GIT_FS_PATH_DIR_INCLUDE_DOT_AND_DOTDOT);
1331
1332
  do {
1333
    /* Our first time through, we already have the data from
1334
     * FindFirstFileW.  Use it, otherwise get the next file.
1335
     */
1336
    if (!diriter->needs_next)
1337
      diriter->needs_next = 1;
1338
    else if (!FindNextFileW(diriter->handle, &diriter->current))
1339
      return GIT_ITEROVER;
1340
  } while (skip_dot && git_fs_path_is_dot_or_dotdotW(diriter->current.cFileName));
1341
1342
  if (diriter_update_paths(diriter) < 0)
1343
    return -1;
1344
1345
  return 0;
1346
}
1347
1348
int git_fs_path_diriter_filename(
1349
  const char **out,
1350
  size_t *out_len,
1351
  git_fs_path_diriter *diriter)
1352
{
1353
  GIT_ASSERT_ARG(out);
1354
  GIT_ASSERT_ARG(out_len);
1355
  GIT_ASSERT_ARG(diriter);
1356
  GIT_ASSERT(diriter->path_utf8.size > diriter->parent_utf8_len);
1357
1358
  *out = &diriter->path_utf8.ptr[diriter->parent_utf8_len+1];
1359
  *out_len = diriter->path_utf8.size - diriter->parent_utf8_len - 1;
1360
  return 0;
1361
}
1362
1363
int git_fs_path_diriter_fullpath(
1364
  const char **out,
1365
  size_t *out_len,
1366
  git_fs_path_diriter *diriter)
1367
{
1368
  GIT_ASSERT_ARG(out);
1369
  GIT_ASSERT_ARG(out_len);
1370
  GIT_ASSERT_ARG(diriter);
1371
1372
  *out = diriter->path_utf8.ptr;
1373
  *out_len = diriter->path_utf8.size;
1374
  return 0;
1375
}
1376
1377
int git_fs_path_diriter_stat(struct stat *out, git_fs_path_diriter *diriter)
1378
{
1379
  GIT_ASSERT_ARG(out);
1380
  GIT_ASSERT_ARG(diriter);
1381
1382
  return git_win32__file_attribute_to_stat(out,
1383
    (WIN32_FILE_ATTRIBUTE_DATA *)&diriter->current,
1384
    diriter->path);
1385
}
1386
1387
void git_fs_path_diriter_free(git_fs_path_diriter *diriter)
1388
{
1389
  if (diriter == NULL)
1390
    return;
1391
1392
  git_str_dispose(&diriter->path_utf8);
1393
1394
  if (diriter->handle != INVALID_HANDLE_VALUE) {
1395
    FindClose(diriter->handle);
1396
    diriter->handle = INVALID_HANDLE_VALUE;
1397
  }
1398
}
1399
1400
#else
1401
1402
int git_fs_path_diriter_init(
1403
  git_fs_path_diriter *diriter,
1404
  const char *path,
1405
  unsigned int flags)
1406
48.7k
{
1407
48.7k
  GIT_ASSERT_ARG(diriter);
1408
48.7k
  GIT_ASSERT_ARG(path);
1409
1410
48.7k
  memset(diriter, 0, sizeof(git_fs_path_diriter));
1411
1412
#ifdef GIT_I18N_ICONV
1413
  diriter->ic.map = (iconv_t)-1;
1414
#endif
1415
1416
48.7k
  if (git_str_puts(&diriter->path, path) < 0)
1417
0
    return -1;
1418
1419
48.7k
  path_trim_slashes(&diriter->path);
1420
1421
48.7k
  if (diriter->path.size == 0) {
1422
0
    git_error_set(GIT_ERROR_FILESYSTEM, "could not open directory '%s'", path);
1423
0
    return -1;
1424
0
  }
1425
1426
48.7k
  if ((diriter->dir = opendir(diriter->path.ptr)) == NULL) {
1427
0
    git_str_dispose(&diriter->path);
1428
1429
0
    git_error_set(GIT_ERROR_OS, "failed to open directory '%s'", path);
1430
0
    return -1;
1431
0
  }
1432
1433
#ifdef GIT_I18N_ICONV
1434
  if ((flags & GIT_FS_PATH_DIR_PRECOMPOSE_UNICODE) != 0)
1435
    (void)git_fs_path_iconv_init_precompose(&diriter->ic);
1436
#endif
1437
1438
48.7k
  diriter->parent_len = diriter->path.size;
1439
48.7k
  diriter->flags = flags;
1440
1441
48.7k
  return 0;
1442
48.7k
}
1443
1444
int git_fs_path_diriter_next(git_fs_path_diriter *diriter)
1445
81.2k
{
1446
81.2k
  struct dirent *de;
1447
81.2k
  const char *filename;
1448
81.2k
  size_t filename_len;
1449
81.2k
  bool skip_dot = !(diriter->flags & GIT_FS_PATH_DIR_INCLUDE_DOT_AND_DOTDOT);
1450
81.2k
  int error = 0;
1451
1452
81.2k
  GIT_ASSERT_ARG(diriter);
1453
1454
81.2k
  errno = 0;
1455
1456
178k
  do {
1457
178k
    if ((de = readdir(diriter->dir)) == NULL) {
1458
48.7k
      if (!errno)
1459
48.7k
        return GIT_ITEROVER;
1460
1461
0
      git_error_set(GIT_ERROR_OS,
1462
0
        "could not read directory '%s'", diriter->path.ptr);
1463
0
      return -1;
1464
48.7k
    }
1465
178k
  } while (skip_dot && git_fs_path_is_dot_or_dotdot(de->d_name));
1466
1467
32.5k
  filename = de->d_name;
1468
32.5k
  filename_len = strlen(filename);
1469
1470
#ifdef GIT_I18N_ICONV
1471
  if ((diriter->flags & GIT_FS_PATH_DIR_PRECOMPOSE_UNICODE) != 0 &&
1472
    (error = git_fs_path_iconv(&diriter->ic, &filename, &filename_len)) < 0)
1473
    return error;
1474
#endif
1475
1476
32.5k
  git_str_truncate(&diriter->path, diriter->parent_len);
1477
1478
32.5k
  if (diriter->parent_len > 0 &&
1479
32.5k
    diriter->path.ptr[diriter->parent_len-1] != '/')
1480
32.5k
    git_str_putc(&diriter->path, '/');
1481
1482
32.5k
  git_str_put(&diriter->path, filename, filename_len);
1483
1484
32.5k
  if (git_str_oom(&diriter->path))
1485
0
    return -1;
1486
1487
32.5k
  return error;
1488
32.5k
}
1489
1490
int git_fs_path_diriter_filename(
1491
  const char **out,
1492
  size_t *out_len,
1493
  git_fs_path_diriter *diriter)
1494
0
{
1495
0
  GIT_ASSERT_ARG(out);
1496
0
  GIT_ASSERT_ARG(out_len);
1497
0
  GIT_ASSERT_ARG(diriter);
1498
0
  GIT_ASSERT(diriter->path.size > diriter->parent_len);
1499
1500
0
  *out = &diriter->path.ptr[diriter->parent_len+1];
1501
0
  *out_len = diriter->path.size - diriter->parent_len - 1;
1502
0
  return 0;
1503
0
}
1504
1505
int git_fs_path_diriter_fullpath(
1506
  const char **out,
1507
  size_t *out_len,
1508
  git_fs_path_diriter *diriter)
1509
32.5k
{
1510
32.5k
  GIT_ASSERT_ARG(out);
1511
32.5k
  GIT_ASSERT_ARG(out_len);
1512
32.5k
  GIT_ASSERT_ARG(diriter);
1513
1514
32.5k
  *out = diriter->path.ptr;
1515
32.5k
  *out_len = diriter->path.size;
1516
32.5k
  return 0;
1517
32.5k
}
1518
1519
int git_fs_path_diriter_stat(struct stat *out, git_fs_path_diriter *diriter)
1520
32.5k
{
1521
32.5k
  GIT_ASSERT_ARG(out);
1522
32.5k
  GIT_ASSERT_ARG(diriter);
1523
1524
32.5k
  return git_fs_path_lstat(diriter->path.ptr, out);
1525
32.5k
}
1526
1527
void git_fs_path_diriter_free(git_fs_path_diriter *diriter)
1528
48.7k
{
1529
48.7k
  if (diriter == NULL)
1530
0
    return;
1531
1532
48.7k
  if (diriter->dir) {
1533
48.7k
    closedir(diriter->dir);
1534
48.7k
    diriter->dir = NULL;
1535
48.7k
  }
1536
1537
#ifdef GIT_I18N_ICONV
1538
  git_fs_path_iconv_clear(&diriter->ic);
1539
#endif
1540
1541
48.7k
  git_str_dispose(&diriter->path);
1542
48.7k
}
1543
1544
#endif
1545
1546
int git_fs_path_dirload(
1547
  git_vector *contents,
1548
  const char *path,
1549
  size_t prefix_len,
1550
  uint32_t flags)
1551
0
{
1552
0
  git_fs_path_diriter iter = GIT_FS_PATH_DIRITER_INIT;
1553
0
  const char *name;
1554
0
  size_t name_len;
1555
0
  char *dup;
1556
0
  int error;
1557
1558
0
  GIT_ASSERT_ARG(contents);
1559
0
  GIT_ASSERT_ARG(path);
1560
1561
0
  if ((error = git_fs_path_diriter_init(&iter, path, flags)) < 0)
1562
0
    return error;
1563
1564
0
  while ((error = git_fs_path_diriter_next(&iter)) == 0) {
1565
0
    if ((error = git_fs_path_diriter_fullpath(&name, &name_len, &iter)) < 0)
1566
0
      break;
1567
1568
0
    GIT_ASSERT(name_len > prefix_len);
1569
1570
0
    dup = git__strndup(name + prefix_len, name_len - prefix_len);
1571
0
    GIT_ERROR_CHECK_ALLOC(dup);
1572
1573
0
    if ((error = git_vector_insert(contents, dup)) < 0)
1574
0
      break;
1575
0
  }
1576
1577
0
  if (error == GIT_ITEROVER)
1578
0
    error = 0;
1579
1580
0
  git_fs_path_diriter_free(&iter);
1581
0
  return error;
1582
0
}
1583
1584
int git_fs_path_from_url_or_path(git_str *local_path_out, const char *url_or_path)
1585
0
{
1586
0
  if (git_fs_path_is_local_file_url(url_or_path))
1587
0
    return git_fs_path_fromurl(local_path_out, url_or_path);
1588
0
  else
1589
0
    return git_str_sets(local_path_out, url_or_path);
1590
0
}
1591
1592
/* Reject paths like AUX or COM1, or those versions that end in a dot or
1593
 * colon.  ("AUX." or "AUX:")
1594
 */
1595
GIT_INLINE(bool) validate_dospath(
1596
  const char *component,
1597
  size_t len,
1598
  const char dospath[3],
1599
  bool trailing_num)
1600
0
{
1601
0
  size_t last = trailing_num ? 4 : 3;
1602
1603
0
  if (len < last || git__strncasecmp(component, dospath, 3) != 0)
1604
0
    return true;
1605
1606
0
  if (trailing_num && (component[3] < '1' || component[3] > '9'))
1607
0
    return true;
1608
1609
0
  return (len > last &&
1610
0
    component[last] != '.' &&
1611
0
    component[last] != ':');
1612
0
}
1613
1614
GIT_INLINE(bool) validate_char(unsigned char c, unsigned int flags)
1615
0
{
1616
0
  if ((flags & GIT_FS_PATH_REJECT_BACKSLASH) && c == '\\')
1617
0
    return false;
1618
1619
0
  if ((flags & GIT_FS_PATH_REJECT_SLASH) && c == '/')
1620
0
    return false;
1621
1622
0
  if (flags & GIT_FS_PATH_REJECT_NT_CHARS) {
1623
0
    if (c < 32)
1624
0
      return false;
1625
1626
0
    switch (c) {
1627
0
    case '<':
1628
0
    case '>':
1629
0
    case ':':
1630
0
    case '"':
1631
0
    case '|':
1632
0
    case '?':
1633
0
    case '*':
1634
0
      return false;
1635
0
    }
1636
0
  }
1637
1638
0
  return true;
1639
0
}
1640
1641
/*
1642
 * We fundamentally don't like some paths when dealing with user-inputted
1643
 * strings (to avoid escaping a sandbox): we don't want dot or dot-dot
1644
 * anywhere, we want to avoid writing weird paths on Windows that can't
1645
 * be handled by tools that use the non-\\?\ APIs, we don't want slashes
1646
 * or double slashes at the end of paths that can make them ambiguous.
1647
 *
1648
 * For checkout, we don't want to recurse into ".git" either.
1649
 */
1650
static bool validate_component(
1651
  const char *component,
1652
  size_t len,
1653
  unsigned int flags)
1654
0
{
1655
0
  if (len == 0)
1656
0
    return !(flags & GIT_FS_PATH_REJECT_EMPTY_COMPONENT);
1657
1658
0
  if ((flags & GIT_FS_PATH_REJECT_TRAVERSAL) &&
1659
0
      len == 1 && component[0] == '.')
1660
0
    return false;
1661
1662
0
  if ((flags & GIT_FS_PATH_REJECT_TRAVERSAL) &&
1663
0
      len == 2 && component[0] == '.' && component[1] == '.')
1664
0
    return false;
1665
1666
0
  if ((flags & GIT_FS_PATH_REJECT_TRAILING_DOT) &&
1667
0
      component[len - 1] == '.')
1668
0
    return false;
1669
1670
0
  if ((flags & GIT_FS_PATH_REJECT_TRAILING_SPACE) &&
1671
0
      component[len - 1] == ' ')
1672
0
    return false;
1673
1674
0
  if ((flags & GIT_FS_PATH_REJECT_TRAILING_COLON) &&
1675
0
      component[len - 1] == ':')
1676
0
    return false;
1677
1678
0
  if (flags & GIT_FS_PATH_REJECT_DOS_PATHS) {
1679
0
    if (!validate_dospath(component, len, "CON", false) ||
1680
0
        !validate_dospath(component, len, "PRN", false) ||
1681
0
        !validate_dospath(component, len, "AUX", false) ||
1682
0
        !validate_dospath(component, len, "NUL", false) ||
1683
0
        !validate_dospath(component, len, "COM", true)  ||
1684
0
        !validate_dospath(component, len, "LPT", true))
1685
0
      return false;
1686
0
  }
1687
1688
0
  return true;
1689
0
}
1690
1691
#ifdef GIT_WIN32
1692
GIT_INLINE(bool) validate_length(
1693
  const char *path,
1694
  size_t len,
1695
  size_t utf8_char_len)
1696
{
1697
  GIT_UNUSED(path);
1698
  GIT_UNUSED(len);
1699
1700
  return (utf8_char_len <= MAX_PATH);
1701
}
1702
#endif
1703
1704
bool git_fs_path_str_is_valid_ext(
1705
  const git_str *path,
1706
  unsigned int flags,
1707
  bool (*validate_char_cb)(char ch, void *payload),
1708
  bool (*validate_component_cb)(const char *component, size_t len, void *payload),
1709
  bool (*validate_length_cb)(const char *path, size_t len, size_t utf8_char_len),
1710
  void *payload)
1711
81.2k
{
1712
81.2k
  const char *start, *c;
1713
81.2k
  size_t len = 0;
1714
1715
81.2k
  if (!flags)
1716
81.2k
    return true;
1717
1718
0
  for (start = c = path->ptr; *c && len < path->size; c++, len++) {
1719
0
    if (!validate_char(*c, flags))
1720
0
      return false;
1721
1722
0
    if (validate_char_cb && !validate_char_cb(*c, payload))
1723
0
      return false;
1724
1725
0
    if (*c != '/')
1726
0
      continue;
1727
1728
0
    if (!validate_component(start, (c - start), flags))
1729
0
      return false;
1730
1731
0
    if (validate_component_cb &&
1732
0
        !validate_component_cb(start, (c - start), payload))
1733
0
      return false;
1734
1735
0
    start = c + 1;
1736
0
  }
1737
1738
  /*
1739
   * We want to support paths specified as either `const char *`
1740
   * or `git_str *`; we pass size as `SIZE_MAX` when we use a
1741
   * `const char *` to avoid a `strlen`.  Ensure that we didn't
1742
   * have a NUL in the buffer if there was a non-SIZE_MAX length.
1743
   */
1744
0
  if (path->size != SIZE_MAX && len != path->size)
1745
0
    return false;
1746
1747
0
  if (!validate_component(start, (c - start), flags))
1748
0
    return false;
1749
1750
0
  if (validate_component_cb &&
1751
0
      !validate_component_cb(start, (c - start), payload))
1752
0
    return false;
1753
1754
#ifdef GIT_WIN32
1755
  if ((flags & GIT_FS_PATH_REJECT_LONG_PATHS) != 0) {
1756
    size_t utf8_len = git_utf8_char_length(path->ptr, len);
1757
1758
    if (!validate_length(path->ptr, len, utf8_len))
1759
      return false;
1760
1761
    if (validate_length_cb &&
1762
        !validate_length_cb(path->ptr, len, utf8_len))
1763
      return false;
1764
  }
1765
#else
1766
0
  GIT_UNUSED(validate_length_cb);
1767
0
#endif
1768
1769
0
  return true;
1770
0
}
1771
1772
int git_fs_path_validate_str_length_with_suffix(
1773
  git_str *path,
1774
  size_t suffix_len)
1775
193
{
1776
#ifdef GIT_WIN32
1777
  size_t utf8_len = git_utf8_char_length(path->ptr, path->size);
1778
  size_t total_len;
1779
1780
  if (GIT_ADD_SIZET_OVERFLOW(&total_len, utf8_len, suffix_len) ||
1781
      total_len > MAX_PATH) {
1782
1783
    git_error_set(GIT_ERROR_FILESYSTEM, "path too long: '%.*s'",
1784
      (int)path->size, path->ptr);
1785
    return -1;
1786
  }
1787
#else
1788
193
  GIT_UNUSED(path);
1789
193
  GIT_UNUSED(suffix_len);
1790
193
#endif
1791
1792
193
  return 0;
1793
193
}
1794
1795
int git_fs_path_normalize_slashes(git_str *out, const char *path)
1796
0
{
1797
0
  int error;
1798
0
  char *p;
1799
1800
0
  if ((error = git_str_puts(out, path)) < 0)
1801
0
    return error;
1802
1803
0
  for (p = out->ptr; *p; p++) {
1804
0
    if (*p == '\\')
1805
0
      *p = '/';
1806
0
  }
1807
1808
0
  return 0;
1809
0
}
1810
1811
bool git_fs_path_supports_symlinks(const char *dir)
1812
2
{
1813
2
  git_str path = GIT_STR_INIT;
1814
2
  bool supported = false;
1815
2
  struct stat st;
1816
2
  int fd;
1817
1818
2
  if ((fd = git_futils_mktmp(&path, dir, 0666)) < 0 ||
1819
2
      p_close(fd) < 0 ||
1820
2
      p_unlink(path.ptr) < 0 ||
1821
2
      p_symlink("testing", path.ptr) < 0 ||
1822
2
      p_lstat(path.ptr, &st) < 0)
1823
0
    goto done;
1824
1825
2
  supported = (S_ISLNK(st.st_mode) != 0);
1826
2
done:
1827
2
  if (path.size)
1828
2
    (void)p_unlink(path.ptr);
1829
2
  git_str_dispose(&path);
1830
2
  return supported;
1831
2
}
1832
1833
static git_fs_path_owner_t mock_owner = GIT_FS_PATH_OWNER_NONE;
1834
1835
void git_fs_path__set_owner(git_fs_path_owner_t owner)
1836
0
{
1837
0
  mock_owner = owner;
1838
0
}
1839
1840
#ifdef GIT_WIN32
1841
static PSID *sid_dup(PSID sid)
1842
{
1843
  DWORD len;
1844
  PSID dup;
1845
1846
  len = GetLengthSid(sid);
1847
1848
  if ((dup = git__malloc(len)) == NULL)
1849
    return NULL;
1850
1851
  if (!CopySid(len, dup, sid)) {
1852
    git_error_set(GIT_ERROR_OS, "could not duplicate sid");
1853
    git__free(dup);
1854
    return NULL;
1855
  }
1856
1857
  return dup;
1858
}
1859
1860
static int current_user_sid(PSID *sid, HANDLE *linked_token)
1861
{
1862
  TOKEN_USER *info = NULL;
1863
  HANDLE token = NULL;
1864
  DWORD len = 0;
1865
  int error = -1;
1866
  TOKEN_ELEVATION_TYPE elevation_type;
1867
  DWORD size;
1868
1869
  if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) {
1870
    git_error_set(GIT_ERROR_OS, "could not lookup process information");
1871
    goto done;
1872
  }
1873
1874
  if (GetTokenInformation(token, TokenUser, NULL, 0, &len) ||
1875
    GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
1876
    git_error_set(GIT_ERROR_OS, "could not lookup token metadata");
1877
    goto done;
1878
  }
1879
1880
  info = git__malloc(len);
1881
  GIT_ERROR_CHECK_ALLOC(info);
1882
1883
  if (!GetTokenInformation(token, TokenUser, info, len, &len)) {
1884
    git_error_set(GIT_ERROR_OS, "could not lookup current user");
1885
    goto done;
1886
  }
1887
1888
  if (GetTokenInformation(token, TokenElevationType, &elevation_type, sizeof(elevation_type), &size) &&
1889
      elevation_type == TokenElevationTypeLimited) {
1890
    /*
1891
     * The current process is run by a member of the Administrators group
1892
     * but is not running elevated.
1893
     */
1894
    if (!GetTokenInformation(token, TokenLinkedToken, linked_token, sizeof(HANDLE), &size)) {
1895
      CloseHandle(*linked_token);
1896
      *linked_token = NULL;
1897
    }
1898
  }
1899
1900
  if ((*sid = sid_dup(info->User.Sid)))
1901
    error = 0;
1902
1903
done:
1904
  if (token)
1905
    CloseHandle(token);
1906
1907
  git__free(info);
1908
  return error;
1909
}
1910
1911
static int file_owner_sid(PSID *out, const char *path)
1912
{
1913
  git_win32_path path_w32;
1914
  PSECURITY_DESCRIPTOR descriptor = NULL;
1915
  PSID owner_sid;
1916
  DWORD ret;
1917
  int error = GIT_EINVALID;
1918
1919
  if (git_win32_path_from_utf8(path_w32, path) < 0)
1920
    return -1;
1921
1922
  ret = GetNamedSecurityInfoW(path_w32, SE_FILE_OBJECT,
1923
    OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
1924
    &owner_sid, NULL, NULL, NULL, &descriptor);
1925
1926
  if (ret == ERROR_FILE_NOT_FOUND || ret == ERROR_PATH_NOT_FOUND)
1927
    error = GIT_ENOTFOUND;
1928
  else if (ret != ERROR_SUCCESS)
1929
    git_error_set(GIT_ERROR_OS, "failed to get security information");
1930
  else if (!IsValidSid(owner_sid))
1931
    git_error_set(GIT_ERROR_OS, "file owner is not valid");
1932
  else if ((*out = sid_dup(owner_sid)))
1933
    error = 0;
1934
1935
  if (descriptor)
1936
    LocalFree(descriptor);
1937
1938
  return error;
1939
}
1940
1941
int git_fs_path_owner_is(
1942
  bool *out,
1943
  const char *path,
1944
  git_fs_path_owner_t owner_type)
1945
{
1946
  PSID owner_sid = NULL, user_sid = NULL;
1947
  HANDLE linked_token = NULL;
1948
  BOOL is_admin, admin_owned;
1949
  int error;
1950
1951
  if (mock_owner) {
1952
    *out = ((mock_owner & owner_type) != 0);
1953
    return 0;
1954
  }
1955
1956
  if ((error = file_owner_sid(&owner_sid, path)) < 0 ||
1957
      (error = current_user_sid(&user_sid, &linked_token)) < 0)
1958
    goto done;
1959
1960
  if ((owner_type & GIT_FS_PATH_OWNER_CURRENT_USER) != 0 &&
1961
      EqualSid(owner_sid, user_sid)) {
1962
    *out = true;
1963
    goto done;
1964
  }
1965
1966
  admin_owned =
1967
    IsWellKnownSid(owner_sid, WinBuiltinAdministratorsSid) ||
1968
    IsWellKnownSid(owner_sid, WinLocalSystemSid);
1969
1970
  if (admin_owned &&
1971
      (owner_type & GIT_FS_PATH_OWNER_ADMINISTRATOR) != 0) {
1972
    *out = true;
1973
    goto done;
1974
  }
1975
1976
  if (admin_owned &&
1977
      (owner_type & GIT_FS_PATH_USER_IS_ADMINISTRATOR) != 0 &&
1978
      CheckTokenMembership(NULL, owner_sid, &is_admin) &&
1979
      CheckTokenMembership(linked_token, owner_sid, &is_admin) &&
1980
      is_admin) {
1981
    *out = true;
1982
    goto done;
1983
  }
1984
1985
  *out = false;
1986
1987
done:
1988
  if (linked_token)
1989
      CloseHandle(linked_token);
1990
1991
  git__free(owner_sid);
1992
  git__free(user_sid);
1993
  return error;
1994
}
1995
1996
#else
1997
1998
static int sudo_uid_lookup(uid_t *out)
1999
0
{
2000
0
  git_str uid_str = GIT_STR_INIT;
2001
0
  int64_t uid;
2002
0
  int error = -1;
2003
2004
0
  if (git__getenv(&uid_str, "SUDO_UID") == 0 &&
2005
0
    git__strntol64(&uid, uid_str.ptr, uid_str.size, NULL, 10) == 0 &&
2006
0
    uid == (int64_t)((uid_t)uid)) {
2007
0
    *out = (uid_t)uid;
2008
0
    error = 0;
2009
0
  }
2010
2011
0
  git_str_dispose(&uid_str);
2012
0
  return error;
2013
0
}
2014
2015
int git_fs_path_owner_is(
2016
  bool *out,
2017
  const char *path,
2018
  git_fs_path_owner_t owner_type)
2019
2
{
2020
2
  struct stat st;
2021
2
  uid_t euid, sudo_uid;
2022
2023
2
  if (mock_owner) {
2024
0
    *out = ((mock_owner & owner_type) != 0);
2025
0
    return 0;
2026
0
  }
2027
2028
2
  euid = geteuid();
2029
2030
2
  if (p_lstat(path, &st) != 0) {
2031
0
    if (errno == ENOENT)
2032
0
      return GIT_ENOTFOUND;
2033
2034
0
    git_error_set(GIT_ERROR_OS, "could not stat '%s'", path);
2035
0
    return -1;
2036
0
  }
2037
2038
2
  if ((owner_type & GIT_FS_PATH_OWNER_CURRENT_USER) != 0 &&
2039
2
      st.st_uid == euid) {
2040
2
    *out = true;
2041
2
    return 0;
2042
2
  }
2043
2044
0
  if ((owner_type & GIT_FS_PATH_OWNER_ADMINISTRATOR) != 0 &&
2045
0
      st.st_uid == 0) {
2046
0
    *out = true;
2047
0
    return 0;
2048
0
  }
2049
2050
0
  if ((owner_type & GIT_FS_PATH_OWNER_RUNNING_SUDO) != 0 &&
2051
0
      euid == 0 &&
2052
0
      sudo_uid_lookup(&sudo_uid) == 0 &&
2053
0
      st.st_uid == sudo_uid) {
2054
0
    *out = true;
2055
0
    return 0;
2056
0
  }
2057
2058
0
  *out = false;
2059
0
  return 0;
2060
0
}
2061
2062
#endif
2063
2064
int git_fs_path_owner_is_current_user(bool *out, const char *path)
2065
0
{
2066
0
  return git_fs_path_owner_is(out, path, GIT_FS_PATH_OWNER_CURRENT_USER);
2067
0
}
2068
2069
int git_fs_path_owner_is_system(bool *out, const char *path)
2070
0
{
2071
0
  return git_fs_path_owner_is(out, path, GIT_FS_PATH_OWNER_ADMINISTRATOR);
2072
0
}
2073
2074
#ifdef GIT_WIN32
2075
2076
static int find_executable(git_str *fullpath, const char *executable)
2077
{
2078
  git_win32_path fullpath_w, executable_w;
2079
  int error;
2080
2081
  if (git_utf8_to_16(executable_w, GIT_WIN_PATH_MAX, executable) < 0)
2082
    return -1;
2083
2084
  error = git_win32_path_find_executable(fullpath_w, executable_w);
2085
2086
  if (error == 0)
2087
    error = git_str_put_w(fullpath, fullpath_w, wcslen(fullpath_w));
2088
2089
  return error;
2090
}
2091
2092
#else
2093
2094
static int find_executable(git_str *fullpath, const char *executable)
2095
0
{
2096
0
  git_str path = GIT_STR_INIT;
2097
0
  const char *current_dir, *term;
2098
0
  size_t current_dirlen;
2099
0
  bool found = false;
2100
2101
0
  if (git__getenv(&path, "PATH") < 0)
2102
0
    return -1;
2103
2104
0
  current_dir = path.ptr;
2105
2106
0
  while (*current_dir) {
2107
0
    if (! (term = strchr(current_dir, GIT_PATH_LIST_SEPARATOR)))
2108
0
      term = strchr(current_dir, '\0');
2109
2110
0
    current_dirlen = term - current_dir;
2111
0
    git_str_clear(fullpath);
2112
2113
    /* An empty path segment is treated as '.' */
2114
0
    if (current_dirlen == 0 && git_str_putc(fullpath, '.'))
2115
0
      return -1;
2116
0
    else if (current_dirlen != 0 &&
2117
0
             git_str_put(fullpath, current_dir, current_dirlen) < 0)
2118
0
      return -1;
2119
2120
0
    if (git_str_putc(fullpath, '/') < 0 ||
2121
0
        git_str_puts(fullpath, executable) < 0)
2122
0
      return -1;
2123
2124
0
    if (git_fs_path_isexecutable(fullpath->ptr)) {
2125
0
      found = true;
2126
0
      break;
2127
0
    }
2128
2129
0
    current_dir = term;
2130
2131
0
    if (*current_dir == GIT_PATH_LIST_SEPARATOR)
2132
0
      current_dir++;
2133
0
  }
2134
2135
0
  git_str_dispose(&path);
2136
2137
0
  if (found)
2138
0
    return 0;
2139
2140
0
  git_str_clear(fullpath);
2141
0
  return GIT_ENOTFOUND;
2142
0
}
2143
2144
#endif
2145
2146
int git_fs_path_find_executable(git_str *fullpath, const char *executable)
2147
0
{
2148
  /* For qualified paths we do not look in PATH */
2149
0
  if (strchr(executable, '/') != NULL) {
2150
0
    if (!git_fs_path_isexecutable(executable))
2151
0
      return GIT_ENOTFOUND;
2152
2153
0
    return git_str_puts(fullpath, executable);
2154
0
  }
2155
2156
0
  return find_executable(fullpath, executable);
2157
0
}