session.cc 12 KB

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