ConfigFile.cpp 7.5 KB

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