hloop.c 27 KB

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