1
0

hloop.c 23 KB

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