-
-
Notifications
You must be signed in to change notification settings - Fork 35.4k
Expand file tree
/
Copy pathpath.cc
More file actions
451 lines (407 loc) Β· 13.3 KB
/
path.cc
File metadata and controls
451 lines (407 loc) Β· 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
#include "path.h"
#include <string>
#include <vector>
#include "ada.h"
#include "env-inl.h"
#include "node_internals.h"
#include "node_url.h"
namespace node {
#ifdef _WIN32
constexpr bool IsPathSeparator(const char c) noexcept {
return c == '\\' || c == '/';
}
#else // POSIX
constexpr bool IsPathSeparator(const char c) noexcept {
return c == '/';
}
#endif // _WIN32
std::string NormalizeString(const std::string_view path,
bool allowAboveRoot,
const std::string_view separator) {
std::string res;
int lastSegmentLength = 0;
int lastSlash = -1;
int dots = 0;
char code = 0;
for (size_t i = 0; i <= path.size(); ++i) {
if (i < path.size()) {
code = path[i];
} else if (IsPathSeparator(code)) {
break;
} else {
code = '/';
}
if (IsPathSeparator(code)) {
if (lastSlash == static_cast<int>(i - 1) || dots == 1) {
// NOOP
} else if (dots == 2) {
int len = res.length();
if (len < 2 || lastSegmentLength != 2 || res[len - 1] != '.' ||
res[len - 2] != '.') {
if (len > 2) {
auto lastSlashIndex = res.find_last_of(separator);
if (lastSlashIndex == std::string::npos) {
res = "";
lastSegmentLength = 0;
} else {
res = res.substr(0, lastSlashIndex);
len = res.length();
lastSegmentLength = len - 1 - res.find_last_of(separator);
}
lastSlash = i;
dots = 0;
continue;
} else if (len != 0) {
res = "";
lastSegmentLength = 0;
lastSlash = i;
dots = 0;
continue;
}
}
if (allowAboveRoot) {
res += res.length() > 0 ? std::string(separator) + ".." : "..";
lastSegmentLength = 2;
}
} else {
if (!res.empty()) {
res += std::string(separator) +
std::string(path.substr(lastSlash + 1, i - (lastSlash + 1)));
} else {
res = path.substr(lastSlash + 1, i - (lastSlash + 1));
}
lastSegmentLength = i - lastSlash - 1;
}
lastSlash = i;
dots = 0;
} else if (code == '.' && dots != -1) {
++dots;
} else {
dots = -1;
}
}
return res;
}
#ifdef _WIN32
constexpr bool IsWindowsDriveLetter(const std::string_view path) noexcept {
return path.size() > 2 && IsWindowsDeviceRoot(path[0]) &&
(path[1] == ':' && (path[2] == '/' || path[2] == '\\'));
}
constexpr bool IsWindowsDeviceRoot(const char c) noexcept {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
enum class WindowsNamespacedPathType {
kNotNamespaced,
kDriveAbsolutePath,
kUNCPath,
kOtherNamespacedPath,
};
static WindowsNamespacedPathType ClassifyWindowsNamespacedPath(
std::string_view path) {
if (!(path.size() >= 4 && path[0] == '\\' && path[1] == '\\' &&
path[2] == '?' && path[3] == '\\')) {
return WindowsNamespacedPathType::kNotNamespaced;
}
if (path.size() >= 7 && IsWindowsDeviceRoot(path[4]) && path[5] == ':' &&
IsPathSeparator(path[6])) {
return WindowsNamespacedPathType::kDriveAbsolutePath;
}
if (path.size() >= 8 && ToLower(path[4]) == 'u' &&
ToLower(path[5]) == 'n' && ToLower(path[6]) == 'c' &&
path[7] == '\\') {
size_t i = 8;
const size_t server_start = i;
while (i < path.size() && !IsPathSeparator(path[i])) {
i++;
}
if (i == server_start || i == path.size()) {
return WindowsNamespacedPathType::kOtherNamespacedPath;
}
while (i < path.size() && IsPathSeparator(path[i])) {
i++;
}
const size_t share_start = i;
while (i < path.size() && !IsPathSeparator(path[i])) {
i++;
}
if (i == share_start) {
return WindowsNamespacedPathType::kOtherNamespacedPath;
}
return WindowsNamespacedPathType::kUNCPath;
}
return WindowsNamespacedPathType::kOtherNamespacedPath;
}
static void StripExtendedPathPrefixForPathResolve(std::string& path) {
switch (ClassifyWindowsNamespacedPath(path)) {
case WindowsNamespacedPathType::kDriveAbsolutePath:
path = path.substr(4);
return;
case WindowsNamespacedPathType::kUNCPath:
path = "\\\\" + path.substr(8);
return;
case WindowsNamespacedPathType::kNotNamespaced:
case WindowsNamespacedPathType::kOtherNamespacedPath:
return;
}
}
std::string PathResolve(Environment* env,
const std::vector<std::string_view>& paths) {
std::string resolvedDevice = "";
std::string resolvedTail = "";
bool resolvedAbsolute = false;
const size_t numArgs = paths.size();
auto cwd = env->GetCwd(env->exec_path());
for (int i = numArgs - 1; i >= -1; i--) {
std::string path;
if (i >= 0) {
path = std::string(paths[i]);
} else if (resolvedDevice.empty()) {
path = cwd;
} else {
// Windows has the concept of drive-specific current working
// directories. If we've resolved a drive letter but not yet an
// absolute path, get cwd for that drive, or the process cwd if
// the drive cwd is not available. We're sure the device is not
// a UNC path at this points, because UNC paths are always absolute.
std::string resolvedDevicePath;
const std::string envvar = "=" + resolvedDevice;
credentials::SafeGetenv(envvar.c_str(), &resolvedDevicePath, env);
path = resolvedDevicePath.empty() ? cwd : resolvedDevicePath;
// Verify that a cwd was found and that it actually points
// to our drive. If not, default to the drive's root.
if (path.empty() ||
(ToLower(path.substr(0, 2)) != ToLower(resolvedDevice) &&
path[2] == '/')) {
path = resolvedDevice + "\\";
}
}
StripExtendedPathPrefixForPathResolve(path);
const size_t len = path.length();
int rootEnd = 0;
std::string device = "";
bool isAbsolute = false;
const char code = path[0];
// Try to match a root
if (len == 1) {
if (IsPathSeparator(code)) {
// `path` contains just a path separator
rootEnd = 1;
isAbsolute = true;
}
} else if (IsPathSeparator(code)) {
// Possible UNC root
// If we started with a separator, we know we at least have an
// absolute path of some kind (UNC or otherwise)
isAbsolute = true;
if (IsPathSeparator(path[1])) {
// Matched double path separator at beginning
size_t j = 2;
size_t last = j;
// Match 1 or more non-path separators
while (j < len && !IsPathSeparator(path[j])) {
j++;
}
if (j < len && j != last) {
const std::string firstPart = path.substr(last, j - last);
// Matched!
last = j;
// Match 1 or more path separators
while (j < len && IsPathSeparator(path[j])) {
j++;
}
if (j < len && j != last) {
// Matched!
last = j;
// Match 1 or more non-path separators
while (j < len && !IsPathSeparator(path[j])) {
j++;
}
if (j == len || j != last) {
if (firstPart != "." && firstPart != "?") {
// We matched a UNC root
device =
"\\\\" + firstPart + "\\" + path.substr(last, j - last);
rootEnd = j;
} else {
// We matched a device root (e.g. \\\\.\\PHYSICALDRIVE0)
device = "\\\\" + firstPart;
rootEnd = 4;
}
}
}
}
}
} else if (IsWindowsDeviceRoot(code) && path[1] == ':') {
// Possible device root
device = path.substr(0, 2);
rootEnd = 2;
if (len > 2 && IsPathSeparator(path[2])) {
// Treat separator following drive name as an absolute path
// indicator
isAbsolute = true;
rootEnd = 3;
}
}
if (!device.empty()) {
if (!resolvedDevice.empty()) {
if (ToLower(device) != ToLower(resolvedDevice)) {
// This path points to another device so it is not applicable
continue;
}
} else {
resolvedDevice = device;
}
}
if (resolvedAbsolute) {
if (!resolvedDevice.empty()) {
break;
}
} else {
resolvedTail = path.substr(rootEnd) + "\\" + resolvedTail;
resolvedAbsolute = isAbsolute;
if (isAbsolute && !resolvedDevice.empty()) {
break;
}
}
}
// At this point the path should be resolved to a full absolute path,
// but handle relative paths to be safe (might happen when process.cwd()
// fails)
// Normalize the tail path
resolvedTail = NormalizeString(resolvedTail, !resolvedAbsolute, "\\");
if (resolvedAbsolute) {
return resolvedDevice + "\\" + resolvedTail;
}
if (!resolvedDevice.empty() || !resolvedTail.empty()) {
return resolvedDevice + resolvedTail;
}
return ".";
}
#else // _WIN32
std::string PathResolve(Environment* env,
const std::vector<std::string_view>& paths) {
std::string resolvedPath;
bool resolvedAbsolute = false;
auto cwd = env->GetCwd(env->exec_path());
const size_t numArgs = paths.size();
for (int i = numArgs - 1; i >= -1 && !resolvedAbsolute; i--) {
const std::string& path = (i >= 0) ? std::string(paths[i]) : cwd;
if (!path.empty()) {
resolvedPath = std::string(path) + "/" + resolvedPath;
if (path.front() == '/') {
resolvedAbsolute = true;
break;
}
}
}
// Normalize the path
auto normalizedPath = NormalizeString(resolvedPath, !resolvedAbsolute, "/");
if (resolvedAbsolute) {
return "/" + normalizedPath;
}
if (normalizedPath.empty()) {
return ".";
}
return normalizedPath;
}
#endif // _WIN32
void ToNamespacedPath(Environment* env, BufferValue* path) {
#ifdef _WIN32
if (path->length() == 0) return;
std::string resolved_path = node::PathResolve(env, {path->ToStringView()});
if (resolved_path.size() <= 2) {
return;
}
// SAFETY: We know that resolved_path.size() > 2, therefore accessing [0],
// [1], and [2] is safe.
if (resolved_path[0] == '\\') {
// Possible UNC root
if (resolved_path[1] == '\\') {
if (resolved_path[2] != '?' && resolved_path[2] != '.') {
// Matched non-long UNC root, convert the path to a long UNC path
std::string_view unc_prefix = R"(\\?\UNC\)";
size_t new_length = unc_prefix.size() + resolved_path.size() - 2;
path->AllocateSufficientStorage(new_length + 1);
path->SetLength(new_length);
memcpy(path->out(), unc_prefix.data(), unc_prefix.size());
memcpy(path->out() + unc_prefix.size(),
resolved_path.c_str() + 2,
resolved_path.size() - 2 + 1);
return;
}
}
} else if (IsWindowsDeviceRoot(resolved_path[0]) && resolved_path[1] == ':' &&
resolved_path[2] == '\\') {
// Matched device root, convert the path to a long UNC path
std::string_view new_prefix = R"(\\?\)";
size_t new_length = new_prefix.size() + resolved_path.size();
path->AllocateSufficientStorage(new_length + 1);
path->SetLength(new_length);
memcpy(path->out(), new_prefix.data(), new_prefix.size());
memcpy(path->out() + new_prefix.size(),
resolved_path.c_str(),
resolved_path.size() + 1);
return;
}
size_t new_length = resolved_path.size();
path->AllocateSufficientStorage(new_length + 1);
path->SetLength(new_length);
memcpy(path->out(), resolved_path.c_str(), resolved_path.size() + 1);
#endif
}
// Reverse the logic applied by path.toNamespacedPath() to create a
// namespace-prefixed path.
void FromNamespacedPath(std::string* path) {
#ifdef _WIN32
switch (ClassifyWindowsNamespacedPath(*path)) {
case WindowsNamespacedPathType::kUNCPath:
*path = "\\\\" + path->substr(8);
return;
case WindowsNamespacedPathType::kDriveAbsolutePath:
*path = path->substr(4);
return;
case WindowsNamespacedPathType::kNotNamespaced:
case WindowsNamespacedPathType::kOtherNamespacedPath:
return;
}
#endif
}
// Check if a path looks like an absolute path or file URL.
bool IsAbsoluteFilePath(std::string_view path) {
if (path.starts_with("file://")) {
return true;
}
#ifdef _WIN32
if (path.size() > 0 && path[0] == '\\') return true;
if (IsWindowsDriveLetter(path)) return true;
#endif
if (path.size() > 0 && path[0] == '/') return true;
return false;
}
// Normalizes paths by resolving file URLs and converting to a consistent
// format with forward slashes.
std::string NormalizeFileURLOrPath(Environment* env, std::string_view path) {
std::string normalized_string(path);
constexpr std::string_view file_scheme = "file://";
if (normalized_string.starts_with(file_scheme)) {
auto out = ada::parse<ada::url_aggregator>(normalized_string);
auto file_path = url::FileURLToPath(env, *out);
if (!file_path.has_value()) {
return std::string();
}
normalized_string = file_path.value();
}
normalized_string = NormalizeString(normalized_string, false, "/");
#ifdef _WIN32
if (IsWindowsDriveLetter(normalized_string)) {
normalized_string[0] = ToLower(normalized_string[0]);
}
for (char& c : normalized_string) {
if (c == '\\') {
c = '/';
}
}
#endif
return normalized_string;
}
} // namespace node