session.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. // Copyright (C) 2009 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. // $Id$
  15. #include <config.h>
  16. #include <cc/session_config.h>
  17. #include <stdint.h>
  18. // XXX: there seems to be a strange dependency between ASIO and std library
  19. // definitions. On some platforms if we include std headers before ASIO
  20. // headers unexpected behaviors will happen.
  21. // A middle term solution is to generalize our local wrapper interface
  22. // (currently only available for the auth server), where all such portability
  23. // issues are hidden, and to have other modules use the wrapper.
  24. #include <unistd.h> // for some IPC/network system calls
  25. #include <asio.hpp>
  26. #include <asio/error_code.hpp>
  27. #include <asio/deadline_timer.hpp>
  28. #include <asio/system_error.hpp>
  29. #include <cstdio>
  30. #include <vector>
  31. #include <iostream>
  32. #include <sstream>
  33. #include <sys/un.h>
  34. #include <boost/bind.hpp>
  35. #include <boost/optional.hpp>
  36. #include <boost/function.hpp>
  37. #include <boost/date_time/posix_time/posix_time_types.hpp>
  38. #include <exceptions/exceptions.h>
  39. #include <cc/data.h>
  40. #include <cc/session.h>
  41. using namespace std;
  42. using namespace isc::cc;
  43. using namespace isc::data;
  44. // some of the asio names conflict with socket API system calls
  45. // (e.g. write(2)) so we don't import the entire asio namespace.
  46. using asio::io_service;
  47. namespace isc {
  48. namespace cc {
  49. class SessionImpl {
  50. public:
  51. SessionImpl(io_service& io_service) :
  52. sequence_(-1), queue_(Element::createList()),
  53. io_service_(io_service), socket_(io_service_), data_length_(0),
  54. timeout_(4000)
  55. {}
  56. void establish(const char& socket_file);
  57. void disconnect();
  58. void writeData(const void* data, size_t datalen);
  59. size_t readDataLength();
  60. // Blocking read. Will throw a SessionTimeout if the timeout value
  61. // (in seconds) is thrown. If timeout is 0 it will block forever
  62. void readData(void* data, size_t datalen);
  63. void startRead(boost::function<void()> user_handler);
  64. virtual void setTimeout(size_t seconds) { timeout_ = seconds; };
  65. virtual size_t getTimeout() { return timeout_; };
  66. long int sequence_; // the next sequence number to use
  67. std::string lname_;
  68. ElementPtr queue_;
  69. private:
  70. void internalRead(const asio::error_code& error,
  71. size_t bytes_transferred);
  72. // Sets the boolean pointed to by result to true, unless
  73. // the given error code is operation_aborted
  74. // Used as a callback for emulating sync reads with async calls
  75. void setResult(bool* result, asio::error_code* result_code, const asio::error_code& b);
  76. private:
  77. io_service& io_service_;
  78. asio::local::stream_protocol::socket socket_;
  79. uint32_t data_length_;
  80. boost::function<void()> user_handler_;
  81. asio::error_code error_;
  82. // timeout for blocking reads (in seconds, defaults to 4)
  83. size_t timeout_;
  84. };
  85. void
  86. SessionImpl::establish(const char& socket_file) {
  87. try {
  88. socket_.connect(asio::local::stream_protocol::endpoint(&socket_file),
  89. error_);
  90. } catch(const asio::system_error& se) {
  91. isc_throw(SessionError, se.what());
  92. }
  93. if (error_) {
  94. isc_throw(SessionError, "Unable to connect to message queue: " <<
  95. error_.message());
  96. }
  97. }
  98. void
  99. SessionImpl::disconnect() {
  100. socket_.close();
  101. data_length_ = 0;
  102. }
  103. void
  104. SessionImpl::writeData(const void* data, size_t datalen) {
  105. try {
  106. asio::write(socket_, asio::buffer(data, datalen));
  107. } catch (const asio::system_error& asio_ex) {
  108. isc_throw(SessionError, "ASIO write failed: " << asio_ex.what());
  109. }
  110. }
  111. size_t
  112. SessionImpl::readDataLength() {
  113. size_t ret_len = data_length_;
  114. if (ret_len == 0) {
  115. readData(&data_length_, sizeof(data_length_));
  116. if (data_length_ == 0) {
  117. isc_throw(SessionError, "ASIO read: data length is not ready");
  118. }
  119. ret_len = ntohl(data_length_);
  120. }
  121. data_length_ = 0;
  122. return (ret_len);
  123. }
  124. void
  125. SessionImpl::setResult(bool* result, asio::error_code* result_code, const asio::error_code& b) {
  126. // if the 'error' is operation_aborted (i.e. a call to cancel()),
  127. // we do not consider the read or the wait 'done'.
  128. if (b != asio::error::operation_aborted) {
  129. *result_code = b;
  130. *result = true;
  131. }
  132. }
  133. void
  134. SessionImpl::readData(void* data, size_t datalen) {
  135. bool timer_result = false;
  136. bool read_result = false;
  137. asio::error_code read_result_code;
  138. asio::error_code timer_result_code;
  139. try {
  140. asio::async_read(socket_, asio::buffer(data, datalen),
  141. boost::bind(&SessionImpl::setResult, this,
  142. &read_result, &read_result_code, _1));
  143. asio::deadline_timer timer(socket_.io_service());
  144. if (getTimeout() != 0) {
  145. timer.expires_from_now(boost::posix_time::milliseconds(getTimeout()));
  146. timer.async_wait(boost::bind(&SessionImpl::setResult,
  147. this, &timer_result,
  148. &timer_result_code, _1));
  149. }
  150. // wait until either we have read the data we want, or the
  151. // timer expires
  152. while (!read_result && !timer_result) {
  153. socket_.io_service().run_one();
  154. if (read_result) {
  155. timer.cancel();
  156. } else if (timer_result) {
  157. socket_.cancel();
  158. }
  159. }
  160. if (read_result_code) {
  161. isc_throw(SessionError,
  162. "Error while reading data from cc session: " <<
  163. read_result_code.message());
  164. }
  165. if (!read_result) {
  166. isc_throw(SessionTimeout,
  167. "Timeout or error while reading data from cc session");
  168. }
  169. } catch (const asio::system_error& asio_ex) {
  170. // to hide boost specific exceptions, we catch them explicitly
  171. // and convert it to SessionError.
  172. isc_throw(SessionError, "ASIO read failed: " << asio_ex.what());
  173. }
  174. }
  175. void
  176. SessionImpl::startRead(boost::function<void()> user_handler) {
  177. data_length_ = 0;
  178. user_handler_ = user_handler;
  179. asio::async_read(socket_, asio::buffer(&data_length_,
  180. sizeof(data_length_)),
  181. boost::bind(&SessionImpl::internalRead, this,
  182. asio::placeholders::error,
  183. asio::placeholders::bytes_transferred));
  184. }
  185. void
  186. SessionImpl::internalRead(const asio::error_code& error,
  187. size_t bytes_transferred)
  188. {
  189. if (!error) {
  190. assert(bytes_transferred == sizeof(data_length_));
  191. data_length_ = ntohl(data_length_);
  192. if (data_length_ == 0) {
  193. isc_throw(SessionError, "Invalid message length (0)");
  194. }
  195. user_handler_();
  196. } else {
  197. isc_throw(SessionError, "asynchronous read failed");
  198. }
  199. }
  200. Session::Session(io_service& io_service) : impl_(new SessionImpl(io_service))
  201. {}
  202. Session::~Session() {
  203. delete impl_;
  204. }
  205. void
  206. Session::disconnect() {
  207. impl_->disconnect();
  208. }
  209. void
  210. Session::startRead(boost::function<void()> read_callback) {
  211. impl_->startRead(read_callback);
  212. }
  213. namespace { // maybe unnecessary.
  214. // This is a helper class to make the establish() method (below) exception-safe
  215. // with the RAII approach.
  216. class SessionHolder {
  217. public:
  218. SessionHolder(SessionImpl* obj) : impl_obj_(obj) {}
  219. ~SessionHolder()
  220. {
  221. if (impl_obj_ != NULL) {
  222. impl_obj_->disconnect();
  223. }
  224. }
  225. void clear() { impl_obj_ = NULL; }
  226. SessionImpl* impl_obj_;
  227. };
  228. }
  229. void
  230. Session::establish(const char* socket_file) {
  231. if (socket_file == NULL) {
  232. socket_file = getenv("BIND10_MSGQ_SOCKET_FILE");
  233. }
  234. if (socket_file == NULL) {
  235. socket_file = BIND10_MSGQ_SOCKET_FILE;
  236. }
  237. impl_->establish(*socket_file);
  238. // once established, encapsulate the implementation object so that we
  239. // can safely release the internal resource when exception happens
  240. // below.
  241. SessionHolder session_holder(impl_);
  242. //
  243. // send a request for our local name, and wait for a response
  244. //
  245. ElementPtr get_lname_msg =
  246. Element::fromJSON("{ \"type\": \"getlname\" }");
  247. sendmsg(get_lname_msg);
  248. ElementPtr routing, msg;
  249. recvmsg(routing, msg, false);
  250. impl_->lname_ = msg->get("lname")->stringValue();
  251. // At this point there's no risk of resource leak.
  252. session_holder.clear();
  253. }
  254. //
  255. // Convert to wire format and send this via the stream socket with its length
  256. // prefix.
  257. //
  258. void
  259. Session::sendmsg(ElementPtr& msg) {
  260. std::string header_wire = msg->toWire();
  261. unsigned int length = 2 + header_wire.length();
  262. unsigned int length_net = htonl(length);
  263. unsigned short header_length = header_wire.length();
  264. unsigned short header_length_net = htons(header_length);
  265. impl_->writeData(&length_net, sizeof(length_net));
  266. impl_->writeData(&header_length_net, sizeof(header_length_net));
  267. impl_->writeData(header_wire.data(), header_length);
  268. }
  269. void
  270. Session::sendmsg(ElementPtr& env, ElementPtr& msg) {
  271. std::string header_wire = env->toWire();
  272. std::string body_wire = msg->toWire();
  273. unsigned int length = 2 + header_wire.length() + body_wire.length();
  274. unsigned int length_net = htonl(length);
  275. unsigned short header_length = header_wire.length();
  276. unsigned short header_length_net = htons(header_length);
  277. impl_->writeData(&length_net, sizeof(length_net));
  278. impl_->writeData(&header_length_net, sizeof(header_length_net));
  279. impl_->writeData(header_wire.data(), header_length);
  280. impl_->writeData(body_wire.data(), body_wire.length());
  281. }
  282. bool
  283. Session::recvmsg(ElementPtr& msg, bool nonblock, int seq) {
  284. ElementPtr l_env;
  285. return recvmsg(l_env, msg, nonblock, seq);
  286. }
  287. bool
  288. Session::recvmsg(ElementPtr& env, ElementPtr& msg,
  289. bool nonblock, int seq) {
  290. size_t length = impl_->readDataLength();
  291. ElementPtr l_env, l_msg;
  292. if (hasQueuedMsgs()) {
  293. ElementPtr q_el;
  294. for (int i = 0; i < impl_->queue_->size(); i++) {
  295. q_el = impl_->queue_->get(i);
  296. if (( seq == -1 &&
  297. !q_el->get(0)->contains("reply")
  298. ) || (
  299. q_el->get(0)->contains("reply") &&
  300. q_el->get(0)->get("reply")->intValue() == seq
  301. )
  302. ) {
  303. env = q_el->get(0);
  304. msg = q_el->get(1);
  305. impl_->queue_->remove(i);
  306. return true;
  307. }
  308. }
  309. }
  310. unsigned short header_length_net;
  311. impl_->readData(&header_length_net, sizeof(header_length_net));
  312. unsigned short header_length = ntohs(header_length_net);
  313. if (header_length > length || length < 2) {
  314. isc_throw(SessionError, "Length parameters invalid: total=" << length
  315. << ", header=" << header_length);
  316. }
  317. // remove the header-length bytes from the total length
  318. length -= 2;
  319. std::vector<char> buffer(length);
  320. impl_->readData(&buffer[0], length);
  321. std::string header_wire = std::string(&buffer[0], header_length);
  322. std::string body_wire = std::string(&buffer[0] + header_length,
  323. length - header_length);
  324. std::stringstream header_wire_stream;
  325. header_wire_stream << header_wire;
  326. l_env = Element::fromWire(header_wire_stream, header_length);
  327. std::stringstream body_wire_stream;
  328. body_wire_stream << body_wire;
  329. l_msg = Element::fromWire(body_wire_stream, length - header_length);
  330. if ((seq == -1 &&
  331. !l_env->contains("reply")
  332. ) || (
  333. l_env->contains("reply") &&
  334. l_env->get("reply")->intValue() == seq
  335. )
  336. ) {
  337. env = l_env;
  338. msg = l_msg;
  339. return true;
  340. } else {
  341. ElementPtr q_el = Element::createList();
  342. q_el->add(l_env);
  343. q_el->add(l_msg);
  344. impl_->queue_->add(q_el);
  345. return recvmsg(env, msg, nonblock, seq);
  346. }
  347. // XXXMLG handle non-block here, and return false for short reads
  348. }
  349. void
  350. Session::subscribe(std::string group, std::string instance) {
  351. ElementPtr env = Element::createMap();
  352. env->set("type", Element::create("subscribe"));
  353. env->set("group", Element::create(group));
  354. env->set("instance", Element::create(instance));
  355. sendmsg(env);
  356. }
  357. void
  358. Session::unsubscribe(std::string group, std::string instance) {
  359. ElementPtr env = Element::createMap();
  360. env->set("type", Element::create("unsubscribe"));
  361. env->set("group", Element::create(group));
  362. env->set("instance", Element::create(instance));
  363. sendmsg(env);
  364. }
  365. int
  366. Session::group_sendmsg(ElementPtr msg, std::string group,
  367. std::string instance, std::string to)
  368. {
  369. ElementPtr env = Element::createMap();
  370. long int nseq = ++impl_->sequence_;
  371. env->set("type", Element::create("send"));
  372. env->set("from", Element::create(impl_->lname_));
  373. env->set("to", Element::create(to));
  374. env->set("group", Element::create(group));
  375. env->set("instance", Element::create(instance));
  376. env->set("seq", Element::create(nseq));
  377. //env->set("msg", Element::create(msg->toWire()));
  378. sendmsg(env, msg);
  379. return nseq;
  380. }
  381. bool
  382. Session::group_recvmsg(ElementPtr& envelope, ElementPtr& msg,
  383. bool nonblock, int seq)
  384. {
  385. return (recvmsg(envelope, msg, nonblock, seq));
  386. }
  387. int
  388. Session::reply(ElementPtr& envelope, ElementPtr& newmsg) {
  389. ElementPtr env = Element::createMap();
  390. long int nseq = ++impl_->sequence_;
  391. env->set("type", Element::create("send"));
  392. env->set("from", Element::create(impl_->lname_));
  393. env->set("to", Element::create(envelope->get("from")->stringValue()));
  394. env->set("group", Element::create(envelope->get("group")->stringValue()));
  395. env->set("instance", Element::create(envelope->get("instance")->stringValue()));
  396. env->set("seq", Element::create(nseq));
  397. env->set("reply", Element::create(envelope->get("seq")->intValue()));
  398. sendmsg(env, newmsg);
  399. return nseq;
  400. }
  401. bool
  402. Session::hasQueuedMsgs() {
  403. return (impl_->queue_->size() > 0);
  404. }
  405. void
  406. Session::setTimeout(size_t milliseconds) {
  407. impl_->setTimeout(milliseconds);
  408. }
  409. size_t
  410. Session::getTimeout() {
  411. return (impl_->getTimeout());
  412. }
  413. }
  414. }