SQLClient.cpp 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. /*
  2. * Copyright (c) 2021, Jan de Visser <jan@de-visser.net>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/DeprecatedString.h>
  8. #include <LibSQL/SQLClient.h>
  9. #if !defined(AK_OS_SERENITY)
  10. # include <LibCore/Directory.h>
  11. # include <LibCore/File.h>
  12. # include <LibCore/SocketAddress.h>
  13. # include <LibCore/StandardPaths.h>
  14. # include <LibCore/Stream.h>
  15. # include <LibCore/System.h>
  16. #endif
  17. namespace SQL {
  18. #if !defined(AK_OS_SERENITY)
  19. // This is heavily based on how SystemServer's Service creates its socket.
  20. static ErrorOr<int> create_database_socket(DeprecatedString const& socket_path)
  21. {
  22. if (Core::File::exists(socket_path))
  23. TRY(Core::System::unlink(socket_path));
  24. # ifdef SOCK_NONBLOCK
  25. auto socket_fd = TRY(Core::System::socket(AF_LOCAL, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0));
  26. # else
  27. auto socket_fd = TRY(Core::System::socket(AF_LOCAL, SOCK_STREAM, 0));
  28. int option = 1;
  29. TRY(Core::System::ioctl(socket_fd, FIONBIO, &option));
  30. TRY(Core::System::fcntl(socket_fd, F_SETFD, FD_CLOEXEC));
  31. # endif
  32. TRY(Core::System::fchmod(socket_fd, 0600));
  33. auto socket_address = Core::SocketAddress::local(socket_path);
  34. auto socket_address_un = socket_address.to_sockaddr_un().release_value();
  35. TRY(Core::System::bind(socket_fd, reinterpret_cast<sockaddr*>(&socket_address_un), sizeof(socket_address_un)));
  36. TRY(Core::System::listen(socket_fd, 16));
  37. return socket_fd;
  38. }
  39. static ErrorOr<void> launch_server(DeprecatedString const& socket_path, DeprecatedString const& pid_path, StringView server_path)
  40. {
  41. auto server_fd = TRY(create_database_socket(socket_path));
  42. auto server_pid = TRY(Core::System::fork());
  43. if (server_pid == 0) {
  44. TRY(Core::System::setsid());
  45. TRY(Core::System::signal(SIGCHLD, SIG_IGN));
  46. server_pid = TRY(Core::System::fork());
  47. if (server_pid != 0) {
  48. auto server_pid_file = TRY(Core::Stream::File::open(pid_path, Core::Stream::OpenMode::Write));
  49. TRY(server_pid_file->write(DeprecatedString::number(server_pid).bytes()));
  50. exit(0);
  51. }
  52. server_fd = TRY(Core::System::dup(server_fd));
  53. auto takeover_string = DeprecatedString::formatted("{}:{}", socket_path, server_fd);
  54. TRY(Core::System::setenv("SOCKET_TAKEOVER"sv, takeover_string, true));
  55. auto arguments = Array {
  56. server_path,
  57. "--pid-file"sv,
  58. pid_path,
  59. };
  60. auto result = Core::System::exec(arguments[0], arguments, Core::System::SearchInPath::Yes);
  61. if (result.is_error()) {
  62. warnln("Could not launch {}: {}", server_path, result.error());
  63. TRY(Core::System::unlink(pid_path));
  64. }
  65. VERIFY_NOT_REACHED();
  66. }
  67. TRY(Core::System::waitpid(server_pid));
  68. return {};
  69. }
  70. static ErrorOr<bool> should_launch_server(DeprecatedString const& pid_path)
  71. {
  72. if (!Core::File::exists(pid_path))
  73. return true;
  74. Optional<pid_t> pid;
  75. {
  76. auto server_pid_file = Core::Stream::File::open(pid_path, Core::Stream::OpenMode::Read);
  77. if (server_pid_file.is_error()) {
  78. warnln("Could not open SQLServer PID file '{}': {}", pid_path, server_pid_file.error());
  79. return server_pid_file.release_error();
  80. }
  81. auto contents = server_pid_file.value()->read_all();
  82. if (contents.is_error()) {
  83. warnln("Could not read SQLServer PID file '{}': {}", pid_path, contents.error());
  84. return contents.release_error();
  85. }
  86. pid = StringView { contents.value() }.to_int<pid_t>();
  87. }
  88. if (!pid.has_value()) {
  89. warnln("SQLServer PID file '{}' exists, but with an invalid PID", pid_path);
  90. TRY(Core::System::unlink(pid_path));
  91. return true;
  92. }
  93. if (kill(*pid, 0) < 0) {
  94. warnln("SQLServer PID file '{}' exists with PID {}, but process cannot be found", pid_path, *pid);
  95. TRY(Core::System::unlink(pid_path));
  96. return true;
  97. }
  98. return false;
  99. }
  100. ErrorOr<NonnullRefPtr<SQLClient>> SQLClient::launch_server_and_create_client(StringView server_path)
  101. {
  102. auto runtime_directory = TRY(Core::StandardPaths::runtime_directory());
  103. auto socket_path = DeprecatedString::formatted("{}/SQLServer.socket", runtime_directory);
  104. auto pid_path = DeprecatedString::formatted("{}/SQLServer.pid", runtime_directory);
  105. if (TRY(should_launch_server(pid_path)))
  106. TRY(launch_server(socket_path, pid_path, server_path));
  107. auto socket = TRY(Core::Stream::LocalSocket::connect(move(socket_path)));
  108. TRY(socket->set_blocking(true));
  109. return adopt_nonnull_ref_or_enomem(new (nothrow) SQLClient(std::move(socket)));
  110. }
  111. #endif
  112. void SQLClient::execution_error(u64 statement_id, u64 execution_id, SQLErrorCode const& code, DeprecatedString const& message)
  113. {
  114. if (on_execution_error)
  115. on_execution_error(statement_id, execution_id, code, message);
  116. else
  117. warnln("Execution error for statement_id {}: {} ({})", statement_id, message, to_underlying(code));
  118. }
  119. void SQLClient::execution_success(u64 statement_id, u64 execution_id, bool has_results, size_t created, size_t updated, size_t deleted)
  120. {
  121. if (on_execution_success)
  122. on_execution_success(statement_id, execution_id, has_results, created, updated, deleted);
  123. else
  124. outln("{} row(s) created, {} updated, {} deleted", created, updated, deleted);
  125. }
  126. void SQLClient::next_result(u64 statement_id, u64 execution_id, Vector<SQL::Value> const& row)
  127. {
  128. if (on_next_result) {
  129. on_next_result(statement_id, execution_id, row);
  130. return;
  131. }
  132. bool first = true;
  133. for (auto& column : row) {
  134. if (!first)
  135. out(", ");
  136. out("\"{}\"", column);
  137. first = false;
  138. }
  139. outln();
  140. }
  141. void SQLClient::results_exhausted(u64 statement_id, u64 execution_id, size_t total_rows)
  142. {
  143. if (on_results_exhausted)
  144. on_results_exhausted(statement_id, execution_id, total_rows);
  145. else
  146. outln("{} total row(s)", total_rows);
  147. }
  148. }