io_fetch.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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 <unistd.h> // for some IPC/network system calls
  16. #include <netinet/in.h>
  17. #include <stdint.h>
  18. #include <sys/socket.h>
  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;
  202. renderer.setBuffer(data_->msgbuf.get());
  203. query_msg->toWire(renderer);
  204. renderer.setBuffer(NULL);
  205. }
  206. // Return protocol in use.
  207. IOFetch::Protocol
  208. IOFetch::getProtocol() const {
  209. return (data_->protocol);
  210. }
  211. /// The function operator is implemented with the "stackless coroutine"
  212. /// pattern; see internal/coroutine.h for details.
  213. void
  214. IOFetch::operator()(asio::error_code ec, size_t length) {
  215. if (data_->stopped) {
  216. return;
  217. } else if (ec) {
  218. logIOFailure(ec);
  219. return;
  220. }
  221. CORO_REENTER (this) {
  222. /// Generate the upstream query and render it to wire format
  223. /// This is done in a different scope to allow inline variable
  224. /// declarations.
  225. {
  226. if (data_->packet) {
  227. // A packet was given, overwrite the QID (which is in the
  228. // first two bytes of the packet).
  229. data_->msgbuf->writeUint16At(data_->qid, 0);
  230. }
  231. }
  232. // If we timeout, we stop, which will can cancel outstanding I/Os and
  233. // shutdown everything.
  234. if (data_->timeout != -1) {
  235. data_->timer.expires_from_now(boost::posix_time::milliseconds(
  236. data_->timeout));
  237. data_->timer.async_wait(boost::bind(&IOFetch::stop, *this,
  238. TIME_OUT));
  239. }
  240. // Open a connection to the target system. For speed, if the operation
  241. // is synchronous (i.e. UDP operation) we bypass the yield.
  242. data_->origin = ASIODNS_OPEN_SOCKET;
  243. if (data_->socket->isOpenSynchronous()) {
  244. data_->socket->open(data_->remote_snd.get(), *this);
  245. } else {
  246. CORO_YIELD data_->socket->open(data_->remote_snd.get(), *this);
  247. }
  248. do {
  249. // Begin an asynchronous send, and then yield. When the send completes,
  250. // we will resume immediately after this point.
  251. data_->origin = ASIODNS_SEND_DATA;
  252. CORO_YIELD data_->socket->asyncSend(data_->msgbuf->getData(),
  253. data_->msgbuf->getLength(), data_->remote_snd.get(), *this);
  254. // Now receive the response. Since TCP may not receive the entire
  255. // message in one operation, we need to loop until we have received
  256. // it. (This can't be done within the asyncReceive() method because
  257. // each I/O operation will be done asynchronously and between each one
  258. // we need to yield ... and we *really* don't want to set up another
  259. // coroutine within that method.) So after each receive (and yield),
  260. // we check if the operation is complete and if not, loop to read again.
  261. //
  262. // Another concession to TCP is that the amount of is contained in the
  263. // first two bytes. This leads to two problems:
  264. //
  265. // a) We don't want those bytes in the return buffer.
  266. // b) They may not both arrive in the first I/O.
  267. //
  268. // So... we need to loop until we have at least two bytes, then store
  269. // the expected amount of data. Then we need to loop until we have
  270. // received all the data before copying it back to the user's buffer.
  271. // And we want to minimise the amount of copying...
  272. data_->origin = ASIODNS_READ_DATA;
  273. data_->cumulative = 0; // No data yet received
  274. data_->offset = 0; // First data into start of buffer
  275. data_->received->clear(); // Clear the receive buffer
  276. do {
  277. CORO_YIELD data_->socket->asyncReceive(data_->staging,
  278. static_cast<size_t>(STAGING_LENGTH),
  279. data_->offset,
  280. data_->remote_rcv.get(), *this);
  281. } while (!data_->socket->processReceivedData(data_->staging, length,
  282. data_->cumulative, data_->offset,
  283. data_->expected, data_->received));
  284. } while (!data_->responseOK());
  285. // Finished with this socket, so close it. This will not generate an
  286. // I/O error, but reset the origin to unknown in case we change this.
  287. data_->origin = ASIODNS_UNKNOWN_ORIGIN;
  288. data_->socket->close();
  289. /// We are done
  290. stop(SUCCESS);
  291. }
  292. }
  293. // Function that stops the coroutine sequence. It is called either when the
  294. // query finishes or when the timer times out. Either way, it sets the
  295. // "stopped_" flag and cancels anything that is in progress.
  296. //
  297. // As the function may be entered multiple times as things wind down, it checks
  298. // if the stopped_ flag is already set. If it is, the call is a no-op.
  299. void
  300. IOFetch::stop(Result result) {
  301. if (!data_->stopped) {
  302. // Mark the fetch as stopped to prevent other completion callbacks
  303. // (invoked because of the calls to cancel()) from executing the
  304. // cancel calls again.
  305. //
  306. // In a single threaded environment, the callbacks won't be invoked
  307. // until this one completes. In a multi-threaded environment, they may
  308. // well be, in which case the testing (and setting) of the stopped_
  309. // variable should be done inside a mutex (and the stopped_ variable
  310. // declared as "volatile").
  311. //
  312. // TODO: Update testing of stopped_ if threads are used.
  313. data_->stopped = true;
  314. switch (result) {
  315. case TIME_OUT:
  316. LOG_DEBUG(logger, DBG_COMMON, ASIODNS_READ_TIMEOUT).
  317. arg(data_->remote_snd->getAddress().toText()).
  318. arg(data_->remote_snd->getPort());
  319. break;
  320. case SUCCESS:
  321. LOG_DEBUG(logger, DBG_ALL, ASIODNS_FETCH_COMPLETED).
  322. arg(data_->remote_rcv->getAddress().toText()).
  323. arg(data_->remote_rcv->getPort());
  324. break;
  325. case STOPPED:
  326. // Fetch has been stopped for some other reason. This is
  327. // allowed but as it is unusual it is logged, but with a lower
  328. // debug level than a timeout (which is totally normal).
  329. LOG_DEBUG(logger, DBG_IMPORTANT, ASIODNS_FETCH_STOPPED).
  330. arg(data_->remote_snd->getAddress().toText()).
  331. arg(data_->remote_snd->getPort());
  332. break;
  333. default:
  334. LOG_ERROR(logger, ASIODNS_UNKNOWN_RESULT).
  335. arg(data_->remote_snd->getAddress().toText()).
  336. arg(data_->remote_snd->getPort());
  337. }
  338. // Stop requested, cancel and I/O's on the socket and shut it down,
  339. // and cancel the timer.
  340. data_->socket->cancel();
  341. data_->socket->close();
  342. data_->timer.cancel();
  343. // Execute the I/O completion callback (if present).
  344. if (data_->callback) {
  345. (*(data_->callback))(result);
  346. }
  347. }
  348. }
  349. // Log an error - called on I/O failure
  350. void IOFetch::logIOFailure(asio::error_code ec) {
  351. // Should only get here with a known error code.
  352. assert((data_->origin == ASIODNS_OPEN_SOCKET) ||
  353. (data_->origin == ASIODNS_SEND_DATA) ||
  354. (data_->origin == ASIODNS_READ_DATA) ||
  355. (data_->origin == ASIODNS_UNKNOWN_ORIGIN));
  356. static const char* PROTOCOL[2] = {"TCP", "UDP"};
  357. LOG_ERROR(logger, data_->origin).arg(ec.value()).
  358. arg((data_->remote_snd->getProtocol() == IPPROTO_TCP) ?
  359. PROTOCOL[0] : PROTOCOL[1]).
  360. arg(data_->remote_snd->getAddress().toText()).
  361. arg(data_->remote_snd->getPort());
  362. }
  363. } // namespace asiodns
  364. } // namespace isc {