SQLClient.cpp 6.0 KB

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