SQLClient.cpp 6.6 KB

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