io_fetch.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. // Copyright (C) 2011 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <config.h>
  15. #include <netinet/in.h>
  16. #include <stdint.h>
  17. #include <sys/socket.h>
  18. #include <unistd.h> // for some IPC/network system calls
  19. #include <boost/bind.hpp>
  20. #include <boost/scoped_ptr.hpp>
  21. #include <boost/date_time/posix_time/posix_time_types.hpp>
  22. #include <asio.hpp>
  23. #include <asio/deadline_timer.hpp>
  24. #include <asiolink/io_address.h>
  25. #include <asiolink/io_asio_socket.h>
  26. #include <asiolink/io_endpoint.h>
  27. #include <asiolink/io_service.h>
  28. #include <asiolink/tcp_endpoint.h>
  29. #include <asiolink/tcp_socket.h>
  30. #include <asiolink/udp_endpoint.h>
  31. #include <asiolink/udp_socket.h>
  32. #include <dns/messagerenderer.h>
  33. #include <dns/opcode.h>
  34. #include <dns/rcode.h>
  35. #include <log/logger.h>
  36. #include <log/macros.h>
  37. #include <asiodns/asiodns_messages.h>
  38. #include <asiodns/io_fetch.h>
  39. #include <util/buffer.h>
  40. #include <util/random/qid_gen.h>
  41. using namespace asio;
  42. using namespace isc::asiolink;
  43. using namespace isc::dns;
  44. using namespace isc::util;
  45. using namespace isc::util::random;
  46. using namespace isc::log;
  47. using namespace std;
  48. namespace isc {
  49. namespace asiodns {
  50. /// Use the ASIO logger
  51. isc::log::Logger logger("asiolink");
  52. // Log debug verbosity
  53. const int DBG_IMPORTANT = DBGLVL_TRACE_BASIC;
  54. const int DBG_COMMON = DBGLVL_TRACE_DETAIL;
  55. const int DBG_ALL = DBGLVL_TRACE_DETAIL + 20;
  56. /// \brief IOFetch Data
  57. ///
  58. /// The data for IOFetch is held in a separate struct pointed to by a shared_ptr
  59. /// object. This is because the IOFetch object will be copied often (it is used
  60. /// as a coroutine and passed as callback to many async_*() functions) and we
  61. /// want keep the same data). Organising the data in this way keeps copying to
  62. /// a minimum.
  63. struct IOFetchData {
  64. // The first two members are shared pointers to a base class because what is
  65. // actually instantiated depends on whether the fetch is over UDP or TCP,
  66. // which is not known until construction of the IOFetch. Use of a shared
  67. // pointer here is merely to ensure deletion when the data object is deleted.
  68. boost::scoped_ptr<IOAsioSocket<IOFetch> > socket;
  69. ///< Socket to use for I/O
  70. boost::scoped_ptr<IOEndpoint> remote_snd;///< Where the fetch is sent
  71. boost::scoped_ptr<IOEndpoint> remote_rcv;///< Where the response came from
  72. OutputBufferPtr msgbuf; ///< Wire buffer for question
  73. OutputBufferPtr received; ///< Received data put here
  74. IOFetch::Callback* callback; ///< Called on I/O Completion
  75. asio::deadline_timer timer; ///< Timer to measure timeouts
  76. IOFetch::Protocol protocol; ///< Protocol being used
  77. size_t cumulative; ///< Cumulative received amount
  78. size_t expected; ///< Expected amount of data
  79. size_t offset; ///< Offset to receive data
  80. bool stopped; ///< Have we stopped running?
  81. int timeout; ///< Timeout in ms
  82. bool packet; ///< true if packet was supplied
  83. // In case we need to log an error, the origin of the last asynchronous
  84. // I/O is recorded. To save time and simplify the code, this is recorded
  85. // as the ID of the error message that would be generated if the I/O failed.
  86. // This means that we must make sure that all possible "origins" take the
  87. // same arguments in their message in the same order.
  88. isc::log::MessageID origin; ///< Origin of last asynchronous I/O
  89. uint8_t staging[IOFetch::STAGING_LENGTH];
  90. ///< Temporary array for received data
  91. isc::dns::qid_t qid; ///< The QID set in the query
  92. /// \brief Constructor
  93. ///
  94. /// Just fills in the data members of the IOFetchData structure
  95. ///
  96. /// \param proto Either IOFetch::TCP or IOFetch::UDP.
  97. /// \param service I/O Service object to handle the asynchronous
  98. /// operations.
  99. /// \param address IP address of upstream server
  100. /// \param port Port to use for the query
  101. /// \param buff Output buffer into which the response (in wire format)
  102. /// is written (if a response is received).
  103. /// \param cb Callback object containing the callback to be called
  104. /// when we terminate. The caller is responsible for managing this
  105. /// object and deleting it if necessary.
  106. /// \param wait Timeout for the fetch (in ms).
  107. ///
  108. /// TODO: May need to alter constructor (see comment 4 in Trac ticket #554)
  109. IOFetchData(IOFetch::Protocol proto, IOService& service,
  110. const IOAddress& address, uint16_t port, OutputBufferPtr& buff,
  111. IOFetch::Callback* cb, int wait)
  112. :
  113. socket((proto == IOFetch::UDP) ?
  114. static_cast<IOAsioSocket<IOFetch>*>(
  115. new UDPSocket<IOFetch>(service)) :
  116. static_cast<IOAsioSocket<IOFetch>*>(
  117. new TCPSocket<IOFetch>(service))
  118. ),
  119. remote_snd((proto == IOFetch::UDP) ?
  120. static_cast<IOEndpoint*>(new UDPEndpoint(address, port)) :
  121. static_cast<IOEndpoint*>(new TCPEndpoint(address, port))
  122. ),
  123. remote_rcv((proto == IOFetch::UDP) ?
  124. static_cast<IOEndpoint*>(new UDPEndpoint(address, port)) :
  125. static_cast<IOEndpoint*>(new TCPEndpoint(address, port))
  126. ),
  127. msgbuf(new OutputBuffer(512)),
  128. received(buff),
  129. callback(cb),
  130. timer(service.get_io_service()),
  131. protocol(proto),
  132. cumulative(0),
  133. expected(0),
  134. offset(0),
  135. stopped(false),
  136. timeout(wait),
  137. packet(false),
  138. origin(ASIODNS_UNKNOWN_ORIGIN),
  139. staging(),
  140. qid(QidGenerator::getInstance().generateQid())
  141. {}
  142. // Checks if the response we received was ok;
  143. // - data contains the buffer we read, as well as the address
  144. // we sent to and the address we received from.
  145. // length is provided by the operator() in IOFetch.
  146. // Addresses must match, number of octets read must be at least
  147. // 2, and the first two octets must match the qid of the message
  148. // we sent.
  149. bool responseOK() {
  150. return (*remote_snd == *remote_rcv && cumulative >= 2 &&
  151. readUint16(received->getData()) == qid);
  152. }
  153. };
  154. /// IOFetch Constructor - just initialize the private data
  155. IOFetch::IOFetch(Protocol protocol, IOService& service,
  156. const isc::dns::Question& question, const IOAddress& address, uint16_t port,
  157. OutputBufferPtr& buff, Callback* cb, int wait)
  158. {
  159. MessagePtr query_msg(new Message(Message::RENDER));
  160. initIOFetch(query_msg, protocol, service, question, address, port, buff,
  161. cb, wait);
  162. }
  163. IOFetch::IOFetch(Protocol protocol, IOService& service,
  164. OutputBufferPtr& outpkt, const IOAddress& address, uint16_t port,
  165. OutputBufferPtr& buff, Callback* cb, int wait)
  166. :
  167. data_(new IOFetchData(protocol, service,
  168. address, port, buff, cb, wait))
  169. {
  170. data_->msgbuf = outpkt;
  171. data_->packet = true;
  172. }
  173. IOFetch::IOFetch(Protocol protocol, IOService& service,
  174. ConstMessagePtr query_message, const IOAddress& address, uint16_t port,
  175. OutputBufferPtr& buff, Callback* cb, int wait)
  176. {
  177. MessagePtr msg(new Message(Message::RENDER));
  178. msg->setHeaderFlag(Message::HEADERFLAG_RD,
  179. query_message->getHeaderFlag(Message::HEADERFLAG_RD));
  180. msg->setHeaderFlag(Message::HEADERFLAG_CD,
  181. query_message->getHeaderFlag(Message::HEADERFLAG_CD));
  182. initIOFetch(msg, protocol, service,
  183. **(query_message->beginQuestion()),
  184. address, port, buff, cb, wait);
  185. }
  186. void
  187. IOFetch::initIOFetch(MessagePtr& query_msg, Protocol protocol, IOService& service,
  188. const isc::dns::Question& question,
  189. const IOAddress& address, uint16_t port,
  190. OutputBufferPtr& buff, Callback* cb, int wait)
  191. {
  192. data_ = boost::shared_ptr<IOFetchData>(new IOFetchData(
  193. protocol, service, address, port, buff, cb, wait));
  194. query_msg->setQid(data_->qid);
  195. query_msg->setOpcode(Opcode::QUERY());
  196. query_msg->setRcode(Rcode::NOERROR());
  197. query_msg->setHeaderFlag(Message::HEADERFLAG_RD);
  198. query_msg->addQuestion(question);
  199. EDNSPtr edns_query(new EDNS());
  200. edns_query->setUDPSize(Message::DEFAULT_MAX_EDNS0_UDPSIZE);
  201. query_msg->setEDNS(edns_query);
  202. MessageRenderer renderer(*data_->msgbuf);
  203. query_msg->toWire(renderer);
  204. }
  205. // Return protocol in use.
  206. IOFetch::Protocol
  207. IOFetch::getProtocol() const {
  208. return (data_->protocol);
  209. }
  210. /// The function operator is implemented with the "stackless coroutine"
  211. /// pattern; see internal/coroutine.h for details.
  212. void
  213. IOFetch::operator()(asio::error_code ec, size_t length) {
  214. if (data_->stopped) {
  215. return;
  216. } else if (ec) {
  217. logIOFailure(ec);
  218. return;
  219. }
  220. CORO_REENTER (this) {
  221. /// Generate the upstream query and render it to wire format
  222. /// This is done in a different scope to allow inline variable
  223. /// declarations.
  224. {
  225. if (data_->packet) {
  226. // A packet was given, overwrite the QID (which is in the
  227. // first two bytes of the packet).
  228. data_->msgbuf->writeUint16At(data_->qid, 0);
  229. }
  230. }
  231. // If we timeout, we stop, which will can cancel outstanding I/Os and
  232. // shutdown everything.
  233. if (data_->timeout != -1) {
  234. data_->timer.expires_from_now(boost::posix_time::milliseconds(
  235. data_->timeout));
  236. data_->timer.async_wait(boost::bind(&IOFetch::stop, *this,
  237. TIME_OUT));
  238. }
  239. // Open a connection to the target system. For speed, if the operation
  240. // is synchronous (i.e. UDP operation) we bypass the yield.
  241. data_->origin = ASIODNS_OPEN_SOCKET;
  242. if (data_->socket->isOpenSynchronous()) {
  243. data_->socket->open(data_->remote_snd.get(), *this);
  244. } else {
  245. CORO_YIELD data_->socket->open(data_->remote_snd.get(), *this);
  246. }
  247. do {
  248. // Begin an asynchronous send, and then yield. When the send completes,
  249. // we will resume immediately after this point.
  250. data_->origin = ASIODNS_SEND_DATA;
  251. CORO_YIELD data_->socket->asyncSend(data_->msgbuf->getData(),
  252. data_->msgbuf->getLength(), data_->remote_snd.get(), *this);
  253. // Now receive the response. Since TCP may not receive the entire
  254. // message in one operation, we need to loop until we have received
  255. // it. (This can't be done within the asyncReceive() method because
  256. // each I/O operation will be done asynchronously and between each one
  257. // we need to yield ... and we *really* don't want to set up another
  258. // coroutine within that method.) So after each receive (and yield),
  259. // we check if the operation is complete and if not, loop to read again.
  260. //
  261. // Another concession to TCP is that the amount of is contained in the
  262. // first two bytes. This leads to two problems:
  263. //
  264. // a) We don't want those bytes in the return buffer.
  265. // b) They may not both arrive in the first I/O.
  266. //
  267. // So... we need to loop until we have at least two bytes, then store
  268. // the expected amount of data. Then we need to loop until we have
  269. // received all the data before copying it back to the user's buffer.
  270. // And we want to minimise the amount of copying...
  271. data_->origin = ASIODNS_READ_DATA;
  272. data_->cumulative = 0; // No data yet received
  273. data_->offset = 0; // First data into start of buffer
  274. data_->received->clear(); // Clear the receive buffer
  275. do {
  276. CORO_YIELD data_->socket->asyncReceive(data_->staging,
  277. static_cast<size_t>(STAGING_LENGTH),
  278. data_->offset,
  279. data_->remote_rcv.get(), *this);
  280. } while (!data_->socket->processReceivedData(data_->staging, length,
  281. data_->cumulative, data_->offset,
  282. data_->expected, data_->received));
  283. } while (!data_->responseOK());
  284. // Finished with this socket, so close it. This will not generate an
  285. // I/O error, but reset the origin to unknown in case we change this.
  286. data_->origin = ASIODNS_UNKNOWN_ORIGIN;
  287. data_->socket->close();
  288. /// We are done
  289. stop(SUCCESS);
  290. }
  291. }
  292. // Function that stops the coroutine sequence. It is called either when the
  293. // query finishes or when the timer times out. Either way, it sets the
  294. // "stopped_" flag and cancels anything that is in progress.
  295. //
  296. // As the function may be entered multiple times as things wind down, it checks
  297. // if the stopped_ flag is already set. If it is, the call is a no-op.
  298. void
  299. IOFetch::stop(Result result) {
  300. if (!data_->stopped) {
  301. // Mark the fetch as stopped to prevent other completion callbacks
  302. // (invoked because of the calls to cancel()) from executing the
  303. // cancel calls again.
  304. //
  305. // In a single threaded environment, the callbacks won't be invoked
  306. // until this one completes. In a multi-threaded environment, they may
  307. // well be, in which case the testing (and setting) of the stopped_
  308. // variable should be done inside a mutex (and the stopped_ variable
  309. // declared as "volatile").
  310. //
  311. // TODO: Update testing of stopped_ if threads are used.
  312. data_->stopped = true;
  313. switch (result) {
  314. case TIME_OUT:
  315. LOG_DEBUG(logger, DBG_COMMON, ASIODNS_READ_TIMEOUT).
  316. arg(data_->remote_snd->getAddress().toText()).
  317. arg(data_->remote_snd->getPort());
  318. break;
  319. case SUCCESS:
  320. LOG_DEBUG(logger, DBG_ALL, ASIODNS_FETCH_COMPLETED).
  321. arg(data_->remote_rcv->getAddress().toText()).
  322. arg(data_->remote_rcv->getPort());
  323. break;
  324. case STOPPED:
  325. // Fetch has been stopped for some other reason. This is
  326. // allowed but as it is unusual it is logged, but with a lower
  327. // debug level than a timeout (which is totally normal).
  328. LOG_DEBUG(logger, DBG_IMPORTANT, ASIODNS_FETCH_STOPPED).
  329. arg(data_->remote_snd->getAddress().toText()).
  330. arg(data_->remote_snd->getPort());
  331. break;
  332. default:
  333. LOG_ERROR(logger, ASIODNS_UNKNOWN_RESULT).
  334. arg(data_->remote_snd->getAddress().toText()).
  335. arg(data_->remote_snd->getPort());
  336. }
  337. // Stop requested, cancel and I/O's on the socket and shut it down,
  338. // and cancel the timer.
  339. data_->socket->cancel();
  340. data_->socket->close();
  341. data_->timer.cancel();
  342. // Execute the I/O completion callback (if present).
  343. if (data_->callback) {
  344. (*(data_->callback))(result);
  345. }
  346. }
  347. }
  348. // Log an error - called on I/O failure
  349. void IOFetch::logIOFailure(asio::error_code ec) {
  350. // Should only get here with a known error code.
  351. assert((data_->origin == ASIODNS_OPEN_SOCKET) ||
  352. (data_->origin == ASIODNS_SEND_DATA) ||
  353. (data_->origin == ASIODNS_READ_DATA) ||
  354. (data_->origin == ASIODNS_UNKNOWN_ORIGIN));
  355. static const char* PROTOCOL[2] = {"TCP", "UDP"};
  356. LOG_ERROR(logger, data_->origin).arg(ec.value()).
  357. arg((data_->remote_snd->getProtocol() == IPPROTO_TCP) ?
  358. PROTOCOL[0] : PROTOCOL[1]).
  359. arg(data_->remote_snd->getAddress().toText()).
  360. arg(data_->remote_snd->getPort());
  361. }
  362. } // namespace asiodns
  363. } // namespace isc {