1
0

Channel.h 9.9 KB

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