hloop.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. #include "hloop.h"
  2. #include "hevent.h"
  3. #include "iowatcher.h"
  4. #include "hdef.h"
  5. #include "hbase.h"
  6. #include "hlog.h"
  7. #include "hmath.h"
  8. #include "htime.h"
  9. #include "hsocket.h"
  10. #define PAUSE_TIME 10 // ms
  11. #define MAX_BLOCK_TIME 1000 // ms
  12. #define IO_ARRAY_INIT_SIZE 1024
  13. #define CUSTOM_EVENT_QUEUE_INIT_SIZE 16
  14. /*
  15. * hio lifeline:
  16. * hio_get => HV_ALLOC_SIZEOF(io) => hio_init =>
  17. * hio_ready => hio_add => hio_del => hio_done =>
  18. * hio_free => HV_FREE(io)
  19. */
  20. static void hio_init(hio_t* io);
  21. static void hio_ready(hio_t* io);
  22. static void hio_done(hio_t* io);
  23. static void hio_free(hio_t* io);
  24. static void __hidle_del(hidle_t* idle);
  25. static void __htimer_del(htimer_t* timer);
  26. static int timers_compare(const struct heap_node* lhs, const struct heap_node* rhs) {
  27. return TIMER_ENTRY(lhs)->next_timeout < TIMER_ENTRY(rhs)->next_timeout;
  28. }
  29. static int hloop_process_idles(hloop_t* loop) {
  30. int nidles = 0;
  31. struct list_node* node = loop->idles.next;
  32. hidle_t* idle = NULL;
  33. while (node != &loop->idles) {
  34. idle = IDLE_ENTRY(node);
  35. node = node->next;
  36. if (idle->repeat != INFINITE) {
  37. --idle->repeat;
  38. }
  39. if (idle->repeat == 0) {
  40. __hidle_del(idle);
  41. }
  42. EVENT_PENDING(idle);
  43. ++nidles;
  44. }
  45. return nidles;
  46. }
  47. static int hloop_process_timers(hloop_t* loop) {
  48. int ntimers = 0;
  49. htimer_t* timer = NULL;
  50. uint64_t now_hrtime = hloop_now_hrtime(loop);
  51. while (loop->timers.root) {
  52. timer = TIMER_ENTRY(loop->timers.root);
  53. if (timer->next_timeout > now_hrtime) {
  54. break;
  55. }
  56. if (timer->repeat != INFINITE) {
  57. --timer->repeat;
  58. }
  59. if (timer->repeat == 0) {
  60. __htimer_del(timer);
  61. }
  62. else {
  63. heap_dequeue(&loop->timers);
  64. if (timer->event_type == HEVENT_TYPE_TIMEOUT) {
  65. while (timer->next_timeout <= now_hrtime) {
  66. timer->next_timeout += ((htimeout_t*)timer)->timeout * 1000;
  67. }
  68. }
  69. else if (timer->event_type == HEVENT_TYPE_PERIOD) {
  70. hperiod_t* period = (hperiod_t*)timer;
  71. timer->next_timeout = cron_next_timeout(period->minute, period->hour, period->day,
  72. period->week, period->month) * 1000000;
  73. }
  74. heap_insert(&loop->timers, &timer->node);
  75. }
  76. EVENT_PENDING(timer);
  77. ++ntimers;
  78. }
  79. return ntimers;
  80. }
  81. static int hloop_process_ios(hloop_t* loop, int timeout) {
  82. int nevents = iowatcher_poll_events(loop, timeout);
  83. if (nevents < 0) {
  84. hloge("poll_events error=%d", -nevents);
  85. }
  86. return nevents < 0 ? 0 : nevents;
  87. }
  88. static int hloop_process_pendings(hloop_t* loop) {
  89. if (loop->npendings == 0) return 0;
  90. hevent_t* cur = NULL;
  91. hevent_t* next = NULL;
  92. int ncbs = 0;
  93. for (int i = HEVENT_PRIORITY_SIZE-1; i >= 0; --i) {
  94. cur = loop->pendings[i];
  95. while (cur) {
  96. next = cur->pending_next;
  97. if (cur->pending) {
  98. if (cur->active && cur->cb) {
  99. cur->cb(cur);
  100. ++ncbs;
  101. }
  102. cur->pending = 0;
  103. if (cur->destroy) {
  104. EVENT_DEL(cur);
  105. }
  106. }
  107. cur = next;
  108. }
  109. loop->pendings[i] = NULL;
  110. }
  111. loop->npendings = 0;
  112. return ncbs;
  113. }
  114. static int hloop_process_events(hloop_t* loop) {
  115. // ios -> timers -> idles
  116. int nios, ntimers, nidles;
  117. nios = ntimers = nidles = 0;
  118. // calc blocktime
  119. int32_t blocktime = MAX_BLOCK_TIME;
  120. if (loop->timers.root) {
  121. hloop_update_time(loop);
  122. uint64_t next_min_timeout = TIMER_ENTRY(loop->timers.root)->next_timeout;
  123. int64_t blocktime_us = next_min_timeout - hloop_now_hrtime(loop);
  124. if (blocktime_us <= 0) goto process_timers;
  125. blocktime = blocktime_us / 1000;
  126. ++blocktime;
  127. blocktime = MIN(blocktime, MAX_BLOCK_TIME);
  128. }
  129. if (loop->nios) {
  130. nios = hloop_process_ios(loop, blocktime);
  131. }
  132. else {
  133. msleep(blocktime);
  134. }
  135. hloop_update_time(loop);
  136. process_timers:
  137. if (loop->ntimers) {
  138. ntimers = hloop_process_timers(loop);
  139. }
  140. int npendings = loop->npendings;
  141. if (npendings == 0) {
  142. if (loop->nidles) {
  143. nidles= hloop_process_idles(loop);
  144. }
  145. }
  146. int ncbs = hloop_process_pendings(loop);
  147. //printd("blocktime=%d nios=%d/%u ntimers=%d/%u nidles=%d/%u nactives=%d npendings=%d ncbs=%d\n",
  148. //blocktime, nios, loop->nios, ntimers, loop->ntimers, nidles, loop->nidles,
  149. //loop->nactives, npendings, ncbs);
  150. return ncbs;
  151. }
  152. static void hloop_init(hloop_t* loop) {
  153. loop->status = HLOOP_STATUS_STOP;
  154. // idles
  155. list_init(&loop->idles);
  156. // timers
  157. heap_init(&loop->timers, timers_compare);
  158. // ios: init when hio_get
  159. // io_array_init(&loop->ios, IO_ARRAY_INIT_SIZE);
  160. // readbuf: alloc when hio_set_readbuf
  161. // loop->readbuf.len = HLOOP_READ_BUFSIZE;
  162. // HV_ALLOC(loop->readbuf.base, loop->readbuf.len);
  163. // iowatcher: init when iowatcher_add_event
  164. // iowatcher_init(loop);
  165. // custom_events: init when hloop_post_event
  166. // event_queue_init(&loop->custom_events, 4);
  167. loop->sockpair[0] = loop->sockpair[1] = -1;
  168. hmutex_init(&loop->custom_events_mutex);
  169. // NOTE: init start_time here, because htimer_add use it.
  170. loop->start_ms = gettimeofday_ms();
  171. loop->start_hrtime = loop->cur_hrtime = gethrtime_us();
  172. }
  173. static void hloop_cleanup(hloop_t* loop) {
  174. // pendings
  175. printd("cleanup pendings...\n");
  176. for (int i = 0; i < HEVENT_PRIORITY_SIZE; ++i) {
  177. loop->pendings[i] = NULL;
  178. }
  179. // ios
  180. printd("cleanup ios...\n");
  181. for (int i = 0; i < loop->ios.maxsize; ++i) {
  182. hio_t* io = loop->ios.ptr[i];
  183. if (io) {
  184. hio_free(io);
  185. }
  186. }
  187. io_array_cleanup(&loop->ios);
  188. // idles
  189. printd("cleanup idles...\n");
  190. struct list_node* node = loop->idles.next;
  191. hidle_t* idle;
  192. while (node != &loop->idles) {
  193. idle = IDLE_ENTRY(node);
  194. node = node->next;
  195. HV_FREE(idle);
  196. }
  197. list_init(&loop->idles);
  198. // timers
  199. printd("cleanup timers...\n");
  200. htimer_t* timer;
  201. while (loop->timers.root) {
  202. timer = TIMER_ENTRY(loop->timers.root);
  203. heap_dequeue(&loop->timers);
  204. HV_FREE(timer);
  205. }
  206. heap_init(&loop->timers, NULL);
  207. // readbuf
  208. if (loop->readbuf.base && loop->readbuf.len) {
  209. HV_FREE(loop->readbuf.base);
  210. loop->readbuf.base = NULL;
  211. loop->readbuf.len = 0;
  212. }
  213. // iowatcher
  214. iowatcher_cleanup(loop);
  215. // custom_events
  216. hmutex_lock(&loop->custom_events_mutex);
  217. if (loop->sockpair[0] != -1 && loop->sockpair[1] != -1) {
  218. closesocket(loop->sockpair[0]);
  219. closesocket(loop->sockpair[1]);
  220. loop->sockpair[0] = loop->sockpair[1] = -1;
  221. }
  222. event_queue_cleanup(&loop->custom_events);
  223. hmutex_unlock(&loop->custom_events_mutex);
  224. hmutex_destroy(&loop->custom_events_mutex);
  225. }
  226. hloop_t* hloop_new(int flags) {
  227. hloop_t* loop;
  228. HV_ALLOC_SIZEOF(loop);
  229. hloop_init(loop);
  230. loop->flags |= flags;
  231. return loop;
  232. }
  233. void hloop_free(hloop_t** pp) {
  234. if (pp && *pp) {
  235. hloop_cleanup(*pp);
  236. HV_FREE(*pp);
  237. *pp = NULL;
  238. }
  239. }
  240. int hloop_run(hloop_t* loop) {
  241. loop->status = HLOOP_STATUS_RUNNING;
  242. while (loop->status != HLOOP_STATUS_STOP) {
  243. if (loop->status == HLOOP_STATUS_PAUSE) {
  244. msleep(PAUSE_TIME);
  245. hloop_update_time(loop);
  246. continue;
  247. }
  248. ++loop->loop_cnt;
  249. if (loop->nactives == 0 && loop->flags & HLOOP_FLAG_QUIT_WHEN_NO_ACTIVE_EVENTS) {
  250. break;
  251. }
  252. hloop_process_events(loop);
  253. if (loop->flags & HLOOP_FLAG_RUN_ONCE) {
  254. break;
  255. }
  256. }
  257. loop->status = HLOOP_STATUS_STOP;
  258. loop->end_hrtime = gethrtime_us();
  259. if (loop->flags & HLOOP_FLAG_AUTO_FREE) {
  260. hloop_cleanup(loop);
  261. HV_FREE(loop);
  262. }
  263. return 0;
  264. }
  265. int hloop_stop(hloop_t* loop) {
  266. loop->status = HLOOP_STATUS_STOP;
  267. return 0;
  268. }
  269. int hloop_pause(hloop_t* loop) {
  270. if (loop->status == HLOOP_STATUS_RUNNING) {
  271. loop->status = HLOOP_STATUS_PAUSE;
  272. }
  273. return 0;
  274. }
  275. int hloop_resume(hloop_t* loop) {
  276. if (loop->status == HLOOP_STATUS_PAUSE) {
  277. loop->status = HLOOP_STATUS_RUNNING;
  278. }
  279. return 0;
  280. }
  281. void hloop_update_time(hloop_t* loop) {
  282. loop->cur_hrtime = gethrtime_us();
  283. if (ABS((int64_t)hloop_now(loop) - (int64_t)time(NULL)) > 1) {
  284. // systemtime changed, we adjust start_ms
  285. loop->start_ms = gettimeofday_ms() - (loop->cur_hrtime - loop->start_hrtime) / 1000;
  286. }
  287. }
  288. uint64_t hloop_now(hloop_t* loop) {
  289. return loop->start_ms / 1000 + (loop->cur_hrtime - loop->start_hrtime) / 1000000;
  290. }
  291. uint64_t hloop_now_ms(hloop_t* loop) {
  292. return loop->start_ms + (loop->cur_hrtime - loop->start_hrtime) / 1000;
  293. }
  294. uint64_t hloop_now_hrtime(hloop_t* loop) {
  295. return loop->start_ms * 1000 + (loop->cur_hrtime - loop->start_hrtime);
  296. }
  297. void hloop_set_userdata(hloop_t* loop, void* userdata) {
  298. loop->userdata = userdata;
  299. }
  300. void* hloop_userdata(hloop_t* loop) {
  301. return loop->userdata;
  302. }
  303. hidle_t* hidle_add(hloop_t* loop, hidle_cb cb, uint32_t repeat) {
  304. hidle_t* idle;
  305. HV_ALLOC_SIZEOF(idle);
  306. idle->event_type = HEVENT_TYPE_IDLE;
  307. idle->priority = HEVENT_LOWEST_PRIORITY;
  308. idle->repeat = repeat;
  309. list_add(&idle->node, &loop->idles);
  310. EVENT_ADD(loop, idle, cb);
  311. loop->nidles++;
  312. return idle;
  313. }
  314. static void __hidle_del(hidle_t* idle) {
  315. if (idle->destroy) return;
  316. idle->destroy = 1;
  317. list_del(&idle->node);
  318. idle->loop->nidles--;
  319. }
  320. void hidle_del(hidle_t* idle) {
  321. if (!idle->active) return;
  322. EVENT_DEL(idle);
  323. __hidle_del(idle);
  324. }
  325. htimer_t* htimer_add(hloop_t* loop, htimer_cb cb, uint32_t timeout, uint32_t repeat) {
  326. if (timeout == 0) return NULL;
  327. htimeout_t* timer;
  328. HV_ALLOC_SIZEOF(timer);
  329. timer->event_type = HEVENT_TYPE_TIMEOUT;
  330. timer->priority = HEVENT_HIGHEST_PRIORITY;
  331. timer->repeat = repeat;
  332. timer->timeout = timeout;
  333. hloop_update_time(loop);
  334. timer->next_timeout = hloop_now_hrtime(loop) + timeout*1000;
  335. heap_insert(&loop->timers, &timer->node);
  336. EVENT_ADD(loop, timer, cb);
  337. loop->ntimers++;
  338. return (htimer_t*)timer;
  339. }
  340. void htimer_reset(htimer_t* timer) {
  341. if (timer->event_type != HEVENT_TYPE_TIMEOUT) {
  342. return;
  343. }
  344. hloop_t* loop = timer->loop;
  345. htimeout_t* timeout = (htimeout_t*)timer;
  346. if (timer->pending) {
  347. if (timer->repeat == 0) {
  348. timer->repeat = 1;
  349. }
  350. }
  351. else {
  352. heap_remove(&loop->timers, &timer->node);
  353. }
  354. timer->next_timeout = hloop_now_hrtime(loop) + timeout->timeout*1000;
  355. heap_insert(&loop->timers, &timer->node);
  356. EVENT_RESET(timer);
  357. }
  358. htimer_t* htimer_add_period(hloop_t* loop, htimer_cb cb,
  359. int8_t minute, int8_t hour, int8_t day,
  360. int8_t week, int8_t month, uint32_t repeat) {
  361. if (minute > 59 || hour > 23 || day > 31 || week > 6 || month > 12) {
  362. return NULL;
  363. }
  364. hperiod_t* timer;
  365. HV_ALLOC_SIZEOF(timer);
  366. timer->event_type = HEVENT_TYPE_PERIOD;
  367. timer->priority = HEVENT_HIGH_PRIORITY;
  368. timer->repeat = repeat;
  369. timer->minute = minute;
  370. timer->hour = hour;
  371. timer->day = day;
  372. timer->month = month;
  373. timer->week = week;
  374. timer->next_timeout = cron_next_timeout(minute, hour, day, week, month) * 1000000;
  375. heap_insert(&loop->timers, &timer->node);
  376. EVENT_ADD(loop, timer, cb);
  377. loop->ntimers++;
  378. return (htimer_t*)timer;
  379. }
  380. static void __htimer_del(htimer_t* timer) {
  381. if (timer->destroy) return;
  382. heap_remove(&timer->loop->timers, &timer->node);
  383. timer->loop->ntimers--;
  384. timer->destroy = 1;
  385. }
  386. void htimer_del(htimer_t* timer) {
  387. if (!timer->active) return;
  388. __htimer_del(timer);
  389. EVENT_DEL(timer);
  390. }
  391. const char* hio_engine() {
  392. #ifdef EVENT_SELECT
  393. return "select";
  394. #elif defined(EVENT_POLL)
  395. return "poll";
  396. #elif defined(EVENT_EPOLL)
  397. return "epoll";
  398. #elif defined(EVENT_KQUEUE)
  399. return "kqueue";
  400. #elif defined(EVENT_IOCP)
  401. return "iocp";
  402. #elif defined(EVENT_PORT)
  403. return "evport";
  404. #else
  405. return "noevent";
  406. #endif
  407. }
  408. static void fill_io_type(hio_t* io) {
  409. int type = 0;
  410. socklen_t optlen = sizeof(int);
  411. int ret = getsockopt(io->fd, SOL_SOCKET, SO_TYPE, (char*)&type, &optlen);
  412. printd("getsockopt SO_TYPE fd=%d ret=%d type=%d errno=%d\n", io->fd, ret, type, socket_errno());
  413. if (ret == 0) {
  414. switch (type) {
  415. case SOCK_STREAM: io->io_type = HIO_TYPE_TCP; break;
  416. case SOCK_DGRAM: io->io_type = HIO_TYPE_UDP; break;
  417. case SOCK_RAW: io->io_type = HIO_TYPE_IP; break;
  418. default: io->io_type = HIO_TYPE_SOCKET; break;
  419. }
  420. }
  421. else if (socket_errno() == ENOTSOCK) {
  422. switch (io->fd) {
  423. case 0: io->io_type = HIO_TYPE_STDIN; break;
  424. case 1: io->io_type = HIO_TYPE_STDOUT; break;
  425. case 2: io->io_type = HIO_TYPE_STDERR; break;
  426. default: io->io_type = HIO_TYPE_FILE; break;
  427. }
  428. }
  429. }
  430. static void hio_socket_init(hio_t* io) {
  431. // nonblocking
  432. nonblocking(io->fd);
  433. // fill io->localaddr io->peeraddr
  434. if (io->localaddr == NULL) {
  435. HV_ALLOC(io->localaddr, sizeof(sockaddr_u));
  436. }
  437. if (io->peeraddr == NULL) {
  438. HV_ALLOC(io->peeraddr, sizeof(sockaddr_u));
  439. }
  440. socklen_t addrlen = sizeof(sockaddr_u);
  441. int ret = getsockname(io->fd, io->localaddr, &addrlen);
  442. printd("getsockname fd=%d ret=%d errno=%d\n", io->fd, ret, socket_errno());
  443. // NOTE:
  444. // tcp_server peeraddr set by accept
  445. // udp_server peeraddr set by recvfrom
  446. // tcp_client/udp_client peeraddr set by hio_setpeeraddr
  447. if (io->io_type == HIO_TYPE_TCP || io->io_type == HIO_TYPE_SSL) {
  448. // tcp acceptfd
  449. addrlen = sizeof(sockaddr_u);
  450. ret = getpeername(io->fd, io->peeraddr, &addrlen);
  451. printd("getpeername fd=%d ret=%d errno=%d\n", io->fd, ret, socket_errno());
  452. }
  453. }
  454. void hio_init(hio_t* io) {
  455. // alloc localaddr,peeraddr when hio_socket_init
  456. /*
  457. if (io->localaddr == NULL) {
  458. HV_ALLOC(io->localaddr, sizeof(sockaddr_u));
  459. }
  460. if (io->peeraddr == NULL) {
  461. HV_ALLOC(io->peeraddr, sizeof(sockaddr_u));
  462. }
  463. */
  464. // write_queue init when hwrite try_write failed
  465. // write_queue_init(&io->write_queue, 4);
  466. }
  467. void hio_ready(hio_t* io) {
  468. if (io->ready) return;
  469. // flags
  470. io->ready = 1;
  471. io->closed = 0;
  472. io->accept = io->connect = io->connectex = 0;
  473. io->recv = io->send = 0;
  474. io->recvfrom = io->sendto = 0;
  475. io->close = 0;
  476. // public:
  477. io->io_type = HIO_TYPE_UNKNOWN;
  478. io->error = 0;
  479. io->events = io->revents = 0;
  480. // callbacks
  481. io->read_cb = NULL;
  482. io->write_cb = NULL;
  483. io->close_cb = 0;
  484. io->accept_cb = 0;
  485. io->connect_cb = 0;
  486. // timers
  487. io->connect_timeout = 0;
  488. io->connect_timer = NULL;
  489. io->close_timeout = 0;
  490. io->close_timer = NULL;
  491. io->keepalive_timeout = 0;
  492. io->keepalive_timer = NULL;
  493. io->heartbeat_interval = 0;
  494. io->heartbeat_fn = NULL;
  495. io->heartbeat_timer = NULL;
  496. // private:
  497. io->event_index[0] = io->event_index[1] = -1;
  498. io->hovlp = NULL;
  499. io->ssl = NULL;
  500. // io_type
  501. fill_io_type(io);
  502. if (io->io_type & HIO_TYPE_SOCKET) {
  503. hio_socket_init(io);
  504. }
  505. }
  506. void hio_done(hio_t* io) {
  507. if (!io->ready) return;
  508. io->ready = 0;
  509. offset_buf_t* pbuf = NULL;
  510. while (!write_queue_empty(&io->write_queue)) {
  511. pbuf = write_queue_front(&io->write_queue);
  512. HV_FREE(pbuf->base);
  513. write_queue_pop_front(&io->write_queue);
  514. }
  515. write_queue_cleanup(&io->write_queue);
  516. }
  517. void hio_free(hio_t* io) {
  518. if (io == NULL) return;
  519. // NOTE: call hio_done to cleanup write_queue
  520. hio_done(io);
  521. hio_close(io);
  522. HV_FREE(io->localaddr);
  523. HV_FREE(io->peeraddr);
  524. HV_FREE(io);
  525. }
  526. hio_t* hio_get(hloop_t* loop, int fd) {
  527. if (loop->ios.maxsize == 0) {
  528. io_array_init(&loop->ios, IO_ARRAY_INIT_SIZE);
  529. }
  530. if (fd >= loop->ios.maxsize) {
  531. int newsize = ceil2e(fd);
  532. io_array_resize(&loop->ios, newsize > fd ? newsize : 2*fd);
  533. }
  534. hio_t* io = loop->ios.ptr[fd];
  535. if (io == NULL) {
  536. HV_ALLOC_SIZEOF(io);
  537. hio_init(io);
  538. io->event_type = HEVENT_TYPE_IO;
  539. io->loop = loop;
  540. io->fd = fd;
  541. loop->ios.ptr[fd] = io;
  542. }
  543. if (!io->ready) {
  544. hio_ready(io);
  545. }
  546. return io;
  547. }
  548. int hio_add(hio_t* io, hio_cb cb, int events) {
  549. printd("hio_add fd=%d events=%d\n", io->fd, events);
  550. #ifdef OS_WIN
  551. // Windows iowatcher not work on stdio
  552. if (io->fd < 3) return 0;
  553. #endif
  554. hloop_t* loop = io->loop;
  555. if (!io->active) {
  556. EVENT_ADD(loop, io, cb);
  557. loop->nios++;
  558. }
  559. if (!io->ready) {
  560. hio_ready(io);
  561. }
  562. if (cb) {
  563. io->cb = (hevent_cb)cb;
  564. }
  565. iowatcher_add_event(loop, io->fd, events);
  566. io->events |= events;
  567. return 0;
  568. }
  569. int hio_del(hio_t* io, int events) {
  570. printd("hio_del fd=%d io->events=%d events=%d\n", io->fd, io->events, events);
  571. #ifdef OS_WIN
  572. // Windows iowatcher not work on stdio
  573. if (io->fd < 3) return 0;
  574. #endif
  575. if (io->active) {
  576. iowatcher_del_event(io->loop, io->fd, events);
  577. io->events &= ~events;
  578. if (io->events == 0) {
  579. io->loop->nios--;
  580. // NOTE: not EVENT_DEL, avoid free
  581. EVENT_INACTIVE(io);
  582. }
  583. }
  584. if (!io->active) {
  585. hio_done(io);
  586. }
  587. return 0;
  588. }
  589. hio_t* hread(hloop_t* loop, int fd, void* buf, size_t len, hread_cb read_cb) {
  590. hio_t* io = hio_get(loop, fd);
  591. assert(io != NULL);
  592. io->readbuf.base = (char*)buf;
  593. io->readbuf.len = len;
  594. if (read_cb) {
  595. io->read_cb = read_cb;
  596. }
  597. hio_read(io);
  598. return io;
  599. }
  600. hio_t* hwrite(hloop_t* loop, int fd, const void* buf, size_t len, hwrite_cb write_cb) {
  601. hio_t* io = hio_get(loop, fd);
  602. assert(io != NULL);
  603. if (write_cb) {
  604. io->write_cb = write_cb;
  605. }
  606. hio_write(io, buf, len);
  607. return io;
  608. }
  609. hio_t* haccept(hloop_t* loop, int listenfd, haccept_cb accept_cb) {
  610. hio_t* io = hio_get(loop, listenfd);
  611. assert(io != NULL);
  612. if (accept_cb) {
  613. io->accept_cb = accept_cb;
  614. }
  615. hio_accept(io);
  616. return io;
  617. }
  618. hio_t* hconnect (hloop_t* loop, int connfd, hconnect_cb connect_cb) {
  619. hio_t* io = hio_get(loop, connfd);
  620. assert(io != NULL);
  621. if (connect_cb) {
  622. io->connect_cb = connect_cb;
  623. }
  624. hio_connect(io);
  625. return io;
  626. }
  627. void hclose (hloop_t* loop, int fd) {
  628. hio_t* io = hio_get(loop, fd);
  629. assert(io != NULL);
  630. hio_close(io);
  631. }
  632. hio_t* hrecv (hloop_t* loop, int connfd, void* buf, size_t len, hread_cb read_cb) {
  633. //hio_t* io = hio_get(loop, connfd);
  634. //assert(io != NULL);
  635. //io->recv = 1;
  636. //if (io->io_type != HIO_TYPE_SSL) {
  637. //io->io_type = HIO_TYPE_TCP;
  638. //}
  639. return hread(loop, connfd, buf, len, read_cb);
  640. }
  641. hio_t* hsend (hloop_t* loop, int connfd, const void* buf, size_t len, hwrite_cb write_cb) {
  642. //hio_t* io = hio_get(loop, connfd);
  643. //assert(io != NULL);
  644. //io->send = 1;
  645. //if (io->io_type != HIO_TYPE_SSL) {
  646. //io->io_type = HIO_TYPE_TCP;
  647. //}
  648. return hwrite(loop, connfd, buf, len, write_cb);
  649. }
  650. hio_t* hrecvfrom (hloop_t* loop, int sockfd, void* buf, size_t len, hread_cb read_cb) {
  651. //hio_t* io = hio_get(loop, sockfd);
  652. //assert(io != NULL);
  653. //io->recvfrom = 1;
  654. //io->io_type = HIO_TYPE_UDP;
  655. return hread(loop, sockfd, buf, len, read_cb);
  656. }
  657. hio_t* hsendto (hloop_t* loop, int sockfd, const void* buf, size_t len, hwrite_cb write_cb) {
  658. //hio_t* io = hio_get(loop, sockfd);
  659. //assert(io != NULL);
  660. //io->sendto = 1;
  661. //io->io_type = HIO_TYPE_UDP;
  662. return hwrite(loop, sockfd, buf, len, write_cb);
  663. }
  664. hio_t* hloop_create_tcp_server (hloop_t* loop, const char* host, int port, haccept_cb accept_cb) {
  665. int listenfd = Listen(port, host);
  666. if (listenfd < 0) {
  667. return NULL;
  668. }
  669. hio_t* io = haccept(loop, listenfd, accept_cb);
  670. if (io == NULL) {
  671. closesocket(listenfd);
  672. }
  673. return io;
  674. }
  675. hio_t* hloop_create_tcp_client (hloop_t* loop, const char* host, int port, hconnect_cb connect_cb) {
  676. sockaddr_u peeraddr;
  677. memset(&peeraddr, 0, sizeof(peeraddr));
  678. int ret = sockaddr_set_ipport(&peeraddr, host, port);
  679. if (ret != 0) {
  680. //printf("unknown host: %s\n", host);
  681. return NULL;
  682. }
  683. int connfd = socket(peeraddr.sa.sa_family, SOCK_STREAM, 0);
  684. if (connfd < 0) {
  685. perror("socket");
  686. return NULL;
  687. }
  688. hio_t* io = hio_get(loop, connfd);
  689. assert(io != NULL);
  690. hio_set_peeraddr(io, &peeraddr.sa, sockaddr_len(&peeraddr));
  691. hconnect(loop, connfd, connect_cb);
  692. return io;
  693. }
  694. // @server: socket -> bind -> hrecvfrom
  695. hio_t* hloop_create_udp_server(hloop_t* loop, const char* host, int port) {
  696. int bindfd = Bind(port, host, SOCK_DGRAM);
  697. if (bindfd < 0) {
  698. return NULL;
  699. }
  700. return hio_get(loop, bindfd);
  701. }
  702. // @client: Resolver -> socket -> hio_get -> hio_set_peeraddr
  703. hio_t* hloop_create_udp_client(hloop_t* loop, const char* host, int port) {
  704. sockaddr_u peeraddr;
  705. memset(&peeraddr, 0, sizeof(peeraddr));
  706. int ret = sockaddr_set_ipport(&peeraddr, host, port);
  707. if (ret != 0) {
  708. //printf("unknown host: %s\n", host);
  709. return NULL;
  710. }
  711. int sockfd = socket(peeraddr.sa.sa_family, SOCK_DGRAM, 0);
  712. if (sockfd < 0) {
  713. perror("socket");
  714. return NULL;
  715. }
  716. hio_t* io = hio_get(loop, sockfd);
  717. assert(io != NULL);
  718. hio_set_peeraddr(io, &peeraddr.sa, sockaddr_len(&peeraddr));
  719. return io;
  720. }
  721. static void sockpair_read_cb(hio_t* io, void* buf, int readbytes) {
  722. hloop_t* loop = io->loop;
  723. hevent_t* pev = NULL;
  724. hevent_t ev;
  725. for (int i = 0; i < readbytes; ++i) {
  726. hmutex_lock(&loop->custom_events_mutex);
  727. if (event_queue_empty(&loop->custom_events)) {
  728. goto unlock;
  729. }
  730. pev = event_queue_front(&loop->custom_events);
  731. if (pev == NULL) {
  732. goto unlock;
  733. }
  734. ev = *pev;
  735. event_queue_pop_front(&loop->custom_events);
  736. // NOTE: unlock before cb, avoid deadlock if hloop_post_event called in cb.
  737. hmutex_unlock(&loop->custom_events_mutex);
  738. if (ev.cb) {
  739. ev.cb(&ev);
  740. }
  741. }
  742. return;
  743. unlock:
  744. hmutex_unlock(&loop->custom_events_mutex);
  745. }
  746. void hloop_post_event(hloop_t* loop, hevent_t* ev) {
  747. char buf = '1';
  748. hmutex_lock(&loop->custom_events_mutex);
  749. if (loop->sockpair[0] <= 0 && loop->sockpair[1] <= 0) {
  750. if (Socketpair(AF_INET, SOCK_STREAM, 0, loop->sockpair) != 0) {
  751. hloge("socketpair error");
  752. goto unlock;
  753. }
  754. hread(loop, loop->sockpair[1], loop->readbuf.base, loop->readbuf.len, sockpair_read_cb);
  755. }
  756. if (loop->custom_events.maxsize == 0) {
  757. event_queue_init(&loop->custom_events, CUSTOM_EVENT_QUEUE_INIT_SIZE);
  758. }
  759. if (ev->loop == NULL) {
  760. ev->loop = loop;
  761. }
  762. if (ev->event_type == 0) {
  763. ev->event_type = HEVENT_TYPE_CUSTOM;
  764. }
  765. if (ev->event_id == 0) {
  766. ev->event_id = ++loop->event_counter;
  767. }
  768. event_queue_push_back(&loop->custom_events, ev);
  769. hwrite(loop, loop->sockpair[0], &buf, 1, NULL);
  770. unlock:
  771. hmutex_unlock(&loop->custom_events_mutex);
  772. }