#include <libsolidity/interface/FileReader.h>
#include <liblangutil/Exceptions.h>
#include <libsolutil/CommonIO.h>
#include <libsolutil/Exceptions.h>
#include <libsolutil/StringUtils.h>
#include <boost/algorithm/string/predicate.hpp>
#include <range/v3/view/transform.hpp>
#include <range/v3/range/conversion.hpp>
#include <functional>
using solidity::frontend::ReadCallback;
using solidity::langutil::InternalCompilerError;
using solidity::util::errinfo_comment;
using solidity::util::readFileAsString;
using solidity::util::joinHumanReadable;
using std::map;
using std::reference_wrapper;
using std::string;
using std::vector;
namespace solidity::frontend
{
FileReader::FileReader(
boost::filesystem::path _basePath,
vector<boost::filesystem::path> const& _includePaths,
FileSystemPathSet _allowedDirectories
):
m_allowedDirectories(std::move(_allowedDirectories)),
m_sourceCodes()
{
setBasePath(_basePath);
for (boost::filesystem::path const& includePath: _includePaths)
addIncludePath(includePath);
for (boost::filesystem::path const& allowedDir: m_allowedDirectories)
solAssert(!allowedDir.empty(), "");
}
void FileReader::setBasePath(boost::filesystem::path const& _path)
{
if (_path.empty())
{
solAssert(m_includePaths.empty(), "");
m_basePath = "";
}
else
m_basePath = normalizeCLIPathForVFS(_path);
}
void FileReader::addIncludePath(boost::filesystem::path const& _path)
{
solAssert(!m_basePath.empty(), "");
solAssert(!_path.empty(), "");
m_includePaths.push_back(normalizeCLIPathForVFS(_path));
}
void FileReader::allowDirectory(boost::filesystem::path _path)
{
solAssert(!_path.empty(), "");
m_allowedDirectories.insert(std::move(_path));
}
void FileReader::addOrUpdateFile(boost::filesystem::path const& _path, SourceCode _source)
{
m_sourceCodes[cliPathToSourceUnitName(_path)] = std::move(_source);
}
void FileReader::setStdin(SourceCode _source)
{
m_sourceCodes["<stdin>"] = std::move(_source);
}
void FileReader::setSourceUnits(StringMap _sources)
{
m_sourceCodes = std::move(_sources);
}
ReadCallback::Result FileReader::readFile(string const& _kind, string const& _sourceUnitName)
{
try
{
if (_kind != ReadCallback::kindString(ReadCallback::Kind::ReadFile))
solAssert(false, "ReadFile callback used as callback kind " + _kind);
string strippedSourceUnitName = _sourceUnitName;
if (strippedSourceUnitName.find("file://") == 0)
strippedSourceUnitName.erase(0, 7);
vector<boost::filesystem::path> candidates;
vector<reference_wrapper<boost::filesystem::path>> prefixes = {m_basePath};
prefixes += (m_includePaths | ranges::to<vector<reference_wrapper<boost::filesystem::path>>>);
for (auto const& prefix: prefixes)
{
boost::filesystem::path canonicalPath = normalizeCLIPathForVFS(prefix / strippedSourceUnitName, SymlinkResolution::Enabled);
if (boost::filesystem::exists(canonicalPath))
candidates.push_back(std::move(canonicalPath));
}
auto pathToQuotedString = [](boost::filesystem::path const& _path){ return "\"" + _path.string() + "\""; };
if (candidates.empty())
return ReadCallback::Result{
false,
"File not found. Searched the following locations: " +
joinHumanReadable(prefixes | ranges::views::transform(pathToQuotedString), ", ") +
"."
};
if (candidates.size() >= 2)
return ReadCallback::Result{
false,
"Ambiguous import. "
"Multiple matching files found inside base path and/or include paths: " +
joinHumanReadable(candidates | ranges::views::transform(pathToQuotedString), ", ") +
"."
};
FileSystemPathSet allowedPaths =
m_allowedDirectories +
decltype(allowedPaths){m_basePath.empty() ? "." : m_basePath} +
m_includePaths;
bool isAllowed = false;
for (boost::filesystem::path const& allowedDir: allowedPaths)
if (isPathPrefix(normalizeCLIPathForVFS(allowedDir, SymlinkResolution::Enabled), candidates[0]))
{
isAllowed = true;
break;
}
if (!isAllowed)
return ReadCallback::Result{
false,
"File outside of allowed directories. The following are allowed: " +
joinHumanReadable(allowedPaths | ranges::views::transform(pathToQuotedString), ", ") +
"."
};
if (!boost::filesystem::is_regular_file(candidates[0]))
return ReadCallback::Result{false, "Not a valid file."};
auto contents = readFileAsString(candidates[0]);
solAssert(m_sourceCodes.count(_sourceUnitName) == 0, "");
m_sourceCodes[_sourceUnitName] = contents;
return ReadCallback::Result{true, contents};
}
catch (util::Exception const& _exception)
{
return ReadCallback::Result{false, "Exception in read callback: " + boost::diagnostic_information(_exception)};
}
catch (std::exception const& _exception)
{
return ReadCallback::Result{false, "Exception in read callback: " + boost::diagnostic_information(_exception)};
}
catch (...)
{
return ReadCallback::Result{false, "Unknown exception in read callback: " + boost::current_exception_diagnostic_information()};
}
}
string FileReader::cliPathToSourceUnitName(boost::filesystem::path const& _cliPath) const
{
vector<boost::filesystem::path> prefixes = {m_basePath.empty() ? normalizeCLIPathForVFS(".") : m_basePath};
prefixes += m_includePaths;
boost::filesystem::path normalizedPath = normalizeCLIPathForVFS(_cliPath);
for (boost::filesystem::path const& prefix: prefixes)
if (isPathPrefix(prefix, normalizedPath))
{
normalizedPath = stripPrefixIfPresent(prefix, normalizedPath);
break;
}
return normalizedPath.generic_string();
}
map<string, FileReader::FileSystemPathSet> FileReader::detectSourceUnitNameCollisions(FileSystemPathSet const& _cliPaths) const
{
map<string, FileReader::FileSystemPathSet> nameToPaths;
for (boost::filesystem::path const& cliPath: _cliPaths)
{
string sourceUnitName = cliPathToSourceUnitName(cliPath);
boost::filesystem::path normalizedPath = normalizeCLIPathForVFS(cliPath);
nameToPaths[sourceUnitName].insert(normalizedPath);
}
map<string, FileReader::FileSystemPathSet> collisions;
for (auto&& [sourceUnitName, cliPaths]: nameToPaths)
if (cliPaths.size() >= 2)
collisions[sourceUnitName] = std::move(cliPaths);
return collisions;
}
boost::filesystem::path FileReader::normalizeCLIPathForVFS(
boost::filesystem::path const& _path,
SymlinkResolution _symlinkResolution
)
{
boost::filesystem::path canonicalWorkDir = boost::filesystem::weakly_canonical(boost::filesystem::current_path());
boost::filesystem::path absolutePath = boost::filesystem::absolute(_path, canonicalWorkDir);
boost::filesystem::path normalizedPath;
if (_symlinkResolution == SymlinkResolution::Enabled)
{
normalizedPath = boost::filesystem::weakly_canonical(absolutePath);
if ((_path == "." || _path == "./" || _path == "../") && !boost::ends_with(normalizedPath.generic_string(), "/"))
normalizedPath = normalizedPath.parent_path() / (normalizedPath.filename().string() + "/");
}
else
{
solAssert(_symlinkResolution == SymlinkResolution::Disabled, "");
normalizedPath = absolutePath.lexically_normal();
}
solAssert(normalizedPath.is_absolute() || normalizedPath.root_path() == "/", "");
boost::filesystem::path normalizedRootPath = normalizeCLIRootPathForVFS(normalizedPath, canonicalWorkDir);
boost::filesystem::path dotDotPrefix = absoluteDotDotPrefix(normalizedPath);
boost::filesystem::path normalizedPathNoDotDot = normalizedPath;
if (dotDotPrefix.empty())
normalizedPathNoDotDot = normalizedRootPath / normalizedPath.relative_path();
else
normalizedPathNoDotDot = normalizedRootPath / normalizedPath.lexically_relative(normalizedPath.root_path() / dotDotPrefix);
solAssert(!hasDotDotSegments(normalizedPathNoDotDot), "");
normalizedPathNoDotDot = normalizedPathNoDotDot.generic_string();
if (normalizedPathNoDotDot == "/.")
return "/";
return normalizedPathNoDotDot;
}
boost::filesystem::path FileReader::normalizeCLIRootPathForVFS(
boost::filesystem::path const& _path,
boost::filesystem::path const& _workDir
)
{
solAssert(_workDir.is_absolute(), "");
boost::filesystem::path absolutePath = boost::filesystem::absolute(_path, _workDir);
boost::filesystem::path rootPath = absolutePath.root_path();
boost::filesystem::path baseRootPath = _workDir.root_path();
if (isUNCPath(absolutePath))
return rootPath;
if (boost::filesystem::equivalent(rootPath, baseRootPath))
return "/";
return rootPath;
}
bool FileReader::isPathPrefix(boost::filesystem::path const& _prefix, boost::filesystem::path const& _path)
{
solAssert(!_prefix.empty() && !_path.empty(), "");
solAssert(_prefix.is_absolute() || isUNCPath(_prefix) || _prefix.root_path() == "/", "");
solAssert(_path.is_absolute() || isUNCPath(_path) || _path.root_path() == "/", "");
solAssert(_prefix == _prefix.lexically_normal() && _path == _path.lexically_normal(), "");
solAssert(!hasDotDotSegments(_prefix) && !hasDotDotSegments(_path), "");
boost::filesystem::path strippedPath = _path.lexically_relative(
_prefix.filename_is_dot() ? _prefix.parent_path() : _prefix
);
return !strippedPath.empty() && *strippedPath.begin() != "..";
}
boost::filesystem::path FileReader::stripPrefixIfPresent(boost::filesystem::path const& _prefix, boost::filesystem::path const& _path)
{
if (!isPathPrefix(_prefix, _path))
return _path;
boost::filesystem::path strippedPath = _path.lexically_relative(
_prefix.filename_is_dot() ? _prefix.parent_path() : _prefix
);
solAssert(strippedPath.empty() || *strippedPath.begin() != "..", "");
return strippedPath;
}
boost::filesystem::path FileReader::absoluteDotDotPrefix(boost::filesystem::path const& _path)
{
solAssert(_path.is_absolute() || _path.root_path() == "/", "");
boost::filesystem::path _pathWithoutRoot = _path.relative_path();
boost::filesystem::path prefix;
for (boost::filesystem::path const& segment: _pathWithoutRoot)
if (segment.filename_is_dot_dot())
prefix /= segment;
return prefix;
}
bool FileReader::hasDotDotSegments(boost::filesystem::path const& _path)
{
for (boost::filesystem::path const& segment: _path)
if (segment.filename_is_dot_dot())
return true;
return false;
}
bool FileReader::isUNCPath(boost::filesystem::path const& _path)
{
string rootName = _path.root_name().string();
return (
rootName.size() == 2 ||
(rootName.size() > 2 && rootName[2] != rootName[1])
) && (
(rootName[0] == '/' && rootName[1] == '/')
#if defined(_WIN32)
|| (rootName[0] == '\\' && rootName[1] == '\\')
#endif
);
}
}