session.cc 12 KB

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