| 1 | // Copyright (c) 2016-2022, The Monero Project |
| 2 | // |
| 3 | // All rights reserved. |
| 4 | // |
| 5 | // Redistribution and use in source and binary forms, with or without modification, are |
| 6 | // permitted provided that the following conditions are met: |
| 7 | // |
| 8 | // 1. Redistributions of source code must retain the above copyright notice, this list of |
| 9 | // conditions and the following disclaimer. |
| 10 | // |
| 11 | // 2. Redistributions in binary form must reproduce the above copyright notice, this list |
| 12 | // of conditions and the following disclaimer in the documentation and/or other |
| 13 | // materials provided with the distribution. |
| 14 | // |
| 15 | // 3. Neither the name of the copyright holder nor the names of its contributors may be |
| 16 | // used to endorse or promote products derived from this software without specific |
| 17 | // prior written permission. |
| 18 | // |
| 19 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY |
| 20 | // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF |
| 21 | // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL |
| 22 | // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, |
| 24 | // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 25 | // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, |
| 26 | // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF |
| 27 | // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 28 | |
| 29 | #include "zmq_server.h" |
| 30 | |
| 31 | #include <chrono> |
| 32 | #include <cstring> |
| 33 | #include <utility> |
| 34 | #include <stdexcept> |
| 35 | #include <system_error> |
| 36 | |
| 37 | #include "byte_slice.h" |
| 38 | #include "rpc/zmq_pub.h" |
| 39 | |
| 40 | #undef MONERO_DEFAULT_LOG_CATEGORY |
| 41 | #define MONERO_DEFAULT_LOG_CATEGORY "net.zmq" |
| 42 | |
| 43 | namespace cryptonote |
| 44 | { |
| 45 | |
| 46 | namespace |
| 47 | { |
| 48 | constexpr const int num_zmq_threads = 1; |
| 49 | constexpr const std::int64_t max_message_size = 10 * 1024 * 1024; // 10 MiB |
| 50 | constexpr const std::chrono::seconds linger_timeout{2}; // wait period for pending out messages |
| 51 | |
| 52 | net::zmq::socket init_socket(void* context, int type, epee::span<const std::string> addresses) |
| 53 | { |
| 54 | if (context == nullptr) |
| 55 | throw std::logic_error{"NULL context provided"}; |
| 56 | |
| 57 | net::zmq::socket out{}; |
| 58 | out.reset(zmq_socket(context, type)); |
| 59 | if (!out) |
| 60 | { |
| 61 | MONERO_LOG_ZMQ_ERROR("Failed to create ZMQ socket"); |
| 62 | return nullptr; |
| 63 | } |
| 64 | |
| 65 | if (zmq_setsockopt(out.get(), ZMQ_MAXMSGSIZE, std::addressof(max_message_size), sizeof(max_message_size)) != 0) |
| 66 | { |
| 67 | MONERO_LOG_ZMQ_ERROR("Failed to set maximum incoming message size"); |
| 68 | return nullptr; |
| 69 | } |
| 70 | |
| 71 | static constexpr const int linger_value = std::chrono::milliseconds{linger_timeout}.count(); |
| 72 | if (zmq_setsockopt(out.get(), ZMQ_LINGER, std::addressof(linger_value), sizeof(linger_value)) != 0) |
| 73 | { |
| 74 | MONERO_LOG_ZMQ_ERROR("Failed to set linger timeout"); |
| 75 | return nullptr; |
| 76 | } |
| 77 | |
| 78 | for (const std::string& address : addresses) |
| 79 | { |
| 80 | if (zmq_bind(out.get(), address.c_str()) < 0) |
| 81 | { |
| 82 | MONERO_LOG_ZMQ_ERROR("ZMQ bind failed"); |
| 83 | return nullptr; |
| 84 | } |
| 85 | MINFO("ZMQ now listening at " << address); |
| 86 | } |
| 87 | |
| 88 | return out; |
| 89 | } |
| 90 | } // anonymous |
| 91 | |
| 92 | namespace rpc |
| 93 | { |
| 94 | |
| 95 | ZmqServer::ZmqServer(RpcHandler& h) : |
| 96 | handler(h), |
| 97 | context(zmq_init(num_zmq_threads)), |
| 98 | rep_socket(nullptr), |
| 99 | pub_socket(nullptr), |
| 100 | relay_socket(nullptr), |
| 101 | shared_state(nullptr) |
| 102 | { |
| 103 | if (!context) |
| 104 | MONERO_ZMQ_THROW("Unable to create ZMQ context"); |
| 105 | } |
| 106 | |
| 107 | ZmqServer::~ZmqServer() |
| 108 | { |
| 109 | } |
| 110 | |
| 111 | void ZmqServer::serve() |
| 112 | { |
| 113 | try |
| 114 | { |
| 115 | // socket must close before `zmq_term` will exit. |
| 116 | const net::zmq::socket rep = std::move(rep_socket); |
| 117 | const net::zmq::socket pub = std::move(pub_socket); |
| 118 | const net::zmq::socket relay = std::move(relay_socket); |
| 119 | const std::shared_ptr<listener::zmq_pub> state = std::move(shared_state); |
| 120 | |
| 121 | const unsigned init_count = unsigned(bool(pub)) + bool(relay) + bool(state); |
| 122 | if (!rep || (init_count && init_count != 3)) |
| 123 | { |
| 124 | MERROR("ZMQ RPC server socket is null"); |
| 125 | return; |
| 126 | } |
| 127 | |
| 128 | MINFO("ZMQ Server started"); |
| 129 | |
| 130 | const int read_flags = pub ? ZMQ_DONTWAIT : 0; |
| 131 | std::array<zmq_pollitem_t, 3> sockets = |
| 132 | {{ |
| 133 | {relay.get(), 0, ZMQ_POLLIN, 0}, |
| 134 | {pub.get(), 0, ZMQ_POLLIN, 0}, |
| 135 | {rep.get(), 0, ZMQ_POLLIN, 0} |
| 136 | }}; |
| 137 | |
| 138 | /* This uses XPUB to watch for subscribers, to reduce CPU cycles for |
| 139 | serialization when the data will be dropped. This is important for block |
| 140 | serialization, which is done on the p2p threads currently (see |
| 141 | zmq_pub.cpp). |
| 142 | |
| 143 | XPUB sockets are not thread-safe, so the p2p thread cannot write into |
| 144 | the socket while we read here for subscribers. A ZMQ_PAIR socket is |
| 145 | used for inproc notification. No data is every copied to kernel, it is |
| 146 | all userspace messaging. */ |
| 147 | |
| 148 | while (1) |
| 149 | { |
| 150 | if (pub) |
| 151 | MONERO_UNWRAP(net::zmq::retry_op(zmq_poll, sockets.data(), sockets.size(), -1)); |
| 152 | |
| 153 | if (sockets[0].revents) |
| 154 | state->relay_to_pub(relay.get(), pub.get()); |
| 155 | |
| 156 | if (sockets[1].revents) |
| 157 | state->sub_request(MONERO_UNWRAP(net::zmq::receive(pub.get(), ZMQ_DONTWAIT))); |
| 158 | |
| 159 | if (!pub || sockets[2].revents) |
| 160 | { |
| 161 | expect<std::string> message = net::zmq::receive(rep.get(), read_flags); |
| 162 | if (!message) |
| 163 | { |
| 164 | // EAGAIN can occur when using `zmq_poll`, which doesn't inspect for message validity |
| 165 | if (message != net::zmq::make_error_code(EAGAIN)) |
| 166 | MONERO_THROW(message.error(), "Read failure on ZMQ-RPC"); |
| 167 | } |
| 168 | else // no errors |
| 169 | { |
| 170 | MDEBUG("Received RPC request: \"" << *message << "\""); |
| 171 | epee::byte_slice response = handler.handle(std::move(*message)); |
| 172 | |
| 173 | const boost::string_ref response_view{reinterpret_cast<const char*>(response.data()), response.size()}; |
| 174 | MDEBUG("Sending RPC reply: \"" << response_view << "\""); |
| 175 | MONERO_UNWRAP(net::zmq::send(std::move(response), rep.get())); |
| 176 | } |
| 177 | } |
| 178 | } |
| 179 | } |
| 180 | catch (const std::system_error& e) |
| 181 | { |
| 182 | if (e.code() != net::zmq::make_error_code(ETERM)) |
| 183 | MERROR("ZMQ RPC Server Error: " << e.what()); |
| 184 | } |
| 185 | catch (const std::exception& e) |
| 186 | { |
| 187 | MERROR("ZMQ RPC Server Error: " << e.what()); |
| 188 | } |
| 189 | catch (...) |
| 190 | { |
| 191 | MERROR("Unknown error in ZMQ RPC server"); |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | void* ZmqServer::init_rpc(boost::string_ref address, boost::string_ref port) |
| 196 | { |
| 197 | if (!context) |
| 198 | { |
| 199 | MERROR("ZMQ RPC Server already shutdown"); |
| 200 | return nullptr; |
| 201 | } |
| 202 | |
| 203 | if (address.empty()) |
| 204 | address = "*"; |
| 205 | if (port.empty()) |
| 206 | port = "*"; |
| 207 | |
| 208 | std::string bind_address = "tcp://"; |
| 209 | bind_address.append(address.data(), address.size()); |
| 210 | bind_address += ":"; |
| 211 | bind_address.append(port.data(), port.size()); |
| 212 | |
| 213 | rep_socket = init_socket(context.get(), ZMQ_REP, {std::addressof(bind_address), 1}); |
| 214 | return bool(rep_socket) ? context.get() : nullptr; |
| 215 | } |
| 216 | |
| 217 | std::shared_ptr<listener::zmq_pub> ZmqServer::init_pub(epee::span<const std::string> addresses) |
| 218 | { |
| 219 | try |
| 220 | { |
| 221 | shared_state = std::make_shared<listener::zmq_pub>(context.get()); |
| 222 | pub_socket = init_socket(context.get(), ZMQ_XPUB, addresses); |
| 223 | if (!pub_socket) |
| 224 | throw std::runtime_error{"Unable to initialize ZMQ_XPUB socket"}; |
| 225 | |
| 226 | const std::string relay_address[] = {listener::zmq_pub::relay_endpoint()}; |
| 227 | relay_socket = init_socket(context.get(), ZMQ_PAIR, relay_address); |
| 228 | if (!relay_socket) |
| 229 | throw std::runtime_error{"Unable to initialize ZMQ_PAIR relay"}; |
| 230 | } |
| 231 | catch (const std::runtime_error& e) |
| 232 | { |
| 233 | shared_state = nullptr; |
| 234 | pub_socket = nullptr; |
| 235 | relay_socket = nullptr; |
| 236 | MERROR("Failed to create ZMQ/Pub listener: " << e.what()); |
| 237 | return nullptr; |
| 238 | } |
| 239 | |
| 240 | return shared_state; |
| 241 | } |
| 242 | |
| 243 | void ZmqServer::run() |
| 244 | { |
| 245 | run_thread = boost::thread(boost::bind(&ZmqServer::serve, this)); |
| 246 | } |
| 247 | |
| 248 | void ZmqServer::stop() |
| 249 | { |
| 250 | if (!run_thread.joinable()) |
| 251 | return; |
| 252 | |
| 253 | context.reset(); // destroying context terminates all calls |
| 254 | run_thread.join(); |
| 255 | } |
| 256 | |
| 257 | } // namespace cryptonote |
| 258 | |
| 259 | } // namespace rpc |