ConfigFile.cpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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 = Stream::File::open(filename, allow_altering == AllowWriting::Yes ? Stream::OpenMode::ReadWrite : Stream::OpenMode::Read);
  38. OwnPtr<Stream::BufferedFile> 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(Stream::BufferedFile::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(Stream::File::adopt_fd(fd, Stream::OpenMode::ReadWrite));
  55. return open(filename, move(file));
  56. }
  57. ErrorOr<NonnullRefPtr<ConfigFile>> ConfigFile::open(DeprecatedString const& filename, NonnullOwnPtr<Core::Stream::File> file)
  58. {
  59. auto buffered_file = TRY(Stream::BufferedFile::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<Stream::BufferedFile> 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. DeprecatedString ConfigFile::read_entry(DeprecatedString const& group, DeprecatedString const& key, DeprecatedString const& default_value) const
  125. {
  126. if (!has_key(group, key)) {
  127. return default_value;
  128. }
  129. auto it = m_groups.find(group);
  130. auto jt = it->value.find(key);
  131. return jt->value;
  132. }
  133. bool ConfigFile::read_bool_entry(DeprecatedString const& group, DeprecatedString const& key, bool default_value) const
  134. {
  135. auto value = read_entry(group, key, default_value ? "true" : "false");
  136. return value == "1" || value.equals_ignoring_case("true"sv);
  137. }
  138. void ConfigFile::write_entry(DeprecatedString const& group, DeprecatedString const& key, DeprecatedString const& value)
  139. {
  140. m_groups.ensure(group).ensure(key) = value;
  141. m_dirty = true;
  142. }
  143. void ConfigFile::write_bool_entry(DeprecatedString const& group, DeprecatedString const& key, bool value)
  144. {
  145. write_entry(group, key, value ? "true" : "false");
  146. }
  147. ErrorOr<void> ConfigFile::sync()
  148. {
  149. if (!m_dirty)
  150. return {};
  151. if (!m_file)
  152. return Error::from_errno(ENOENT);
  153. TRY(m_file->truncate(0));
  154. TRY(m_file->seek(0, SeekMode::SetPosition));
  155. for (auto& it : m_groups) {
  156. TRY(m_file->write(DeprecatedString::formatted("[{}]\n", it.key).bytes()));
  157. for (auto& jt : it.value)
  158. TRY(m_file->write(DeprecatedString::formatted("{}={}\n", jt.key, jt.value).bytes()));
  159. TRY(m_file->write("\n"sv.bytes()));
  160. }
  161. m_dirty = false;
  162. return {};
  163. }
  164. void ConfigFile::dump() const
  165. {
  166. for (auto& it : m_groups) {
  167. outln("[{}]", it.key);
  168. for (auto& jt : it.value)
  169. outln("{}={}", jt.key, jt.value);
  170. outln();
  171. }
  172. }
  173. Vector<DeprecatedString> ConfigFile::groups() const
  174. {
  175. return m_groups.keys();
  176. }
  177. Vector<DeprecatedString> ConfigFile::keys(DeprecatedString const& group) const
  178. {
  179. auto it = m_groups.find(group);
  180. if (it == m_groups.end())
  181. return {};
  182. return it->value.keys();
  183. }
  184. bool ConfigFile::has_key(DeprecatedString const& group, DeprecatedString const& key) const
  185. {
  186. auto it = m_groups.find(group);
  187. if (it == m_groups.end())
  188. return {};
  189. return it->value.contains(key);
  190. }
  191. bool ConfigFile::has_group(DeprecatedString const& group) const
  192. {
  193. return m_groups.contains(group);
  194. }
  195. void ConfigFile::add_group(DeprecatedString const& group)
  196. {
  197. m_groups.ensure(group);
  198. m_dirty = true;
  199. }
  200. void ConfigFile::remove_group(DeprecatedString const& group)
  201. {
  202. m_groups.remove(group);
  203. m_dirty = true;
  204. }
  205. void ConfigFile::remove_entry(DeprecatedString const& group, DeprecatedString const& key)
  206. {
  207. auto it = m_groups.find(group);
  208. if (it == m_groups.end())
  209. return;
  210. it->value.remove(key);
  211. m_dirty = true;
  212. }
  213. }