session.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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 "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 "data.h"
  36. #include "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. using asio::ip::tcp;
  44. #include <sys/types.h>
  45. #include <sys/socket.h>
  46. #include <netinet/in.h>
  47. namespace isc {
  48. namespace cc {
  49. class SessionImpl {
  50. public:
  51. SessionImpl() : sequence_(-1) { queue_ = Element::createFromString("[]"); }
  52. virtual ~SessionImpl() {}
  53. virtual void establish(const char& socket_file) = 0;
  54. virtual int getSocket() = 0;
  55. virtual void disconnect() = 0;
  56. virtual void writeData(const void* data, size_t datalen) = 0;
  57. virtual size_t readDataLength() = 0;
  58. virtual void readData(void* data, size_t datalen) = 0;
  59. virtual void startRead(boost::function<void()> user_handler) = 0;
  60. int sequence_; // the next sequence number to use
  61. std::string lname_;
  62. ElementPtr queue_;
  63. };
  64. class ASIOSession : public SessionImpl {
  65. public:
  66. ASIOSession(io_service& io_service) :
  67. io_service_(io_service), socket_(io_service_), data_length_(0)
  68. {}
  69. virtual void establish(const char& socket_file);
  70. virtual void disconnect();
  71. virtual int getSocket() { return (socket_.native()); }
  72. virtual void writeData(const void* data, size_t datalen);
  73. virtual size_t readDataLength();
  74. virtual void readData(void* data, size_t datalen);
  75. virtual void startRead(boost::function<void()> user_handler);
  76. private:
  77. void internalRead(const asio::error_code& error,
  78. size_t bytes_transferred);
  79. private:
  80. io_service& io_service_;
  81. asio::local::stream_protocol::socket socket_;
  82. uint32_t data_length_;
  83. boost::function<void()> user_handler_;
  84. asio::error_code error_;
  85. };
  86. void
  87. ASIOSession::establish(const char& socket_file) {
  88. try {
  89. socket_.connect(asio::local::stream_protocol::endpoint(&socket_file), error_);
  90. } catch (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. }
  96. }
  97. void
  98. ASIOSession::disconnect() {
  99. socket_.close();
  100. data_length_ = 0;
  101. }
  102. void
  103. ASIOSession::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. ASIOSession::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. ASIOSession::readData(void* data, size_t datalen) {
  125. try {
  126. asio::read(socket_, asio::buffer(data, datalen));
  127. } catch (const asio::system_error& asio_ex) {
  128. // to hide boost specific exceptions, we catch them explicitly
  129. // and convert it to SessionError.
  130. isc_throw(SessionError, "ASIO read failed: " << asio_ex.what());
  131. }
  132. }
  133. void
  134. ASIOSession::startRead(boost::function<void()> user_handler) {
  135. data_length_ = 0;
  136. user_handler_ = user_handler;
  137. async_read(socket_, asio::buffer(&data_length_,
  138. sizeof(data_length_)),
  139. boost::bind(&ASIOSession::internalRead, this,
  140. asio::placeholders::error,
  141. asio::placeholders::bytes_transferred));
  142. }
  143. void
  144. ASIOSession::internalRead(const asio::error_code& error,
  145. size_t bytes_transferred)
  146. {
  147. if (!error) {
  148. assert(bytes_transferred == sizeof(data_length_));
  149. data_length_ = ntohl(data_length_);
  150. if (data_length_ == 0) {
  151. isc_throw(SessionError, "Invalid message length (0)");
  152. }
  153. user_handler_();
  154. } else {
  155. isc_throw(SessionError, "asynchronous read failed");
  156. }
  157. }
  158. class SocketSession : public SessionImpl {
  159. public:
  160. SocketSession() : sock_(-1) {}
  161. virtual ~SocketSession() { disconnect(); }
  162. virtual int getSocket() { return (sock_); }
  163. void establish(const char& socket_file);
  164. virtual void disconnect()
  165. {
  166. if (sock_ >= 0) {
  167. close(sock_);
  168. }
  169. sock_ = -1;
  170. }
  171. virtual void writeData(const void* data, size_t datalen);
  172. virtual void readData(void* data, size_t datalen);
  173. virtual size_t readDataLength();
  174. virtual void startRead(boost::function<void()> user_handler UNUSED_PARAM)
  175. {} // nothing to do for this class
  176. private:
  177. int sock_;
  178. };
  179. namespace { // maybe unnecessary.
  180. // This is a helper class to make the establish() method (below) exception-safe
  181. // with the RAII approach.
  182. class SessionHolder {
  183. public:
  184. SessionHolder(SessionImpl* obj) : impl_obj_(obj) {}
  185. ~SessionHolder()
  186. {
  187. if (impl_obj_ != NULL) {
  188. impl_obj_->disconnect();
  189. }
  190. }
  191. void clear() { impl_obj_ = NULL; }
  192. SessionImpl* impl_obj_;
  193. };
  194. }
  195. void
  196. SocketSession::establish(const char& socket_file) {
  197. struct sockaddr_un s_un;
  198. #ifdef HAVE_SA_LEN
  199. s_un.sun_len = sizeof(struct sockaddr_un);
  200. #endif
  201. if (strlen(&socket_file) >= sizeof(s_un.sun_path)) {
  202. isc_throw(SessionError, "Unable to connect to message queue; "
  203. "socket file path too long: " << socket_file);
  204. }
  205. s_un.sun_family = AF_UNIX;
  206. strncpy(s_un.sun_path, &socket_file, sizeof(s_un.sun_path) - 1);
  207. int s = socket(AF_UNIX, SOCK_STREAM, 0);
  208. if (s < 0) {
  209. isc_throw(SessionError, "socket() failed");
  210. }
  211. if (connect(s, (struct sockaddr *)&s_un, sizeof(s_un)) < 0) {
  212. close(s);
  213. isc_throw(SessionError, "Unable to connect to message queue");
  214. }
  215. sock_ = s;
  216. }
  217. void
  218. SocketSession::writeData(const void* data, const size_t datalen) {
  219. int cc = write(sock_, data, datalen);
  220. if (cc != datalen) {
  221. isc_throw(SessionError, "Write failed: expect " << datalen <<
  222. ", actual " << cc);
  223. }
  224. }
  225. size_t
  226. SocketSession::readDataLength() {
  227. uint32_t length;
  228. readData(&length, sizeof(length));
  229. return (ntohl(length));
  230. }
  231. void
  232. SocketSession::readData(void* data, const size_t datalen) {
  233. int cc = read(sock_, data, datalen);
  234. if (cc != datalen) {
  235. isc_throw(SessionError, "Read failed: expect " << datalen <<
  236. ", actual " << cc);
  237. }
  238. }
  239. Session::Session() : impl_(new SocketSession)
  240. {}
  241. Session::Session(io_service& io_service) : impl_(new ASIOSession(io_service))
  242. {}
  243. Session::~Session() {
  244. delete impl_;
  245. }
  246. void
  247. Session::disconnect() {
  248. impl_->disconnect();
  249. }
  250. int
  251. Session::getSocket() const {
  252. return (impl_->getSocket());
  253. }
  254. void
  255. Session::startRead(boost::function<void()> read_callback) {
  256. impl_->startRead(read_callback);
  257. }
  258. void
  259. Session::establish(const char* socket_file) {
  260. if (socket_file == NULL) {
  261. socket_file = getenv("BIND10_MSGQ_SOCKET_FILE");
  262. }
  263. if (socket_file == NULL) {
  264. socket_file = BIND10_MSGQ_SOCKET_FILE;
  265. }
  266. impl_->establish(*socket_file);
  267. // once established, encapsulate the implementation object so that we
  268. // can safely release the internal resource when exception happens
  269. // below.
  270. SessionHolder session_holder(impl_);
  271. //
  272. // send a request for our local name, and wait for a response
  273. //
  274. ElementPtr get_lname_msg =
  275. Element::createFromString("{ \"type\": \"getlname\" }");
  276. sendmsg(get_lname_msg);
  277. ElementPtr routing, msg;
  278. recvmsg(routing, msg, false);
  279. impl_->lname_ = msg->get("lname")->stringValue();
  280. // At this point there's no risk of resource leak.
  281. session_holder.clear();
  282. }
  283. //
  284. // Convert to wire format and send this on the TCP stream with its length prefix
  285. //
  286. void
  287. Session::sendmsg(ElementPtr& msg) {
  288. std::string header_wire = msg->toWire();
  289. unsigned int length = 2 + header_wire.length();
  290. unsigned int length_net = htonl(length);
  291. unsigned short header_length = header_wire.length();
  292. unsigned short header_length_net = htons(header_length);
  293. impl_->writeData(&length_net, sizeof(length_net));
  294. impl_->writeData(&header_length_net, sizeof(header_length_net));
  295. impl_->writeData(header_wire.data(), header_length);
  296. }
  297. void
  298. Session::sendmsg(ElementPtr& env, ElementPtr& msg) {
  299. std::string header_wire = env->toWire();
  300. std::string body_wire = msg->toWire();
  301. unsigned int length = 2 + header_wire.length() + body_wire.length();
  302. unsigned int length_net = htonl(length);
  303. unsigned short header_length = header_wire.length();
  304. unsigned short header_length_net = htons(header_length);
  305. impl_->writeData(&length_net, sizeof(length_net));
  306. impl_->writeData(&header_length_net, sizeof(header_length_net));
  307. impl_->writeData(header_wire.data(), header_length);
  308. impl_->writeData(body_wire.data(), body_wire.length());
  309. }
  310. bool
  311. Session::recvmsg(ElementPtr& msg, bool nonblock, int seq) {
  312. ElementPtr l_env;
  313. return recvmsg(l_env, msg, nonblock, seq);
  314. }
  315. bool
  316. Session::recvmsg(ElementPtr& env, ElementPtr& msg,
  317. bool nonblock, int seq) {
  318. size_t length = impl_->readDataLength();
  319. ElementPtr l_env, l_msg;
  320. if (hasQueuedMsgs()) {
  321. ElementPtr q_el;
  322. for (int i = 0; i < impl_->queue_->size(); i++) {
  323. q_el = impl_->queue_->get(i);
  324. if (( seq == -1 &&
  325. !q_el->get(0)->contains("reply")
  326. ) || (
  327. q_el->get(0)->contains("reply") &&
  328. q_el->get(0)->get("reply")->intValue() == seq
  329. )
  330. ) {
  331. env = q_el->get(0);
  332. msg = q_el->get(1);
  333. impl_->queue_->remove(i);
  334. return true;
  335. }
  336. }
  337. }
  338. unsigned short header_length_net;
  339. impl_->readData(&header_length_net, sizeof(header_length_net));
  340. unsigned short header_length = ntohs(header_length_net);
  341. if (header_length > length || length < 2) {
  342. isc_throw(SessionError, "Length parameters invalid: total=" << length
  343. << ", header=" << header_length);
  344. }
  345. // remove the header-length bytes from the total length
  346. length -= 2;
  347. std::vector<char> buffer(length);
  348. impl_->readData(&buffer[0], length);
  349. std::string header_wire = std::string(&buffer[0], header_length);
  350. std::string body_wire = std::string(&buffer[0] + header_length,
  351. length - header_length);
  352. std::stringstream header_wire_stream;
  353. header_wire_stream << header_wire;
  354. l_env = Element::fromWire(header_wire_stream, header_length);
  355. std::stringstream body_wire_stream;
  356. body_wire_stream << body_wire;
  357. l_msg = Element::fromWire(body_wire_stream, length - header_length);
  358. if ((seq == -1 &&
  359. !l_env->contains("reply")
  360. ) || (
  361. l_env->contains("reply") &&
  362. l_env->get("reply")->intValue() == seq
  363. )
  364. ) {
  365. env = l_env;
  366. msg = l_msg;
  367. return true;
  368. } else {
  369. ElementPtr q_el = Element::createFromString("[]");
  370. q_el->add(l_env);
  371. q_el->add(l_msg);
  372. impl_->queue_->add(q_el);
  373. return recvmsg(env, msg, nonblock, seq);
  374. }
  375. // XXXMLG handle non-block here, and return false for short reads
  376. }
  377. void
  378. Session::subscribe(std::string group, std::string instance) {
  379. ElementPtr env = Element::create(std::map<std::string, ElementPtr>());
  380. env->set("type", Element::create("subscribe"));
  381. env->set("group", Element::create(group));
  382. env->set("instance", Element::create(instance));
  383. sendmsg(env);
  384. }
  385. void
  386. Session::unsubscribe(std::string group, std::string instance) {
  387. ElementPtr env = Element::create(std::map<std::string, ElementPtr>());
  388. env->set("type", Element::create("unsubscribe"));
  389. env->set("group", Element::create(group));
  390. env->set("instance", Element::create(instance));
  391. sendmsg(env);
  392. }
  393. int
  394. Session::group_sendmsg(ElementPtr msg, std::string group,
  395. std::string instance, std::string to)
  396. {
  397. ElementPtr env = Element::create(std::map<std::string, ElementPtr>());
  398. int nseq = ++impl_->sequence_;
  399. env->set("type", Element::create("send"));
  400. env->set("from", Element::create(impl_->lname_));
  401. env->set("to", Element::create(to));
  402. env->set("group", Element::create(group));
  403. env->set("instance", Element::create(instance));
  404. env->set("seq", Element::create(nseq));
  405. //env->set("msg", Element::create(msg->toWire()));
  406. sendmsg(env, msg);
  407. return nseq;
  408. }
  409. bool
  410. Session::group_recvmsg(ElementPtr& envelope, ElementPtr& msg,
  411. bool nonblock, int seq)
  412. {
  413. return (recvmsg(envelope, msg, nonblock, seq));
  414. }
  415. int
  416. Session::reply(ElementPtr& envelope, ElementPtr& newmsg) {
  417. ElementPtr env = Element::create(std::map<std::string, ElementPtr>());
  418. int nseq = ++impl_->sequence_;
  419. env->set("type", Element::create("send"));
  420. env->set("from", Element::create(impl_->lname_));
  421. env->set("to", Element::create(envelope->get("from")->stringValue()));
  422. env->set("group", Element::create(envelope->get("group")->stringValue()));
  423. env->set("instance", Element::create(envelope->get("instance")->stringValue()));
  424. env->set("seq", Element::create(nseq));
  425. env->set("reply", Element::create(envelope->get("seq")->intValue()));
  426. sendmsg(env, newmsg);
  427. return nseq;
  428. }
  429. bool
  430. Session::hasQueuedMsgs()
  431. {
  432. return (impl_->queue_->size() > 0);
  433. }
  434. }
  435. }