hloop.c 28 KB

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