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 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
|
// Copyright Contributors to the DNF5 project.
// Copyright Contributors to the libdnf project.
// SPDX-License-Identifier: GPL-2.0-or-later
//
// This file is part of libdnf: https://github.com/rpm-software-management/libdnf/
//
// Libdnf is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// Libdnf is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with libdnf. If not, see <https://www.gnu.org/licenses/>.
#include "addrepo.hpp"
#include "shared.hpp"
#include <curl/curl.h>
#include <fmt/format.h>
#include <libdnf5/repo/file_downloader.hpp>
#include <libdnf5/utils/bgettext/bgettext-mark-domain.h>
#include <zlib.h>
#include <regex>
#include <string_view>
namespace dnf5 {
using namespace libdnf5;
namespace {
// Extracts a specific part of the URL from a URL string.
// Returns an empty string if the URL is not valid/supported or the required part is not present.
std::string get_url_part(const std::string & url, CURLUPart what_part) {
std::string ret;
CURLUcode rc;
CURLU * c_url = curl_url();
rc = curl_url_set(c_url, CURLUPART_URL, url.c_str(), 0);
if (!rc) {
char * part;
rc = curl_url_get(c_url, what_part, &part, 0);
if (!rc) {
ret = part;
curl_free(part);
}
}
curl_url_cleanup(c_url);
return ret;
}
// Converts all letters consider illegal in repository id to their "_XX" versions (XX - hex code).
std::string escape(const std::string & text) {
static constexpr const char * digits = "0123456789ABCDEF";
char tmp[] = "_XX";
std::string ret;
ret.reserve(text.size() * 3);
for (const char ch : text) {
if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || ch == '-' ||
ch == '.' || ch == ':' || ch == '_') {
ret += ch;
} else {
const auto uch = static_cast<unsigned char>(ch);
tmp[2] = digits[uch & 0x0F];
tmp[1] = digits[(uch >> 4) & 0x0F];
ret += tmp;
}
}
return ret;
}
// Regular expressions to sanitise repository id
const std::regex RE_SCHEME{R"(^\w+:/*(\w+:|www\.)?)"};
const std::regex RE_SLASH{R"([?/:&#|~\*\[\]\(\)'\\]+)"};
const std::regex RE_BEGIN{"^[,.]*"};
const std::regex RE_FINAL{"[,.]*$"};
// Generates a repository id from a URL.
// Strips dangerous and common characters, encodes some characters and limits the length.
std::string generate_repoid_from_url(const std::string & url) {
std::string ret;
ret = std::regex_replace(url, RE_SCHEME, "");
ret = std::regex_replace(ret, RE_SLASH, "_");
ret = std::regex_replace(ret, RE_BEGIN, "");
ret = std::regex_replace(ret, RE_FINAL, "");
ret = escape(ret);
// Limits the length of the repository id.
// Copies the first and last 100 characters. The substring in between is replaced by a crc32 hash.
if (ret.size() > 250) {
size_t sz = ret.size();
ret = fmt::format(
"{}-{:08X}-{}",
ret.substr(0, 100),
crc32_z(0, ((const unsigned char *)ret.c_str()) + 100, sz - 200),
ret.substr(sz - 100));
}
return ret;
}
} // namespace
void ConfigManagerAddRepoCommand::set_argument_parser() {
auto & ctx = get_context();
auto & parser = ctx.get_argument_parser();
auto & cmd = *get_argument_parser_command();
cmd.set_description(
"Add repositories from the specified configuration file or define a new repository using user options");
cmd.set_long_description(
"Add repositories from the specified configuration file or define a new repository using user options.");
auto from_repofile_opt = parser.add_new_named_arg("from-repofile");
from_repofile_opt->set_long_name("from-repofile");
from_repofile_opt->set_description("Download repository configuration file, test it and put it in reposdir");
from_repofile_opt->set_has_value(true);
from_repofile_opt->set_arg_value_help("REPO_CONFIGURATION_FILE_URL");
from_repofile_opt->set_parse_hook_func([this](cli::ArgumentParser::NamedArg *, const char *, const char * value) {
source_repofile.location = value;
// If the URL is invalid. Scheme not found. It can be a path to a local file.
source_repofile.is_local_path = get_url_part(source_repofile.location, CURLUPART_SCHEME) == "";
if (source_repofile.is_local_path) {
// Tests whether it is really a path to an existing local file.
try {
if (!std::filesystem::exists(source_repofile.location)) {
throw ConfigManagerError(M_("from-repofile: \"{}\" file does not exist"), source_repofile.location);
}
} catch (const std::filesystem::filesystem_error & ex) {
throw ConfigManagerError(M_("from-repofile: {}"), std::string{ex.what()});
}
}
return true;
});
cmd.register_named_arg(from_repofile_opt);
auto repo_id_opt = parser.add_new_named_arg("id");
repo_id_opt->set_long_name("id");
repo_id_opt->set_description("Set id for newly created repository");
repo_id_opt->set_has_value(true);
repo_id_opt->set_arg_value_help("REPO_ID");
repo_id_opt->set_parse_hook_func([this](cli::ArgumentParser::NamedArg *, const char *, const char * value) {
repo_id = value;
return true;
});
cmd.register_named_arg(repo_id_opt);
auto set_opt = parser.add_new_named_arg("set");
set_opt->set_long_name("set");
set_opt->set_description("Set option in newly created repository");
set_opt->set_has_value(true);
set_opt->set_arg_value_help("REPO_OPTION=VALUE");
set_opt->set_parse_hook_func([this](
[[maybe_unused]] cli::ArgumentParser::NamedArg * arg,
[[maybe_unused]] const char * option,
const char * value) {
const auto * const val = strchr(value + 1, '=');
if (!val) {
throw cli::ArgumentParserError(
M_("{}: Badly formatted argument value \"{}\""), std::string{"set"}, std::string{value});
}
std::string key{value, val};
std::string key_value{val + 1};
// Test if the repository option can be set.
try {
tmp_repo_conf.opt_binds().at(key).new_string(Option::Priority::RUNTIME, key_value);
} catch (const Error & ex) {
throw ConfigManagerError(
M_("Cannot set repository option \"{}={}\": {}"), key, key_value, std::string{ex.what()});
}
// Save the repo option for later writing to a file.
const auto [it, inserted] = repo_opts.insert({key, key_value});
if (!inserted) {
if (it->second != key_value) {
throw ConfigManagerError(
M_("Sets the \"{}\" option again with a different value: \"{}\" != \"{}\""),
key,
it->second,
key_value);
}
}
return true;
});
cmd.register_named_arg(set_opt);
auto add_or_replace = parser.add_new_named_arg("add-or-replace");
add_or_replace->set_long_name("add-or-replace");
add_or_replace->set_description("Allow adding or replacing a repository in the existing configuration file");
add_or_replace->set_has_value(false);
add_or_replace->set_parse_hook_func([this](cli::ArgumentParser::NamedArg *, const char *, const char *) {
file_policy = FilePolicy::ADD_OR_REPLACE;
return true;
});
cmd.register_named_arg(add_or_replace);
auto create_missing_dirs_opt = parser.add_new_named_arg("create-missing-dir");
create_missing_dirs_opt->set_long_name("create-missing-dir");
create_missing_dirs_opt->set_description("Allow creation of missing directories");
create_missing_dirs_opt->set_has_value(false);
create_missing_dirs_opt->set_parse_hook_func([this](cli::ArgumentParser::NamedArg *, const char *, const char *) {
create_missing_dirs = true;
return true;
});
cmd.register_named_arg(create_missing_dirs_opt);
auto overwrite_opt = parser.add_new_named_arg("overwrite");
overwrite_opt->set_long_name("overwrite");
overwrite_opt->set_description("Allow overwriting of existing repository configuration file");
overwrite_opt->set_has_value(false);
overwrite_opt->set_parse_hook_func([this](cli::ArgumentParser::NamedArg *, const char *, const char *) {
file_policy = FilePolicy::OVERWRITE;
return true;
});
cmd.register_named_arg(overwrite_opt);
auto save_filename_opt = parser.add_new_named_arg("save-filename");
save_filename_opt->set_long_name("save-filename");
save_filename_opt->set_description(
"Set the name of the configuration file of the added repository. The \".repo\" extension is added if it is "
"missing.");
save_filename_opt->set_has_value(true);
save_filename_opt->set_arg_value_help("FILENAME");
save_filename_opt->set_parse_hook_func([this](cli::ArgumentParser::NamedArg *, const char *, const char * value) {
save_filename = value;
return true;
});
cmd.register_named_arg(save_filename_opt);
// Set conflicting arguments
add_or_replace->add_conflict_argument(*from_repofile_opt);
repo_id_opt->add_conflict_argument(*from_repofile_opt);
set_opt->add_conflict_argument(*from_repofile_opt);
}
void ConfigManagerAddRepoCommand::configure() {
auto & ctx = get_context();
auto & base = ctx.get_base();
const auto & repo_dirs = base.get_config().get_reposdir_option().get_value();
if (repo_dirs.empty()) {
throw ConfigManagerError(M_("Missing path to repository configuration directory"));
}
std::filesystem::path dest_repo_dir = repo_dirs.front();
resolve_missing_dir(dest_repo_dir, create_missing_dirs);
if (source_repofile.location.empty()) {
create_repo(repo_id, repo_opts, dest_repo_dir);
} else {
add_repos_from_repofile(source_repofile, dest_repo_dir);
}
}
void ConfigManagerAddRepoCommand::add_repos_from_repofile(
const SourceRepofile & source_repofile, const std::filesystem::path & dest_repo_dir) {
auto & ctx = get_context();
auto & base = ctx.get_base();
auto logger = base.get_logger();
if (save_filename.empty()) {
if (source_repofile.is_local_path) {
save_filename = std::filesystem::path(source_repofile.location).filename();
} else {
save_filename = std::filesystem::path(get_url_part(source_repofile.location, CURLUPART_PATH)).filename();
}
}
if (!save_filename.ends_with(".repo")) {
save_filename += ".repo";
}
auto dest_path = dest_repo_dir / save_filename;
test_if_filepath_not_exist(dest_path, false);
// Creates an open temporary file. It then closes it but does not remove it.
// In the following code, this temporary file is used to store the copied/downloaded configuration.
auto tmpfilepath = dest_path.string() + ".XXXXXX";
auto fd = mkstemp(tmpfilepath.data());
if (fd == -1) {
throw std::filesystem::filesystem_error(
"cannot create temporary file", tmpfilepath, std::error_code(errno, std::system_category()));
}
close(fd);
try {
if (source_repofile.is_local_path) {
try {
std::filesystem::copy_file(
source_repofile.location, tmpfilepath, std::filesystem::copy_options::overwrite_existing);
} catch (const std::filesystem::filesystem_error & e) {
throw ConfigManagerError(
M_("Failed to copy repository configuration file \"{}\": {}"),
source_repofile.location,
std::string{e.what()});
}
} else {
try {
repo::FileDownloader downloader(base);
downloader.add(source_repofile.location, tmpfilepath);
downloader.download();
} catch (const repo::FileDownloadError & e) {
throw ConfigManagerError(
M_("Failed to download repository configuration file \"{}\": {}"),
source_repofile.location,
std::string{e.what()});
}
}
ConfigParser parser;
parser.read(tmpfilepath);
std::vector<std::string> repo_ids;
repo_ids.reserve(parser.get_data().size());
for (const auto & [repo_id, opts] : parser.get_data()) {
repo_ids.emplace_back(repo_id);
}
test_if_ids_not_already_exist(repo_ids, dest_path);
// Test if the repository options can be set.
for (const auto & [repo_id, repo_opts] : parser.get_data()) {
for (const auto & [key, key_val] : repo_opts) {
// Skip empty lines and comment lines (ConfigParser stores the empty line and comment line
// in an automatically generated key whose name starts with the '#' character).
if (key.starts_with('#')) {
continue;
}
try {
tmp_repo_conf.opt_binds().at(key).new_string(Option::Priority::RUNTIME, key_val);
} catch (const Error & ex) {
throw ConfigManagerError(
M_("Error in added repository configuration file. Cannot set repository option \"{}={}\": {}"),
key,
key_val,
std::string{ex.what()});
}
}
}
} catch (const Error & ex) {
std::error_code ec;
std::filesystem::remove(tmpfilepath, ec);
throw;
}
// All tests passed. Renames the configuration file to the final name.
std::filesystem::rename(tmpfilepath, dest_path);
logger->info("config-manager: Added repofile \"{}\" from \"{}\"", dest_path.string(), source_repofile.location);
set_file_permissions(dest_path);
}
void ConfigManagerAddRepoCommand::create_repo(
std::string repo_id,
const std::map<std::string, std::string> & repo_opts,
const std::filesystem::path & dest_repo_dir) {
auto & ctx = get_context();
auto & base = ctx.get_base();
auto logger = base.get_logger();
// Test for presence of required arguments.
// And sets the URL - used to create the repository ID if not specified.
std::string url;
if (const auto it = repo_opts.find("baseurl"); it != repo_opts.end() && !it->second.empty()) {
const auto urls = OptionStringList(std::vector<std::string>{}).from_string(it->second);
if (urls.empty() || (url = urls.front()).empty()) {
throw ConfigManagerError(M_("Bad baseurl: {}={}"), it->first, it->second);
}
} else if (const auto it = repo_opts.find("mirrorlist"); it != repo_opts.end() && !it->second.empty()) {
url = it->second;
} else if (const auto it = repo_opts.find("metalink"); it != repo_opts.end() && !it->second.empty()) {
url = it->second;
} else {
throw cli::ArgumentParserMissingDependentArgumentError(
M_("One of --from-repofile=<URL>, --set=baseurl=<URL>, --set=mirrorlist=<URL>, --set=metalink=<URL> "
"must be set to a non-empty URL"));
}
if (repo_id.empty()) {
repo_id = generate_repoid_from_url(url);
}
if (save_filename.empty()) {
save_filename = repo_id;
}
if (!save_filename.ends_with(".repo")) {
save_filename += ".repo";
}
auto dest_path = dest_repo_dir / save_filename;
test_if_filepath_not_exist(dest_path, true);
test_if_ids_not_already_exist({repo_id}, dest_path);
ConfigParser parser;
if (file_policy == FilePolicy::ADD_OR_REPLACE && std::filesystem::exists(dest_path)) {
parser.read(dest_path);
if (parser.has_section(repo_id)) {
// If the repository with the id already exists, it will be removed.
parser.remove_section(repo_id);
}
}
parser.add_section(repo_id);
// Sets the default repository name. May be overwritten with "--set=name=<name>".
parser.set_value(repo_id, "name", repo_id + " - Created by dnf5 config-manager");
// Enables repository by default. The repository can be disabled with "--set=enabled=0".
parser.set_value(repo_id, "enabled", "1");
for (const auto & [key, key_val] : repo_opts) {
parser.set_value(repo_id, key, key_val);
}
try {
parser.write(dest_path, false);
logger->info("config-manager: Added new repo \"{}\" to file \"{}\"", repo_id, dest_path.string());
} catch (const std::runtime_error & e) {
throw ConfigManagerError(
M_("Failed to save repository configuration file \"{}\": {}"), dest_path.native(), std::string{e.what()});
}
set_file_permissions(dest_path);
}
void ConfigManagerAddRepoCommand::test_if_filepath_not_exist(
const std::filesystem::path & path, bool show_hint_add_or_replace) const {
if (file_policy == FilePolicy::ERROR && std::filesystem::exists(path)) {
ConfigParser parser;
parser.read(path);
std::string repo_ids;
bool first{true};
for (const auto & [repo_id, opts] : parser.get_data()) {
if (first) {
first = false;
} else {
repo_ids += ' ';
}
repo_ids += repo_id;
}
constexpr BgettextMessage msg1 =
M_("File \"{}\" already exists and configures repositories with IDs \"{}\"."
" Add \"--add-or-replace\" or \"--overwrite\".");
constexpr BgettextMessage msg2 =
M_("File \"{}\" already exists and configures repositories with IDs \"{}\"."
" Add \"--overwrite\" to overwrite.");
throw ConfigManagerError(show_hint_add_or_replace ? msg1 : msg2, path.string(), repo_ids);
}
}
void ConfigManagerAddRepoCommand::test_if_ids_not_already_exist(
const std::vector<std::string> & repo_ids, const std::filesystem::path & ignore_path) const {
auto & ctx = get_context();
auto & base = ctx.get_base();
auto logger = base.get_logger();
// The repository can also be defined in the main configuration file.
if (const auto & conf_path = get_config_file_path(base.get_config()); std::filesystem::exists(conf_path)) {
ConfigParser parser;
parser.read(conf_path);
for (const auto & repo_id : repo_ids) {
if (parser.has_section(repo_id)) {
throw ConfigManagerError(
M_("A repository with id \"{}\" already configured in file: {}"), repo_id, conf_path.string());
}
}
}
const auto & repo_dirs = base.get_config().get_reposdir_option().get_value();
for (const std::filesystem::path dir : repo_dirs) {
if (std::filesystem::exists(dir)) {
std::error_code ec;
std::filesystem::directory_iterator di(dir, ec);
if (ec) {
write_warning(
*logger, M_("Cannot read repositories from directory \"{}\": {}"), dir.string(), ec.message());
continue;
}
for (auto & dentry : di) {
const auto & path = dentry.path();
if (path == ignore_path) {
continue;
}
if (path.extension() == ".repo") {
ConfigParser parser;
parser.read(path);
for (const auto & repo_id : repo_ids) {
if (parser.has_section(repo_id)) {
throw ConfigManagerError(
M_("A repository with id \"{}\" already configured in file: {}"),
repo_id,
path.string());
}
}
}
}
}
}
}
} // namespace dnf5
|