io_fetch.cc 17 KB

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