SQLClient.cpp 6.3 KB

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