diff --git a/src/node_file.cc b/src/node_file.cc index b96771217b83..a5f294c61472 100644 --- a/src/node_file.cc +++ b/src/node_file.cc @@ -5473,16 +5473,9 @@ void BindingData::LegacyMainResolve(const FunctionCallbackInfo& args) { for (int i = 0; i < legacy_main_extensions_with_main_end; i++) { file_path = *initial_file_path + std::string(legacy_main_extensions[i]); - // TODO(anonrig): Remove this when ToNamespacedPath supports std::string - Local local_file_path; - if (!Buffer::Copy(env->isolate(), file_path.c_str(), file_path.size()) - .ToLocal(&local_file_path)) { - return; - } - BufferValue buff_file_path(isolate, local_file_path); - ToNamespacedPath(env, &buff_file_path); + ToNamespacedPath(env, &file_path); - switch (FilePathIsFile(env, buff_file_path.ToString())) { + switch (FilePathIsFile(env, file_path)) { case BindingData::FilePathIsFileReturnType::kIsFile: return args.GetReturnValue().Set(i); case BindingData::FilePathIsFileReturnType::kIsNotFile: @@ -5510,16 +5503,9 @@ void BindingData::LegacyMainResolve(const FunctionCallbackInfo& args) { i < legacy_main_extensions_package_fallback_end; i++) { file_path = *initial_file_path + std::string(legacy_main_extensions[i]); - // TODO(anonrig): Remove this when ToNamespacedPath supports std::string - Local local_file_path; - if (!Buffer::Copy(env->isolate(), file_path.c_str(), file_path.size()) - .ToLocal(&local_file_path)) { - return; - } - BufferValue buff_file_path(isolate, local_file_path); - ToNamespacedPath(env, &buff_file_path); + ToNamespacedPath(env, &file_path); - switch (FilePathIsFile(env, buff_file_path.ToString())) { + switch (FilePathIsFile(env, file_path)) { case BindingData::FilePathIsFileReturnType::kIsFile: return args.GetReturnValue().Set(i); case BindingData::FilePathIsFileReturnType::kIsNotFile: diff --git a/src/node_modules.cc b/src/node_modules.cc index ee9be4557ac1..f966879fc152 100644 --- a/src/node_modules.cc +++ b/src/node_modules.cc @@ -581,32 +581,40 @@ void BindingData::GetPackageScopeConfig( return; } - std::string_view node_modules_package_path = "/node_modules/package.json"; auto error_context = ErrorContext(); error_context.is_esm = true; + error_context.specifier = resolved.ToString(); - // TODO(@anonrig): Rewrite this function and avoid calling URL parser. - while (true) { - auto pathname = package_json_url->get_pathname(); - if (pathname.ends_with(node_modules_package_path)) { - break; - } + auto file_path = url::FileURLToPath(realm->env(), *package_json_url); + if (!file_path) { + url::ThrowInvalidURL(realm->env(), resolved.ToStringView(), std::nullopt); + return; + } - auto file_url = url::FileURLToPath(realm->env(), *package_json_url); - if (!file_url) { - url::ThrowInvalidURL(realm->env(), resolved.ToStringView(), std::nullopt); - return; - } - BufferValue file_path_buf(realm->isolate(), - String::NewFromUtf8(realm->isolate(), - file_url->c_str(), - NewStringType::kInternalized, - file_url->size()) - .ToLocalChecked()); - ToNamespacedPath(realm->env(), &file_path_buf); - error_context.specifier = resolved.ToString(); - auto package_json = - GetPackageJSON(realm, file_path_buf.ToStringView(), &error_context); + // Avoids a URL parse per level. + std::string& path = *file_path; + static constexpr std::string_view kPackageJSON = "package.json"; + size_t root_end = 0; +#ifdef _WIN32 + static constexpr std::string_view kNodeModulesPackagePath = + "\\node_modules\\package.json"; + // Stop at the drive ("C:") or UNC host ("\\host"). + root_end = path.starts_with("\\\\") ? path.find('\\', 2) : 2; +#else + static constexpr std::string_view kNodeModulesPackagePath = + "/node_modules/package.json"; +#endif + + while (!path.ends_with(kNodeModulesPackagePath)) { +#ifdef _WIN32 + // Cache keys are namespaced. + std::string namespaced_path = path; + ToNamespacedPath(realm->env(), &namespaced_path); + std::string_view key = namespaced_path; +#else + std::string_view key = path; +#endif + auto package_json = GetPackageJSON(realm, key, &error_context); if (package_json != nullptr) { if constexpr (return_only_type) { Local value; @@ -619,19 +627,18 @@ void BindingData::GetPackageScopeConfig( } } - auto last_href = std::string(package_json_url->get_href()); - auto last_pathname = std::string(package_json_url->get_pathname()); - package_json_url = ada::parse("../package.json", &package_json_url.value()); - if (!package_json_url) { - url::ThrowInvalidURL(realm->env(), "../package.json", last_href); - return; - } - - // Terminates at root where ../package.json equals ../../package.json - // (can't just check "/package.json" for Windows support). - if (package_json_url->get_pathname() == last_pathname) { + const size_t dir_end = path.size() - kPackageJSON.size() - 1; + if (dir_end <= root_end) { break; } + const size_t parent_end = path.rfind(kPathSeparator, dir_end - 1); + // Drive-relative, from "file:///C:foo/x.js". The URL walk threw here. + if (parent_end == std::string::npos) { + url::ThrowInvalidURL(realm->env(), resolved.ToStringView(), std::nullopt); + return; + } + path.resize(parent_end + 1); + path += kPackageJSON; } if constexpr (return_only_type) { @@ -640,12 +647,8 @@ void BindingData::GetPackageScopeConfig( // If the package.json could not be found return a string containing a path // to the non-existent package.json file in the initial requested location - auto package_json_url_as_path = - url::FileURLToPath(realm->env(), *package_json_url); - CHECK(package_json_url_as_path); Local ret; - if (ToV8Value(realm->context(), *package_json_url_as_path, realm->isolate()) - .ToLocal(&ret)) { + if (ToV8Value(realm->context(), path, realm->isolate()).ToLocal(&ret)) { args.GetReturnValue().Set(ret); } } diff --git a/src/path.cc b/src/path.cc index f2e1ae116c3d..ff80e8f60c65 100644 --- a/src/path.cc +++ b/src/path.cc @@ -1,4 +1,5 @@ #include "path.h" +#include #include #include #include "ada.h" @@ -261,50 +262,55 @@ std::string PathResolve(Environment* env, } #endif // _WIN32 -void ToNamespacedPath(Environment* env, BufferValue* path) { #ifdef _WIN32 - if (path->length() == 0) return; - std::string resolved_path = node::PathResolve(env, {path->ToStringView()}); +// Returns the namespace-prefixed form of `path`, or std::nullopt when `path` +// must be left unchanged. +static std::optional NamespacedPath(Environment* env, + std::string_view path) { + if (path.empty()) return std::nullopt; + std::string resolved_path = PathResolve(env, {path}); if (resolved_path.size() <= 2) { - return; + return std::nullopt; } // 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; - } + if (resolved_path[1] == '\\' && resolved_path[2] != '?' && + resolved_path[2] != '.') { + // Matched non-long UNC root, convert the path to a long UNC path + resolved_path.replace(0, 2, R"(\\?\UNC\)"); } } 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; + resolved_path.insert(0, R"(\\?\)"); } - size_t new_length = resolved_path.size(); + return resolved_path; +} +#endif // _WIN32 + +void ToNamespacedPath(Environment* env, BufferValue* path) { +#ifdef _WIN32 + std::optional namespaced_path = + NamespacedPath(env, path->ToStringView()); + if (!namespaced_path.has_value()) return; + + size_t new_length = namespaced_path->size(); path->AllocateSufficientStorage(new_length + 1); path->SetLength(new_length); - memcpy(path->out(), resolved_path.c_str(), resolved_path.size() + 1); + memcpy(path->out(), namespaced_path->c_str(), new_length + 1); +#endif +} + +void ToNamespacedPath(Environment* env, std::string* path) { +#ifdef _WIN32 + std::optional namespaced_path = NamespacedPath(env, *path); + if (namespaced_path.has_value()) { + *path = std::move(*namespaced_path); + } #endif } diff --git a/src/path.h b/src/path.h index 65f0eb858ca7..d4feefe4d9e1 100644 --- a/src/path.h +++ b/src/path.h @@ -42,6 +42,7 @@ constexpr bool IsWindowsDriveLetter(const std::string_view path) noexcept { #endif // _WIN32 void ToNamespacedPath(Environment* env, BufferValue* path); +void ToNamespacedPath(Environment* env, std::string* path); void FromNamespacedPath(std::string* path); } // namespace node diff --git a/test/cctest/test_path.cc b/test/cctest/test_path.cc index 1fd991340452..d45e927ce120 100644 --- a/test/cctest/test_path.cc +++ b/test/cctest/test_path.cc @@ -95,6 +95,38 @@ TEST_F(PathTest, ToNamespacedPath) { #endif } +TEST_F(PathTest, ToNamespacedPathString) { + const v8::HandleScope handle_scope(isolate_); + Argv argv; + Env env{handle_scope, argv, node::EnvironmentFlags::kNoBrowserGlobals}; +#ifdef _WIN32 + std::string data = ""; + ToNamespacedPath(*env, &data); + EXPECT_EQ(data, ""); // Empty string should not be mutated + std::string data_2 = "C://"; + ToNamespacedPath(*env, &data_2); + EXPECT_EQ(data_2, "\\\\?\\C:\\"); + std::string data_3 = + "C:\\workspace\\node-test-binary-windows-js-" + "suites\\node\\test\\fixtures\\permission\\deny\\protected-file.md"; + ToNamespacedPath(*env, &data_3); + EXPECT_EQ( + data_3, + "\\\\?\\C:\\workspace\\node-test-binary-windows-js-" + "suites\\node\\test\\fixtures\\permission\\deny\\protected-file.md"); + std::string data_4 = "\\\\?\\c:\\Windows/System"; + ToNamespacedPath(*env, &data_4); + EXPECT_EQ(data_4, "\\\\?\\c:\\Windows\\System"); + std::string data_5 = "\\\\server\\share\\file"; + ToNamespacedPath(*env, &data_5); + EXPECT_EQ(data_5, "\\\\?\\UNC\\server\\share\\file"); +#else + std::string data = "hello world"; + ToNamespacedPath(*env, &data); + EXPECT_EQ(data, "hello world"); // Input should not be mutated +#endif +} + #ifdef _WIN32 TEST_F(PathTest, NormalizeShortFileURLPath) { const v8::HandleScope handle_scope(isolate_); diff --git a/test/parallel/test-find-package-json.js b/test/parallel/test-find-package-json.js index d1df637dcc56..9258c54bb4e3 100644 --- a/test/parallel/test-find-package-json.js +++ b/test/parallel/test-find-package-json.js @@ -48,6 +48,13 @@ describe('findPackageJSON', () => { // Throws when no arguments are provided ); }); + it('should reject a drive-relative file URL', { skip: !common.isWindows }, () => { + assert.throws( + () => findPackageJSON('pkg', 'file:///C:foo/x.js'), + { code: 'ERR_INVALID_URL' }, + ); + }); + it('should be able to crawl up (CJS)', () => { const pathToMod = fixtures.path('packages/nested/sub-pkg-cjs/index.js'); const parentPkg = require(pathToMod);