1
0

Channel.h 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. return async ? hio_close_async(io_) : hio_close(io_);
  163. }
  164. public:
  165. hio_t* io_;
  166. int fd_;
  167. uint32_t id_;
  168. void* ctx_;
  169. enum Status {
  170. OPENED,
  171. CONNECTING,
  172. CONNECTED,
  173. DISCONNECTED,
  174. CLOSED,
  175. };
  176. std::atomic<Status> status;
  177. std::function<void(Buffer*)> onread;
  178. // NOTE: Use Channel::isWriteComplete in onwrite callback to determine whether all data has been written.
  179. std::function<void(Buffer*)> onwrite;
  180. std::function<void()> onclose;
  181. std::shared_ptr<void> contextPtr_;
  182. private:
  183. static void on_read(hio_t* io, void* data, int readbytes) {
  184. Channel* channel = (Channel*)hio_context(io);
  185. if (channel && channel->onread) {
  186. Buffer buf(data, readbytes);
  187. channel->onread(&buf);
  188. }
  189. }
  190. static void on_write(hio_t* io, const void* data, int writebytes) {
  191. Channel* channel = (Channel*)hio_context(io);
  192. if (channel && channel->onwrite) {
  193. Buffer buf((void*)data, writebytes);
  194. channel->onwrite(&buf);
  195. }
  196. }
  197. static void on_close(hio_t* io) {
  198. Channel* channel = (Channel*)hio_context(io);
  199. if (channel) {
  200. channel->status = CLOSED;
  201. if (channel->onclose) {
  202. channel->onclose();
  203. }
  204. }
  205. }
  206. };
  207. class SocketChannel : public Channel {
  208. public:
  209. std::function<void()> onconnect; // only for TcpClient
  210. std::function<void()> heartbeat;
  211. SocketChannel(hio_t* io) : Channel(io) {
  212. }
  213. virtual ~SocketChannel() {}
  214. // SSL/TLS
  215. int enableSSL() {
  216. if (io_ == NULL) return -1;
  217. return hio_enable_ssl(io_);
  218. }
  219. bool isSSL() {
  220. if (io_ == NULL) return false;
  221. return hio_is_ssl(io_);
  222. }
  223. int setSSL(hssl_t ssl) {
  224. if (io_ == NULL) return -1;
  225. return hio_set_ssl(io_, ssl);
  226. }
  227. int setSslCtx(hssl_ctx_t ssl_ctx) {
  228. if (io_ == NULL) return -1;
  229. return hio_set_ssl_ctx(io_, ssl_ctx);
  230. }
  231. int newSslCtx(hssl_ctx_opt_t* opt) {
  232. if (io_ == NULL) return -1;
  233. return hio_new_ssl_ctx(io_, opt);
  234. }
  235. // for hssl_set_sni_hostname
  236. int setHostname(const std::string& hostname) {
  237. if (io_ == NULL) return -1;
  238. return hio_set_hostname(io_, hostname.c_str());
  239. }
  240. // timeout
  241. void setConnectTimeout(int timeout_ms) {
  242. if (io_ == NULL) return;
  243. hio_set_connect_timeout(io_, timeout_ms);
  244. }
  245. void setCloseTimeout(int timeout_ms) {
  246. if (io_ == NULL) return;
  247. hio_set_close_timeout(io_, timeout_ms);
  248. }
  249. void setReadTimeout(int timeout_ms) {
  250. if (io_ == NULL) return;
  251. hio_set_read_timeout(io_, timeout_ms);
  252. }
  253. void setWriteTimeout(int timeout_ms) {
  254. if (io_ == NULL) return;
  255. hio_set_write_timeout(io_, timeout_ms);
  256. }
  257. void setKeepaliveTimeout(int timeout_ms) {
  258. if (io_ == NULL) return;
  259. hio_set_keepalive_timeout(io_, timeout_ms);
  260. }
  261. // heartbeat
  262. // NOTE: Beware of circular reference problems caused by passing SocketChannelPtr by value.
  263. void setHeartbeat(int interval_ms, std::function<void()> fn) {
  264. if (io_ == NULL) return;
  265. heartbeat = std::move(fn);
  266. hio_set_heartbeat(io_, interval_ms, send_heartbeat);
  267. }
  268. /*
  269. * unpack
  270. *
  271. * NOTE: unpack_setting_t of multiple IOs of the same function also are same,
  272. * so only the pointer of unpack_setting_t is stored in hio_t,
  273. * the life time of unpack_setting_t shoud be guaranteed by caller.
  274. */
  275. void setUnpack(unpack_setting_t* setting) {
  276. if (io_ == NULL) return;
  277. hio_set_unpack(io_, setting);
  278. }
  279. int startConnect(int port, const char* host = "127.0.0.1") {
  280. sockaddr_u peeraddr;
  281. memset(&peeraddr, 0, sizeof(peeraddr));
  282. int ret = sockaddr_set_ipport(&peeraddr, host, port);
  283. if (ret != 0) {
  284. // hloge("unknown host %s", host);
  285. return ret;
  286. }
  287. return startConnect(&peeraddr.sa);
  288. }
  289. int startConnect(struct sockaddr* peeraddr) {
  290. if (io_ == NULL) return -1;
  291. hio_set_peeraddr(io_, peeraddr, SOCKADDR_LEN(peeraddr));
  292. return startConnect();
  293. }
  294. int startConnect() {
  295. if (io_ == NULL) return -1;
  296. status = CONNECTING;
  297. hio_setcb_connect(io_, on_connect);
  298. return hio_connect(io_);
  299. }
  300. bool isConnected() {
  301. return status == CONNECTED && isOpened();
  302. }
  303. std::string localaddr() {
  304. if (io_ == NULL) return "";
  305. struct sockaddr* addr = hio_localaddr(io_);
  306. char buf[SOCKADDR_STRLEN] = {0};
  307. return SOCKADDR_STR(addr, buf);
  308. }
  309. std::string peeraddr() {
  310. if (io_ == NULL) return "";
  311. struct sockaddr* addr = hio_peeraddr(io_);
  312. char buf[SOCKADDR_STRLEN] = {0};
  313. return SOCKADDR_STR(addr, buf);
  314. }
  315. private:
  316. static void on_connect(hio_t* io) {
  317. SocketChannel* channel = (SocketChannel*)hio_context(io);
  318. if (channel) {
  319. channel->status = CONNECTED;
  320. if (channel->onconnect) {
  321. channel->onconnect();
  322. }
  323. }
  324. }
  325. static void send_heartbeat(hio_t* io) {
  326. SocketChannel* channel = (SocketChannel*)hio_context(io);
  327. if (channel && channel->heartbeat) {
  328. channel->heartbeat();
  329. }
  330. }
  331. };
  332. typedef std::shared_ptr<Channel> ChannelPtr;
  333. typedef std::shared_ptr<SocketChannel> SocketChannelPtr;
  334. }
  335. #endif // HV_CHANNEL_HPP_