session.cc 14 KB

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