ConfigFile.cpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, networkException <networkexception@serenityos.org>
  4. * Copyright (c) 2022, Sam Atkins <atkinssj@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/LexicalPath.h>
  9. #include <AK/StringBuilder.h>
  10. #include <LibCore/ConfigFile.h>
  11. #include <LibCore/Directory.h>
  12. #include <LibCore/StandardPaths.h>
  13. #include <LibCore/System.h>
  14. #include <pwd.h>
  15. #include <sys/types.h>
  16. namespace Core {
  17. ErrorOr<NonnullRefPtr<ConfigFile>> ConfigFile::open_for_lib(DeprecatedString const& lib_name, AllowWriting allow_altering)
  18. {
  19. DeprecatedString directory_name = DeprecatedString::formatted("{}/lib", StandardPaths::config_directory());
  20. auto directory = TRY(Directory::create(directory_name, Directory::CreateDirectories::Yes));
  21. auto path = DeprecatedString::formatted("{}/{}.ini", directory, lib_name);
  22. return ConfigFile::open(path, allow_altering);
  23. }
  24. ErrorOr<NonnullRefPtr<ConfigFile>> ConfigFile::open_for_app(DeprecatedString const& app_name, AllowWriting allow_altering)
  25. {
  26. auto directory = TRY(Directory::create(StandardPaths::config_directory(), Directory::CreateDirectories::Yes));
  27. auto path = DeprecatedString::formatted("{}/{}.ini", directory, app_name);
  28. return ConfigFile::open(path, allow_altering);
  29. }
  30. ErrorOr<NonnullRefPtr<ConfigFile>> ConfigFile::open_for_system(DeprecatedString const& app_name, AllowWriting allow_altering)
  31. {
  32. auto path = DeprecatedString::formatted("/etc/{}.ini", app_name);
  33. return ConfigFile::open(path, allow_altering);
  34. }
  35. ErrorOr<NonnullRefPtr<ConfigFile>> ConfigFile::open(DeprecatedString const& filename, AllowWriting allow_altering)
  36. {
  37. auto maybe_file = File::open(filename, allow_altering == AllowWriting::Yes ? File::OpenMode::ReadWrite : File::OpenMode::Read);
  38. OwnPtr<InputBufferedFile> buffered_file;
  39. if (maybe_file.is_error()) {
  40. // If we attempted to open a read-only file that does not exist, we ignore the error, making it appear
  41. // the same as if we had opened an empty file. This behavior is a little weird, but is required by
  42. // user code, which does not check the config file exists before opening.
  43. if (!(allow_altering == AllowWriting::No && maybe_file.error().code() == ENOENT))
  44. return maybe_file.release_error();
  45. } else {
  46. buffered_file = TRY(InputBufferedFile::create(maybe_file.release_value()));
  47. }
  48. auto config_file = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) ConfigFile(filename, move(buffered_file))));
  49. TRY(config_file->reparse());
  50. return config_file;
  51. }
  52. ErrorOr<NonnullRefPtr<ConfigFile>> ConfigFile::open(DeprecatedString const& filename, int fd)
  53. {
  54. auto file = TRY(File::adopt_fd(fd, File::OpenMode::ReadWrite));
  55. return open(filename, move(file));
  56. }
  57. ErrorOr<NonnullRefPtr<ConfigFile>> ConfigFile::open(DeprecatedString const& filename, NonnullOwnPtr<Core::File> file)
  58. {
  59. auto buffered_file = TRY(InputBufferedFile::create(move(file)));
  60. auto config_file = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) ConfigFile(filename, move(buffered_file))));
  61. TRY(config_file->reparse());
  62. return config_file;
  63. }
  64. ConfigFile::ConfigFile(DeprecatedString const& filename, OwnPtr<InputBufferedFile> open_file)
  65. : m_filename(filename)
  66. , m_file(move(open_file))
  67. {
  68. }
  69. ConfigFile::~ConfigFile()
  70. {
  71. MUST(sync());
  72. }
  73. ErrorOr<void> ConfigFile::reparse()
  74. {
  75. m_groups.clear();
  76. if (!m_file)
  77. return {};
  78. HashMap<DeprecatedString, DeprecatedString>* current_group = nullptr;
  79. auto buffer = TRY(ByteBuffer::create_uninitialized(4096));
  80. while (TRY(m_file->can_read_line())) {
  81. auto line = TRY(m_file->read_line(buffer));
  82. size_t i = 0;
  83. while (i < line.length() && (line[i] == ' ' || line[i] == '\t' || line[i] == '\n'))
  84. ++i;
  85. if (i >= line.length())
  86. continue;
  87. switch (line[i]) {
  88. case '#': // Comment, skip entire line.
  89. case ';': // -||-
  90. continue;
  91. case '[': { // Start of new group.
  92. StringBuilder builder;
  93. ++i; // Skip the '['
  94. while (i < line.length() && (line[i] != ']')) {
  95. builder.append(line[i]);
  96. ++i;
  97. }
  98. current_group = &m_groups.ensure(builder.to_deprecated_string());
  99. break;
  100. }
  101. default: { // Start of key
  102. StringBuilder key_builder;
  103. StringBuilder value_builder;
  104. while (i < line.length() && (line[i] != '=')) {
  105. key_builder.append(line[i]);
  106. ++i;
  107. }
  108. ++i; // Skip the '='
  109. while (i < line.length() && (line[i] != '\n')) {
  110. value_builder.append(line[i]);
  111. ++i;
  112. }
  113. if (!current_group) {
  114. // We're not in a group yet, create one with the name ""...
  115. current_group = &m_groups.ensure("");
  116. }
  117. auto value_string = value_builder.to_deprecated_string();
  118. current_group->set(key_builder.to_deprecated_string(), value_string.trim_whitespace(TrimMode::Right));
  119. }
  120. }
  121. }
  122. return {};
  123. }
  124. Optional<DeprecatedString> ConfigFile::read_entry_optional(const AK::DeprecatedString& group, const AK::DeprecatedString& key) const
  125. {
  126. if (!has_key(group, key))
  127. return {};
  128. auto it = m_groups.find(group);
  129. auto jt = it->value.find(key);
  130. return jt->value;
  131. }
  132. bool ConfigFile::read_bool_entry(DeprecatedString const& group, DeprecatedString const& key, bool default_value) const
  133. {
  134. auto value = read_entry(group, key, default_value ? "true" : "false");
  135. return value == "1" || value.equals_ignoring_ascii_case("true"sv);
  136. }
  137. void ConfigFile::write_entry(DeprecatedString const& group, DeprecatedString const& key, DeprecatedString const& value)
  138. {
  139. m_groups.ensure(group).ensure(key) = value;
  140. m_dirty = true;
  141. }
  142. void ConfigFile::write_bool_entry(DeprecatedString const& group, DeprecatedString const& key, bool value)
  143. {
  144. write_entry(group, key, value ? "true" : "false");
  145. }
  146. ErrorOr<void> ConfigFile::sync()
  147. {
  148. if (!m_dirty)
  149. return {};
  150. if (!m_file)
  151. return Error::from_errno(ENOENT);
  152. TRY(m_file->truncate(0));
  153. TRY(m_file->seek(0, SeekMode::SetPosition));
  154. for (auto& it : m_groups) {
  155. TRY(m_file->write_until_depleted(DeprecatedString::formatted("[{}]\n", it.key).bytes()));
  156. for (auto& jt : it.value)
  157. TRY(m_file->write_until_depleted(DeprecatedString::formatted("{}={}\n", jt.key, jt.value).bytes()));
  158. TRY(m_file->write_until_depleted("\n"sv.bytes()));
  159. }
  160. m_dirty = false;
  161. return {};
  162. }
  163. void ConfigFile::dump() const
  164. {
  165. for (auto& it : m_groups) {
  166. outln("[{}]", it.key);
  167. for (auto& jt : it.value)
  168. outln("{}={}", jt.key, jt.value);
  169. outln();
  170. }
  171. }
  172. Vector<DeprecatedString> ConfigFile::groups() const
  173. {
  174. return m_groups.keys();
  175. }
  176. Vector<DeprecatedString> ConfigFile::keys(DeprecatedString const& group) const
  177. {
  178. auto it = m_groups.find(group);
  179. if (it == m_groups.end())
  180. return {};
  181. return it->value.keys();
  182. }
  183. bool ConfigFile::has_key(DeprecatedString const& group, DeprecatedString const& key) const
  184. {
  185. auto it = m_groups.find(group);
  186. if (it == m_groups.end())
  187. return {};
  188. return it->value.contains(key);
  189. }
  190. bool ConfigFile::has_group(DeprecatedString const& group) const
  191. {
  192. return m_groups.contains(group);
  193. }
  194. void ConfigFile::add_group(DeprecatedString const& group)
  195. {
  196. m_groups.ensure(group);
  197. m_dirty = true;
  198. }
  199. void ConfigFile::remove_group(DeprecatedString const& group)
  200. {
  201. m_groups.remove(group);
  202. m_dirty = true;
  203. }
  204. void ConfigFile::remove_entry(DeprecatedString const& group, DeprecatedString const& key)
  205. {
  206. auto it = m_groups.find(group);
  207. if (it == m_groups.end())
  208. return;
  209. it->value.remove(key);
  210. m_dirty = true;
  211. }
  212. }