Channel.h 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. #ifndef HV_CHANNEL_HPP_
  2. #define HV_CHANNEL_HPP_
  3. #include <string>
  4. #include <functional>
  5. #include <memory>
  6. #include "hloop.h"
  7. #include "hsocket.h"
  8. #include "Buffer.h"
  9. namespace hv {
  10. class Channel {
  11. public:
  12. Channel(hio_t* io = NULL) {
  13. io_ = io;
  14. fd_ = -1;
  15. id_ = 0;
  16. ctx_ = NULL;
  17. status = CLOSED;
  18. if (io) {
  19. fd_ = hio_fd(io);
  20. id_ = hio_id(io);
  21. ctx_ = hio_context(io);
  22. hio_set_context(io, this);
  23. if (hio_is_opened(io)) {
  24. status = OPENED;
  25. }
  26. if (hio_getcb_read(io) == NULL) {
  27. hio_setcb_read(io_, on_read);
  28. }
  29. if (hio_getcb_write(io) == NULL) {
  30. hio_setcb_write(io_, on_write);
  31. }
  32. if (hio_getcb_close(io) == NULL) {
  33. hio_setcb_close(io_, on_close);
  34. }
  35. }
  36. }
  37. virtual ~Channel() {
  38. if (isOpened()) {
  39. close();
  40. // NOTE: Detach after destructor to avoid triggering onclose
  41. if (io_ && id_ == hio_id(io_)) {
  42. hio_set_context(io_, NULL);
  43. }
  44. }
  45. }
  46. hio_t* io() { return io_; }
  47. int fd() { return fd_; }
  48. uint32_t id() { return id_; }
  49. int error() { return hio_error(io_); }
  50. // context
  51. void* context() {
  52. return ctx_;
  53. }
  54. void setContext(void* ctx) {
  55. ctx_ = ctx;
  56. }
  57. template<class T>
  58. T* newContext() {
  59. ctx_ = new T;
  60. return (T*)ctx_;
  61. }
  62. template<class T>
  63. T* getContext() {
  64. return (T*)ctx_;
  65. }
  66. template<class T>
  67. void deleteContext() {
  68. if (ctx_) {
  69. delete (T*)ctx_;
  70. ctx_ = NULL;
  71. }
  72. }
  73. // contextPtr
  74. std::shared_ptr<void> contextPtr() {
  75. return contextPtr_;
  76. }
  77. void setContextPtr(const std::shared_ptr<void>& ctx) {
  78. contextPtr_ = ctx;
  79. }
  80. void setContextPtr(std::shared_ptr<void>&& ctx) {
  81. contextPtr_ = std::move(ctx);
  82. }
  83. template<class T>
  84. std::shared_ptr<T> newContextPtr() {
  85. contextPtr_ = std::make_shared<T>();
  86. return std::static_pointer_cast<T>(contextPtr_);
  87. }
  88. template<class T>
  89. std::shared_ptr<T> getContextPtr() {
  90. return std::static_pointer_cast<T>(contextPtr_);
  91. }
  92. void deleteContextPtr() {
  93. contextPtr_.reset();
  94. }
  95. bool isOpened() {
  96. if (io_ == NULL || status >= DISCONNECTED) return false;
  97. return id_ == hio_id(io_) && hio_is_opened(io_);
  98. }
  99. bool isClosed() {
  100. return !isOpened();
  101. }
  102. int startRead() {
  103. if (!isOpened()) return -1;
  104. return hio_read_start(io_);
  105. }
  106. int stopRead() {
  107. if (!isOpened()) return -1;
  108. return hio_read_stop(io_);
  109. }
  110. int readOnce() {
  111. if (!isOpened()) return -1;
  112. return hio_read_once(io_);
  113. }
  114. int readString() {
  115. if (!isOpened()) return -1;
  116. return hio_readstring(io_);
  117. }
  118. int readLine() {
  119. if (!isOpened()) return -1;
  120. return hio_readline(io_);
  121. }
  122. int readBytes(int len) {
  123. if (!isOpened() || len <= 0) return -1;
  124. return hio_readbytes(io_, len);
  125. }
  126. // write thread-safe
  127. int write(const void* data, int size) {
  128. if (!isOpened()) return -1;
  129. return hio_write(io_, data, size);
  130. }
  131. int write(Buffer* buf) {
  132. return write(buf->data(), buf->size());
  133. }
  134. int write(const std::string& str) {
  135. return write(str.data(), str.size());
  136. }
  137. // iobuf setting
  138. void setReadBuf(void* buf, size_t len) {
  139. if (io_ == NULL) return;
  140. hio_set_readbuf(io_, buf, len);
  141. }
  142. void setMaxReadBufsize(uint32_t size) {
  143. if (io_ == NULL) return;
  144. hio_set_max_read_bufsize(io_, size);
  145. }
  146. void setMaxWriteBufsize(uint32_t size) {
  147. if (io_ == NULL) return;
  148. hio_set_max_write_bufsize(io_, size);
  149. }
  150. size_t writeBufsize() {
  151. if (io_ == NULL) return 0;
  152. return hio_write_bufsize(io_);
  153. }
  154. bool isWriteComplete() {
  155. return writeBufsize() == 0;
  156. }
  157. // close thread-safe
  158. int close(bool async = false) {
  159. if (isClosed()) return -1;
  160. status = CLOSED;
  161. return async ? hio_close_async(io_) : hio_close(io_);
  162. }
  163. public:
  164. hio_t* io_;
  165. int fd_;
  166. uint32_t id_;
  167. void* ctx_;
  168. enum Status {
  169. OPENED,
  170. CONNECTING,
  171. CONNECTED,
  172. DISCONNECTED,
  173. CLOSED,
  174. } status;
  175. std::function<void(Buffer*)> onread;
  176. // NOTE: Use Channel::isWriteComplete in onwrite callback to determine whether all data has been written.
  177. std::function<void(Buffer*)> onwrite;
  178. std::function<void()> onclose;
  179. std::shared_ptr<void> contextPtr_;
  180. private:
  181. static void on_read(hio_t* io, void* data, int readbytes) {
  182. Channel* channel = (Channel*)hio_context(io);
  183. if (channel && channel->onread) {
  184. Buffer buf(data, readbytes);
  185. channel->onread(&buf);
  186. }
  187. }
  188. static void on_write(hio_t* io, const void* data, int writebytes) {
  189. Channel* channel = (Channel*)hio_context(io);
  190. if (channel && channel->onwrite) {
  191. Buffer buf((void*)data, writebytes);
  192. channel->onwrite(&buf);
  193. }
  194. }
  195. static void on_close(hio_t* io) {
  196. Channel* channel = (Channel*)hio_context(io);
  197. if (channel) {
  198. channel->status = CLOSED;
  199. if (channel->onclose) {
  200. channel->onclose();
  201. }
  202. }
  203. }
  204. };
  205. class SocketChannel : public Channel {
  206. public:
  207. std::function<void()> onconnect; // only for TcpClient
  208. std::function<void()> heartbeat;
  209. SocketChannel(hio_t* io) : Channel(io) {
  210. }
  211. virtual ~SocketChannel() {}
  212. // SSL/TLS
  213. int enableSSL() {
  214. if (io_ == NULL) return -1;
  215. return hio_enable_ssl(io_);
  216. }
  217. bool isSSL() {
  218. if (io_ == NULL) return false;
  219. return hio_is_ssl(io_);
  220. }
  221. int setSSL(hssl_t ssl) {
  222. if (io_ == NULL) return -1;
  223. return hio_set_ssl(io_, ssl);
  224. }
  225. int setSslCtx(hssl_ctx_t ssl_ctx) {
  226. if (io_ == NULL) return -1;
  227. return hio_set_ssl_ctx(io_, ssl_ctx);
  228. }
  229. int newSslCtx(hssl_ctx_opt_t* opt) {
  230. if (io_ == NULL) return -1;
  231. return hio_new_ssl_ctx(io_, opt);
  232. }
  233. // for hssl_set_sni_hostname
  234. int setHostname(const std::string& hostname) {
  235. if (io_ == NULL) return -1;
  236. return hio_set_hostname(io_, hostname.c_str());
  237. }
  238. // timeout
  239. void setConnectTimeout(int timeout_ms) {
  240. if (io_ == NULL) return;
  241. hio_set_connect_timeout(io_, timeout_ms);
  242. }
  243. void setCloseTimeout(int timeout_ms) {
  244. if (io_ == NULL) return;
  245. hio_set_close_timeout(io_, timeout_ms);
  246. }
  247. void setReadTimeout(int timeout_ms) {
  248. if (io_ == NULL) return;
  249. hio_set_read_timeout(io_, timeout_ms);
  250. }
  251. void setWriteTimeout(int timeout_ms) {
  252. if (io_ == NULL) return;
  253. hio_set_write_timeout(io_, timeout_ms);
  254. }
  255. void setKeepaliveTimeout(int timeout_ms) {
  256. if (io_ == NULL) return;
  257. hio_set_keepalive_timeout(io_, timeout_ms);
  258. }
  259. // heartbeat
  260. // NOTE: Beware of circular reference problems caused by passing SocketChannelPtr by value.
  261. void setHeartbeat(int interval_ms, std::function<void()> fn) {
  262. if (io_ == NULL) return;
  263. heartbeat = std::move(fn);
  264. hio_set_heartbeat(io_, interval_ms, send_heartbeat);
  265. }
  266. /*
  267. * unpack
  268. *
  269. * NOTE: unpack_setting_t of multiple IOs of the same function also are same,
  270. * so only the pointer of unpack_setting_t is stored in hio_t,
  271. * the life time of unpack_setting_t shoud be guaranteed by caller.
  272. */
  273. void setUnpack(unpack_setting_t* setting) {
  274. if (io_ == NULL) return;
  275. hio_set_unpack(io_, setting);
  276. }
  277. int startConnect(int port, const char* host = "127.0.0.1") {
  278. sockaddr_u peeraddr;
  279. memset(&peeraddr, 0, sizeof(peeraddr));
  280. int ret = sockaddr_set_ipport(&peeraddr, host, port);
  281. if (ret != 0) {
  282. // hloge("unknown host %s", host);
  283. return ret;
  284. }
  285. return startConnect(&peeraddr.sa);
  286. }
  287. int startConnect(struct sockaddr* peeraddr) {
  288. if (io_ == NULL) return -1;
  289. hio_set_peeraddr(io_, peeraddr, SOCKADDR_LEN(peeraddr));
  290. return startConnect();
  291. }
  292. int startConnect() {
  293. if (io_ == NULL) return -1;
  294. status = CONNECTING;
  295. hio_setcb_connect(io_, on_connect);
  296. return hio_connect(io_);
  297. }
  298. bool isConnected() {
  299. return status == CONNECTED && isOpened();
  300. }
  301. std::string localaddr() {
  302. if (io_ == NULL) return "";
  303. struct sockaddr* addr = hio_localaddr(io_);
  304. char buf[SOCKADDR_STRLEN] = {0};
  305. return SOCKADDR_STR(addr, buf);
  306. }
  307. std::string peeraddr() {
  308. if (io_ == NULL) return "";
  309. struct sockaddr* addr = hio_peeraddr(io_);
  310. char buf[SOCKADDR_STRLEN] = {0};
  311. return SOCKADDR_STR(addr, buf);
  312. }
  313. private:
  314. static void on_connect(hio_t* io) {
  315. SocketChannel* channel = (SocketChannel*)hio_context(io);
  316. if (channel) {
  317. channel->status = CONNECTED;
  318. if (channel->onconnect) {
  319. channel->onconnect();
  320. }
  321. }
  322. }
  323. static void send_heartbeat(hio_t* io) {
  324. SocketChannel* channel = (SocketChannel*)hio_context(io);
  325. if (channel && channel->heartbeat) {
  326. channel->heartbeat();
  327. }
  328. }
  329. };
  330. typedef std::shared_ptr<Channel> ChannelPtr;
  331. typedef std::shared_ptr<SocketChannel> SocketChannelPtr;
  332. }
  333. #endif // HV_CHANNEL_HPP_