session.cc 14 KB

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