core.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326
  1. /* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
  2. * Permission is hereby granted, free of charge, to any person obtaining a copy
  3. * of this software and associated documentation files (the "Software"), to
  4. * deal in the Software without restriction, including without limitation the
  5. * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  6. * sell copies of the Software, and to permit persons to whom the Software is
  7. * furnished to do so, subject to the following conditions:
  8. *
  9. * The above copyright notice and this permission notice shall be included in
  10. * all copies or substantial portions of the Software.
  11. *
  12. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  17. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  18. * IN THE SOFTWARE.
  19. */
  20. #include "uv.h"
  21. #include "internal.h"
  22. #include <stddef.h> /* NULL */
  23. #include <stdio.h> /* printf */
  24. #include <stdlib.h>
  25. #include <string.h> /* strerror */
  26. #include <errno.h>
  27. #include <assert.h>
  28. #include <unistd.h>
  29. #include <sys/param.h> /* MAXHOSTNAMELEN on Linux and the BSDs */
  30. #include <sys/types.h>
  31. #include <sys/stat.h>
  32. #include <fcntl.h>
  33. #include <sys/ioctl.h>
  34. #include <sys/socket.h>
  35. #include <sys/un.h>
  36. #include <netinet/in.h>
  37. #include <arpa/inet.h>
  38. #include <limits.h> /* INT_MAX, PATH_MAX, IOV_MAX */
  39. #include <sys/uio.h> /* writev */
  40. #include <sys/resource.h> /* getrusage */
  41. #include <pwd.h>
  42. #ifdef __sun
  43. # include <netdb.h> /* MAXHOSTNAMELEN on Solaris */
  44. # include <sys/filio.h>
  45. # include <sys/types.h>
  46. # include <sys/wait.h>
  47. #endif
  48. #ifdef __APPLE__
  49. # include <mach-o/dyld.h> /* _NSGetExecutablePath */
  50. # include <sys/filio.h>
  51. # if defined(O_CLOEXEC)
  52. # define UV__O_CLOEXEC O_CLOEXEC
  53. # endif
  54. #endif
  55. #if defined(__DragonFly__) || \
  56. defined(__FreeBSD__) || \
  57. defined(__FreeBSD_kernel__)
  58. # include <sys/sysctl.h>
  59. # include <sys/filio.h>
  60. # include <sys/wait.h>
  61. # define UV__O_CLOEXEC O_CLOEXEC
  62. # if defined(__FreeBSD__) && __FreeBSD__ >= 10
  63. # define uv__accept4 accept4
  64. # define UV__SOCK_NONBLOCK SOCK_NONBLOCK
  65. # define UV__SOCK_CLOEXEC SOCK_CLOEXEC
  66. # endif
  67. # if !defined(F_DUP2FD_CLOEXEC) && defined(_F_DUP2FD_CLOEXEC)
  68. # define F_DUP2FD_CLOEXEC _F_DUP2FD_CLOEXEC
  69. # endif
  70. #endif
  71. #if defined(__ANDROID_API__) && __ANDROID_API__ < 21
  72. # include <dlfcn.h> /* for dlsym */
  73. #endif
  74. #if defined(__MVS__)
  75. #include <sys/ioctl.h>
  76. #endif
  77. /* Fallback for the maximum hostname length */
  78. #ifndef MAXHOSTNAMELEN
  79. # define MAXHOSTNAMELEN 256
  80. #endif
  81. static int uv__run_pending(uv_loop_t* loop);
  82. /* Verify that uv_buf_t is ABI-compatible with struct iovec. */
  83. STATIC_ASSERT(sizeof(uv_buf_t) == sizeof(struct iovec));
  84. STATIC_ASSERT(sizeof(&((uv_buf_t*) 0)->base) ==
  85. sizeof(((struct iovec*) 0)->iov_base));
  86. STATIC_ASSERT(sizeof(&((uv_buf_t*) 0)->len) ==
  87. sizeof(((struct iovec*) 0)->iov_len));
  88. STATIC_ASSERT(offsetof(uv_buf_t, base) == offsetof(struct iovec, iov_base));
  89. STATIC_ASSERT(offsetof(uv_buf_t, len) == offsetof(struct iovec, iov_len));
  90. uint64_t uv_hrtime(void) {
  91. return uv__hrtime(UV_CLOCK_PRECISE);
  92. }
  93. void uv_close(uv_handle_t* handle, uv_close_cb close_cb) {
  94. assert(!uv__is_closing(handle));
  95. handle->flags |= UV_CLOSING;
  96. handle->close_cb = close_cb;
  97. switch (handle->type) {
  98. case UV_NAMED_PIPE:
  99. uv__pipe_close((uv_pipe_t*)handle);
  100. break;
  101. case UV_TTY:
  102. uv__stream_close((uv_stream_t*)handle);
  103. break;
  104. case UV_TCP:
  105. uv__tcp_close((uv_tcp_t*)handle);
  106. break;
  107. case UV_UDP:
  108. uv__udp_close((uv_udp_t*)handle);
  109. break;
  110. case UV_PREPARE:
  111. uv__prepare_close((uv_prepare_t*)handle);
  112. break;
  113. case UV_CHECK:
  114. uv__check_close((uv_check_t*)handle);
  115. break;
  116. case UV_IDLE:
  117. uv__idle_close((uv_idle_t*)handle);
  118. break;
  119. case UV_ASYNC:
  120. uv__async_close((uv_async_t*)handle);
  121. break;
  122. case UV_TIMER:
  123. uv__timer_close((uv_timer_t*)handle);
  124. break;
  125. case UV_PROCESS:
  126. uv__process_close((uv_process_t*)handle);
  127. break;
  128. case UV_FS_EVENT:
  129. uv__fs_event_close((uv_fs_event_t*)handle);
  130. break;
  131. case UV_POLL:
  132. uv__poll_close((uv_poll_t*)handle);
  133. break;
  134. case UV_FS_POLL:
  135. uv__fs_poll_close((uv_fs_poll_t*)handle);
  136. break;
  137. case UV_SIGNAL:
  138. uv__signal_close((uv_signal_t*) handle);
  139. /* Signal handles may not be closed immediately. The signal code will */
  140. /* itself close uv__make_close_pending whenever appropriate. */
  141. return;
  142. default:
  143. assert(0);
  144. }
  145. uv__make_close_pending(handle);
  146. }
  147. int uv__socket_sockopt(uv_handle_t* handle, int optname, int* value) {
  148. int r;
  149. int fd;
  150. socklen_t len;
  151. if (handle == NULL || value == NULL)
  152. return -EINVAL;
  153. if (handle->type == UV_TCP || handle->type == UV_NAMED_PIPE)
  154. fd = uv__stream_fd((uv_stream_t*) handle);
  155. else if (handle->type == UV_UDP)
  156. fd = ((uv_udp_t *) handle)->io_watcher.fd;
  157. else
  158. return -ENOTSUP;
  159. len = sizeof(*value);
  160. if (*value == 0)
  161. r = getsockopt(fd, SOL_SOCKET, optname, value, &len);
  162. else
  163. r = setsockopt(fd, SOL_SOCKET, optname, (const void*) value, len);
  164. if (r < 0)
  165. return -errno;
  166. return 0;
  167. }
  168. void uv__make_close_pending(uv_handle_t* handle) {
  169. assert(handle->flags & UV_CLOSING);
  170. assert(!(handle->flags & UV_CLOSED));
  171. handle->next_closing = handle->loop->closing_handles;
  172. handle->loop->closing_handles = handle;
  173. }
  174. int uv__getiovmax(void) {
  175. #if defined(IOV_MAX)
  176. return IOV_MAX;
  177. #elif defined(_SC_IOV_MAX)
  178. static int iovmax = -1;
  179. if (iovmax == -1) {
  180. iovmax = sysconf(_SC_IOV_MAX);
  181. /* On some embedded devices (arm-linux-uclibc based ip camera),
  182. * sysconf(_SC_IOV_MAX) can not get the correct value. The return
  183. * value is -1 and the errno is EINPROGRESS. Degrade the value to 1.
  184. */
  185. if (iovmax == -1) iovmax = 1;
  186. }
  187. return iovmax;
  188. #else
  189. return 1024;
  190. #endif
  191. }
  192. static void uv__finish_close(uv_handle_t* handle) {
  193. /* Note: while the handle is in the UV_CLOSING state now, it's still possible
  194. * for it to be active in the sense that uv__is_active() returns true.
  195. * A good example is when the user calls uv_shutdown(), immediately followed
  196. * by uv_close(). The handle is considered active at this point because the
  197. * completion of the shutdown req is still pending.
  198. */
  199. assert(handle->flags & UV_CLOSING);
  200. assert(!(handle->flags & UV_CLOSED));
  201. handle->flags |= UV_CLOSED;
  202. switch (handle->type) {
  203. case UV_PREPARE:
  204. case UV_CHECK:
  205. case UV_IDLE:
  206. case UV_ASYNC:
  207. case UV_TIMER:
  208. case UV_PROCESS:
  209. case UV_FS_EVENT:
  210. case UV_FS_POLL:
  211. case UV_POLL:
  212. case UV_SIGNAL:
  213. break;
  214. case UV_NAMED_PIPE:
  215. case UV_TCP:
  216. case UV_TTY:
  217. uv__stream_destroy((uv_stream_t*)handle);
  218. break;
  219. case UV_UDP:
  220. uv__udp_finish_close((uv_udp_t*)handle);
  221. break;
  222. default:
  223. assert(0);
  224. break;
  225. }
  226. uv__handle_unref(handle);
  227. QUEUE_REMOVE(&handle->handle_queue);
  228. if (handle->close_cb) {
  229. handle->close_cb(handle);
  230. }
  231. }
  232. static void uv__run_closing_handles(uv_loop_t* loop) {
  233. uv_handle_t* p;
  234. uv_handle_t* q;
  235. p = loop->closing_handles;
  236. loop->closing_handles = NULL;
  237. while (p) {
  238. q = p->next_closing;
  239. uv__finish_close(p);
  240. p = q;
  241. }
  242. }
  243. int uv_is_closing(const uv_handle_t* handle) {
  244. return uv__is_closing(handle);
  245. }
  246. int uv_backend_fd(const uv_loop_t* loop) {
  247. return loop->backend_fd;
  248. }
  249. int uv_backend_timeout(const uv_loop_t* loop) {
  250. if (loop->stop_flag != 0)
  251. return 0;
  252. if (!uv__has_active_handles(loop) && !uv__has_active_reqs(loop))
  253. return 0;
  254. if (!QUEUE_EMPTY(&loop->idle_handles))
  255. return 0;
  256. if (!QUEUE_EMPTY(&loop->pending_queue))
  257. return 0;
  258. if (loop->closing_handles)
  259. return 0;
  260. return uv__next_timeout(loop);
  261. }
  262. static int uv__loop_alive(const uv_loop_t* loop) {
  263. return uv__has_active_handles(loop) ||
  264. uv__has_active_reqs(loop) ||
  265. loop->closing_handles != NULL;
  266. }
  267. int uv_loop_alive(const uv_loop_t* loop) {
  268. return uv__loop_alive(loop);
  269. }
  270. int uv_run(uv_loop_t* loop, uv_run_mode mode) {
  271. int timeout;
  272. int r;
  273. int ran_pending;
  274. r = uv__loop_alive(loop);
  275. if (!r)
  276. uv__update_time(loop);
  277. while (r != 0 && loop->stop_flag == 0) {
  278. uv__update_time(loop);
  279. uv__run_timers(loop);
  280. ran_pending = uv__run_pending(loop);
  281. uv__run_idle(loop);
  282. uv__run_prepare(loop);
  283. timeout = 0;
  284. if ((mode == UV_RUN_ONCE && !ran_pending) || mode == UV_RUN_DEFAULT)
  285. timeout = uv_backend_timeout(loop);
  286. uv__io_poll(loop, timeout);
  287. uv__run_check(loop);
  288. uv__run_closing_handles(loop);
  289. if (mode == UV_RUN_ONCE) {
  290. /* UV_RUN_ONCE implies forward progress: at least one callback must have
  291. * been invoked when it returns. uv__io_poll() can return without doing
  292. * I/O (meaning: no callbacks) when its timeout expires - which means we
  293. * have pending timers that satisfy the forward progress constraint.
  294. *
  295. * UV_RUN_NOWAIT makes no guarantees about progress so it's omitted from
  296. * the check.
  297. */
  298. uv__update_time(loop);
  299. uv__run_timers(loop);
  300. }
  301. r = uv__loop_alive(loop);
  302. if (mode == UV_RUN_ONCE || mode == UV_RUN_NOWAIT)
  303. break;
  304. }
  305. /* The if statement lets gcc compile it to a conditional store. Avoids
  306. * dirtying a cache line.
  307. */
  308. if (loop->stop_flag != 0)
  309. loop->stop_flag = 0;
  310. return r;
  311. }
  312. void uv_update_time(uv_loop_t* loop) {
  313. uv__update_time(loop);
  314. }
  315. int uv_is_active(const uv_handle_t* handle) {
  316. return uv__is_active(handle);
  317. }
  318. /* Open a socket in non-blocking close-on-exec mode, atomically if possible. */
  319. int uv__socket(int domain, int type, int protocol) {
  320. int sockfd;
  321. int err;
  322. #if defined(SOCK_NONBLOCK) && defined(SOCK_CLOEXEC)
  323. sockfd = socket(domain, type | SOCK_NONBLOCK | SOCK_CLOEXEC, protocol);
  324. if (sockfd != -1)
  325. return sockfd;
  326. if (errno != EINVAL)
  327. return -errno;
  328. #endif
  329. sockfd = socket(domain, type, protocol);
  330. if (sockfd == -1)
  331. return -errno;
  332. err = uv__nonblock(sockfd, 1);
  333. if (err == 0)
  334. err = uv__cloexec(sockfd, 1);
  335. if (err) {
  336. uv__close(sockfd);
  337. return err;
  338. }
  339. #if defined(SO_NOSIGPIPE)
  340. {
  341. int on = 1;
  342. setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, &on, sizeof(on));
  343. }
  344. #endif
  345. return sockfd;
  346. }
  347. /* get a file pointer to a file in read-only and close-on-exec mode */
  348. FILE* uv__open_file(const char* path) {
  349. int fd;
  350. FILE* fp;
  351. fd = uv__open_cloexec(path, O_RDONLY);
  352. if (fd < 0)
  353. return NULL;
  354. fp = fdopen(fd, "r");
  355. if (fp == NULL)
  356. uv__close(fd);
  357. return fp;
  358. }
  359. int uv__accept(int sockfd) {
  360. int peerfd;
  361. int err;
  362. assert(sockfd >= 0);
  363. while (1) {
  364. #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD__ >= 10)
  365. static int no_accept4;
  366. if (no_accept4)
  367. goto skip;
  368. peerfd = uv__accept4(sockfd,
  369. NULL,
  370. NULL,
  371. UV__SOCK_NONBLOCK|UV__SOCK_CLOEXEC);
  372. if (peerfd != -1)
  373. return peerfd;
  374. if (errno == EINTR)
  375. continue;
  376. if (errno != ENOSYS)
  377. return -errno;
  378. no_accept4 = 1;
  379. skip:
  380. #endif
  381. peerfd = accept(sockfd, NULL, NULL);
  382. if (peerfd == -1) {
  383. if (errno == EINTR)
  384. continue;
  385. return -errno;
  386. }
  387. err = uv__cloexec(peerfd, 1);
  388. if (err == 0)
  389. err = uv__nonblock(peerfd, 1);
  390. if (err) {
  391. uv__close(peerfd);
  392. return err;
  393. }
  394. return peerfd;
  395. }
  396. }
  397. int uv__close_nocheckstdio(int fd) {
  398. int saved_errno;
  399. int rc;
  400. assert(fd > -1); /* Catch uninitialized io_watcher.fd bugs. */
  401. saved_errno = errno;
  402. rc = close(fd);
  403. if (rc == -1) {
  404. rc = -errno;
  405. if (rc == -EINTR || rc == -EINPROGRESS)
  406. rc = 0; /* The close is in progress, not an error. */
  407. errno = saved_errno;
  408. }
  409. return rc;
  410. }
  411. int uv__close(int fd) {
  412. assert(fd > STDERR_FILENO); /* Catch stdio close bugs. */
  413. #if defined(__MVS__)
  414. epoll_file_close(fd);
  415. #endif
  416. return uv__close_nocheckstdio(fd);
  417. }
  418. int uv__nonblock_ioctl(int fd, int set) {
  419. int r;
  420. do
  421. r = ioctl(fd, FIONBIO, &set);
  422. while (r == -1 && errno == EINTR);
  423. if (r)
  424. return -errno;
  425. return 0;
  426. }
  427. #if !defined(__CYGWIN__) && !defined(__MSYS__)
  428. int uv__cloexec_ioctl(int fd, int set) {
  429. int r;
  430. do
  431. r = ioctl(fd, set ? FIOCLEX : FIONCLEX);
  432. while (r == -1 && errno == EINTR);
  433. if (r)
  434. return -errno;
  435. return 0;
  436. }
  437. #endif
  438. int uv__nonblock_fcntl(int fd, int set) {
  439. int flags;
  440. int r;
  441. do
  442. r = fcntl(fd, F_GETFL);
  443. while (r == -1 && errno == EINTR);
  444. if (r == -1)
  445. return -errno;
  446. /* Bail out now if already set/clear. */
  447. if (!!(r & O_NONBLOCK) == !!set)
  448. return 0;
  449. if (set)
  450. flags = r | O_NONBLOCK;
  451. else
  452. flags = r & ~O_NONBLOCK;
  453. do
  454. r = fcntl(fd, F_SETFL, flags);
  455. while (r == -1 && errno == EINTR);
  456. if (r)
  457. return -errno;
  458. return 0;
  459. }
  460. int uv__cloexec_fcntl(int fd, int set) {
  461. int flags;
  462. int r;
  463. do
  464. r = fcntl(fd, F_GETFD);
  465. while (r == -1 && errno == EINTR);
  466. if (r == -1)
  467. return -errno;
  468. /* Bail out now if already set/clear. */
  469. if (!!(r & FD_CLOEXEC) == !!set)
  470. return 0;
  471. if (set)
  472. flags = r | FD_CLOEXEC;
  473. else
  474. flags = r & ~FD_CLOEXEC;
  475. do
  476. r = fcntl(fd, F_SETFD, flags);
  477. while (r == -1 && errno == EINTR);
  478. if (r)
  479. return -errno;
  480. return 0;
  481. }
  482. /* This function is not execve-safe, there is a race window
  483. * between the call to dup() and fcntl(FD_CLOEXEC).
  484. */
  485. int uv__dup(int fd) {
  486. int err;
  487. fd = dup(fd);
  488. if (fd == -1)
  489. return -errno;
  490. err = uv__cloexec(fd, 1);
  491. if (err) {
  492. uv__close(fd);
  493. return err;
  494. }
  495. return fd;
  496. }
  497. ssize_t uv__recvmsg(int fd, struct msghdr* msg, int flags) {
  498. struct cmsghdr* cmsg;
  499. ssize_t rc;
  500. int* pfd;
  501. int* end;
  502. #if defined(__linux__)
  503. static int no_msg_cmsg_cloexec;
  504. if (no_msg_cmsg_cloexec == 0) {
  505. rc = recvmsg(fd, msg, flags | 0x40000000); /* MSG_CMSG_CLOEXEC */
  506. if (rc != -1)
  507. return rc;
  508. if (errno != EINVAL)
  509. return -errno;
  510. rc = recvmsg(fd, msg, flags);
  511. if (rc == -1)
  512. return -errno;
  513. no_msg_cmsg_cloexec = 1;
  514. } else {
  515. rc = recvmsg(fd, msg, flags);
  516. }
  517. #else
  518. rc = recvmsg(fd, msg, flags);
  519. #endif
  520. if (rc == -1)
  521. return -errno;
  522. if (msg->msg_controllen == 0)
  523. return rc;
  524. for (cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL; cmsg = CMSG_NXTHDR(msg, cmsg))
  525. if (cmsg->cmsg_type == SCM_RIGHTS)
  526. for (pfd = (int*) CMSG_DATA(cmsg),
  527. end = (int*) ((char*) cmsg + cmsg->cmsg_len);
  528. pfd < end;
  529. pfd += 1)
  530. uv__cloexec(*pfd, 1);
  531. return rc;
  532. }
  533. int uv_cwd(char* buffer, size_t* size) {
  534. if (buffer == NULL || size == NULL)
  535. return -EINVAL;
  536. if (getcwd(buffer, *size) == NULL)
  537. return -errno;
  538. *size = strlen(buffer);
  539. if (*size > 1 && buffer[*size - 1] == '/') {
  540. buffer[*size-1] = '\0';
  541. (*size)--;
  542. }
  543. return 0;
  544. }
  545. int uv_chdir(const char* dir) {
  546. if (chdir(dir))
  547. return -errno;
  548. return 0;
  549. }
  550. void uv_disable_stdio_inheritance(void) {
  551. int fd;
  552. /* Set the CLOEXEC flag on all open descriptors. Unconditionally try the
  553. * first 16 file descriptors. After that, bail out after the first error.
  554. */
  555. for (fd = 0; ; fd++)
  556. if (uv__cloexec(fd, 1) && fd > 15)
  557. break;
  558. }
  559. int uv_fileno(const uv_handle_t* handle, uv_os_fd_t* fd) {
  560. int fd_out;
  561. switch (handle->type) {
  562. case UV_TCP:
  563. case UV_NAMED_PIPE:
  564. case UV_TTY:
  565. fd_out = uv__stream_fd((uv_stream_t*) handle);
  566. break;
  567. case UV_UDP:
  568. fd_out = ((uv_udp_t *) handle)->io_watcher.fd;
  569. break;
  570. case UV_POLL:
  571. fd_out = ((uv_poll_t *) handle)->io_watcher.fd;
  572. break;
  573. default:
  574. return -EINVAL;
  575. }
  576. if (uv__is_closing(handle) || fd_out == -1)
  577. return -EBADF;
  578. *fd = fd_out;
  579. return 0;
  580. }
  581. static int uv__run_pending(uv_loop_t* loop) {
  582. QUEUE* q;
  583. QUEUE pq;
  584. uv__io_t* w;
  585. if (QUEUE_EMPTY(&loop->pending_queue))
  586. return 0;
  587. QUEUE_MOVE(&loop->pending_queue, &pq);
  588. while (!QUEUE_EMPTY(&pq)) {
  589. q = QUEUE_HEAD(&pq);
  590. QUEUE_REMOVE(q);
  591. QUEUE_INIT(q);
  592. w = QUEUE_DATA(q, uv__io_t, pending_queue);
  593. w->cb(loop, w, POLLOUT);
  594. }
  595. return 1;
  596. }
  597. static unsigned int next_power_of_two(unsigned int val) {
  598. val -= 1;
  599. val |= val >> 1;
  600. val |= val >> 2;
  601. val |= val >> 4;
  602. val |= val >> 8;
  603. val |= val >> 16;
  604. val += 1;
  605. return val;
  606. }
  607. static void maybe_resize(uv_loop_t* loop, unsigned int len) {
  608. uv__io_t** watchers;
  609. void* fake_watcher_list;
  610. void* fake_watcher_count;
  611. unsigned int nwatchers;
  612. unsigned int i;
  613. if (len <= loop->nwatchers)
  614. return;
  615. /* Preserve fake watcher list and count at the end of the watchers */
  616. if (loop->watchers != NULL) {
  617. fake_watcher_list = loop->watchers[loop->nwatchers];
  618. fake_watcher_count = loop->watchers[loop->nwatchers + 1];
  619. } else {
  620. fake_watcher_list = NULL;
  621. fake_watcher_count = NULL;
  622. }
  623. nwatchers = next_power_of_two(len + 2) - 2;
  624. watchers = uv__realloc(loop->watchers,
  625. (nwatchers + 2) * sizeof(loop->watchers[0]));
  626. if (watchers == NULL)
  627. abort();
  628. for (i = loop->nwatchers; i < nwatchers; i++)
  629. watchers[i] = NULL;
  630. watchers[nwatchers] = fake_watcher_list;
  631. watchers[nwatchers + 1] = fake_watcher_count;
  632. loop->watchers = watchers;
  633. loop->nwatchers = nwatchers;
  634. }
  635. void uv__io_init(uv__io_t* w, uv__io_cb cb, int fd) {
  636. assert(cb != NULL);
  637. assert(fd >= -1);
  638. QUEUE_INIT(&w->pending_queue);
  639. QUEUE_INIT(&w->watcher_queue);
  640. w->cb = cb;
  641. w->fd = fd;
  642. w->events = 0;
  643. w->pevents = 0;
  644. #if defined(UV_HAVE_KQUEUE)
  645. w->rcount = 0;
  646. w->wcount = 0;
  647. #endif /* defined(UV_HAVE_KQUEUE) */
  648. }
  649. void uv__io_start(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
  650. assert(0 == (events & ~(POLLIN | POLLOUT | UV__POLLRDHUP)));
  651. assert(0 != events);
  652. assert(w->fd >= 0);
  653. assert(w->fd < INT_MAX);
  654. w->pevents |= events;
  655. maybe_resize(loop, w->fd + 1);
  656. #if !defined(__sun)
  657. /* The event ports backend needs to rearm all file descriptors on each and
  658. * every tick of the event loop but the other backends allow us to
  659. * short-circuit here if the event mask is unchanged.
  660. */
  661. if (w->events == w->pevents)
  662. return;
  663. #endif
  664. if (QUEUE_EMPTY(&w->watcher_queue))
  665. QUEUE_INSERT_TAIL(&loop->watcher_queue, &w->watcher_queue);
  666. if (loop->watchers[w->fd] == NULL) {
  667. loop->watchers[w->fd] = w;
  668. loop->nfds++;
  669. }
  670. }
  671. void uv__io_stop(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
  672. assert(0 == (events & ~(POLLIN | POLLOUT | UV__POLLRDHUP)));
  673. assert(0 != events);
  674. if (w->fd == -1)
  675. return;
  676. assert(w->fd >= 0);
  677. /* Happens when uv__io_stop() is called on a handle that was never started. */
  678. if ((unsigned) w->fd >= loop->nwatchers)
  679. return;
  680. w->pevents &= ~events;
  681. if (w->pevents == 0) {
  682. QUEUE_REMOVE(&w->watcher_queue);
  683. QUEUE_INIT(&w->watcher_queue);
  684. if (loop->watchers[w->fd] != NULL) {
  685. assert(loop->watchers[w->fd] == w);
  686. assert(loop->nfds > 0);
  687. loop->watchers[w->fd] = NULL;
  688. loop->nfds--;
  689. w->events = 0;
  690. }
  691. }
  692. else if (QUEUE_EMPTY(&w->watcher_queue))
  693. QUEUE_INSERT_TAIL(&loop->watcher_queue, &w->watcher_queue);
  694. }
  695. void uv__io_close(uv_loop_t* loop, uv__io_t* w) {
  696. uv__io_stop(loop, w, POLLIN | POLLOUT | UV__POLLRDHUP);
  697. QUEUE_REMOVE(&w->pending_queue);
  698. /* Remove stale events for this file descriptor */
  699. uv__platform_invalidate_fd(loop, w->fd);
  700. }
  701. void uv__io_feed(uv_loop_t* loop, uv__io_t* w) {
  702. if (QUEUE_EMPTY(&w->pending_queue))
  703. QUEUE_INSERT_TAIL(&loop->pending_queue, &w->pending_queue);
  704. }
  705. int uv__io_active(const uv__io_t* w, unsigned int events) {
  706. assert(0 == (events & ~(POLLIN | POLLOUT | UV__POLLRDHUP)));
  707. assert(0 != events);
  708. return 0 != (w->pevents & events);
  709. }
  710. int uv_getrusage(uv_rusage_t* rusage) {
  711. struct rusage usage;
  712. if (getrusage(RUSAGE_SELF, &usage))
  713. return -errno;
  714. rusage->ru_utime.tv_sec = usage.ru_utime.tv_sec;
  715. rusage->ru_utime.tv_usec = usage.ru_utime.tv_usec;
  716. rusage->ru_stime.tv_sec = usage.ru_stime.tv_sec;
  717. rusage->ru_stime.tv_usec = usage.ru_stime.tv_usec;
  718. #if !defined(__MVS__)
  719. rusage->ru_maxrss = usage.ru_maxrss;
  720. rusage->ru_ixrss = usage.ru_ixrss;
  721. rusage->ru_idrss = usage.ru_idrss;
  722. rusage->ru_isrss = usage.ru_isrss;
  723. rusage->ru_minflt = usage.ru_minflt;
  724. rusage->ru_majflt = usage.ru_majflt;
  725. rusage->ru_nswap = usage.ru_nswap;
  726. rusage->ru_inblock = usage.ru_inblock;
  727. rusage->ru_oublock = usage.ru_oublock;
  728. rusage->ru_msgsnd = usage.ru_msgsnd;
  729. rusage->ru_msgrcv = usage.ru_msgrcv;
  730. rusage->ru_nsignals = usage.ru_nsignals;
  731. rusage->ru_nvcsw = usage.ru_nvcsw;
  732. rusage->ru_nivcsw = usage.ru_nivcsw;
  733. #endif
  734. return 0;
  735. }
  736. int uv__open_cloexec(const char* path, int flags) {
  737. int err;
  738. int fd;
  739. #if defined(UV__O_CLOEXEC)
  740. static int no_cloexec;
  741. if (!no_cloexec) {
  742. fd = open(path, flags | UV__O_CLOEXEC);
  743. if (fd != -1)
  744. return fd;
  745. if (errno != EINVAL)
  746. return -errno;
  747. /* O_CLOEXEC not supported. */
  748. no_cloexec = 1;
  749. }
  750. #endif
  751. fd = open(path, flags);
  752. if (fd == -1)
  753. return -errno;
  754. err = uv__cloexec(fd, 1);
  755. if (err) {
  756. uv__close(fd);
  757. return err;
  758. }
  759. return fd;
  760. }
  761. int uv__dup2_cloexec(int oldfd, int newfd) {
  762. int r;
  763. #if defined(__FreeBSD__) && __FreeBSD__ >= 10
  764. r = dup3(oldfd, newfd, O_CLOEXEC);
  765. if (r == -1)
  766. return -errno;
  767. return r;
  768. #elif defined(__FreeBSD__) && defined(F_DUP2FD_CLOEXEC)
  769. r = fcntl(oldfd, F_DUP2FD_CLOEXEC, newfd);
  770. if (r != -1)
  771. return r;
  772. if (errno != EINVAL)
  773. return -errno;
  774. /* Fall through. */
  775. #elif defined(__linux__)
  776. static int no_dup3;
  777. if (!no_dup3) {
  778. do
  779. r = uv__dup3(oldfd, newfd, UV__O_CLOEXEC);
  780. while (r == -1 && errno == EBUSY);
  781. if (r != -1)
  782. return r;
  783. if (errno != ENOSYS)
  784. return -errno;
  785. /* Fall through. */
  786. no_dup3 = 1;
  787. }
  788. #endif
  789. {
  790. int err;
  791. do
  792. r = dup2(oldfd, newfd);
  793. #if defined(__linux__)
  794. while (r == -1 && errno == EBUSY);
  795. #else
  796. while (0); /* Never retry. */
  797. #endif
  798. if (r == -1)
  799. return -errno;
  800. err = uv__cloexec(newfd, 1);
  801. if (err) {
  802. uv__close(newfd);
  803. return err;
  804. }
  805. return r;
  806. }
  807. }
  808. int uv_os_homedir(char* buffer, size_t* size) {
  809. uv_passwd_t pwd;
  810. char* buf;
  811. size_t len;
  812. int r;
  813. if (buffer == NULL || size == NULL || *size == 0)
  814. return -EINVAL;
  815. /* Check if the HOME environment variable is set first */
  816. buf = getenv("HOME");
  817. if (buf != NULL) {
  818. len = strlen(buf);
  819. if (len >= *size) {
  820. *size = len + 1;
  821. return -ENOBUFS;
  822. }
  823. memcpy(buffer, buf, len + 1);
  824. *size = len;
  825. return 0;
  826. }
  827. /* HOME is not set, so call uv__getpwuid_r() */
  828. r = uv__getpwuid_r(&pwd);
  829. if (r != 0) {
  830. return r;
  831. }
  832. len = strlen(pwd.homedir);
  833. if (len >= *size) {
  834. *size = len + 1;
  835. uv_os_free_passwd(&pwd);
  836. return -ENOBUFS;
  837. }
  838. memcpy(buffer, pwd.homedir, len + 1);
  839. *size = len;
  840. uv_os_free_passwd(&pwd);
  841. return 0;
  842. }
  843. int uv_os_tmpdir(char* buffer, size_t* size) {
  844. const char* buf;
  845. size_t len;
  846. if (buffer == NULL || size == NULL || *size == 0)
  847. return -EINVAL;
  848. #define CHECK_ENV_VAR(name) \
  849. do { \
  850. buf = getenv(name); \
  851. if (buf != NULL) \
  852. goto return_buffer; \
  853. } \
  854. while (0)
  855. /* Check the TMPDIR, TMP, TEMP, and TEMPDIR environment variables in order */
  856. CHECK_ENV_VAR("TMPDIR");
  857. CHECK_ENV_VAR("TMP");
  858. CHECK_ENV_VAR("TEMP");
  859. CHECK_ENV_VAR("TEMPDIR");
  860. #undef CHECK_ENV_VAR
  861. /* No temp environment variables defined */
  862. #if defined(__ANDROID__)
  863. buf = "/data/local/tmp";
  864. #else
  865. buf = "/tmp";
  866. #endif
  867. return_buffer:
  868. len = strlen(buf);
  869. if (len >= *size) {
  870. *size = len + 1;
  871. return -ENOBUFS;
  872. }
  873. /* The returned directory should not have a trailing slash. */
  874. if (len > 1 && buf[len - 1] == '/') {
  875. len--;
  876. }
  877. memcpy(buffer, buf, len + 1);
  878. buffer[len] = '\0';
  879. *size = len;
  880. return 0;
  881. }
  882. int uv__getpwuid_r(uv_passwd_t* pwd) {
  883. struct passwd pw;
  884. struct passwd* result;
  885. char* buf;
  886. uid_t uid;
  887. size_t bufsize;
  888. size_t name_size;
  889. size_t homedir_size;
  890. size_t shell_size;
  891. long initsize;
  892. int r;
  893. #if defined(__ANDROID_API__) && __ANDROID_API__ < 21
  894. int (*getpwuid_r)(uid_t, struct passwd*, char*, size_t, struct passwd**);
  895. getpwuid_r = dlsym(RTLD_DEFAULT, "getpwuid_r");
  896. if (getpwuid_r == NULL)
  897. return -ENOSYS;
  898. #endif
  899. if (pwd == NULL)
  900. return -EINVAL;
  901. initsize = sysconf(_SC_GETPW_R_SIZE_MAX);
  902. if (initsize <= 0)
  903. bufsize = 4096;
  904. else
  905. bufsize = (size_t) initsize;
  906. uid = geteuid();
  907. buf = NULL;
  908. for (;;) {
  909. uv__free(buf);
  910. buf = uv__malloc(bufsize);
  911. if (buf == NULL)
  912. return -ENOMEM;
  913. r = getpwuid_r(uid, &pw, buf, bufsize, &result);
  914. if (r != ERANGE)
  915. break;
  916. bufsize *= 2;
  917. }
  918. if (r != 0) {
  919. uv__free(buf);
  920. return -r;
  921. }
  922. if (result == NULL) {
  923. uv__free(buf);
  924. return -ENOENT;
  925. }
  926. /* Allocate memory for the username, shell, and home directory */
  927. name_size = strlen(pw.pw_name) + 1;
  928. homedir_size = strlen(pw.pw_dir) + 1;
  929. shell_size = strlen(pw.pw_shell) + 1;
  930. pwd->username = uv__malloc(name_size + homedir_size + shell_size);
  931. if (pwd->username == NULL) {
  932. uv__free(buf);
  933. return -ENOMEM;
  934. }
  935. /* Copy the username */
  936. memcpy(pwd->username, pw.pw_name, name_size);
  937. /* Copy the home directory */
  938. pwd->homedir = pwd->username + name_size;
  939. memcpy(pwd->homedir, pw.pw_dir, homedir_size);
  940. /* Copy the shell */
  941. pwd->shell = pwd->homedir + homedir_size;
  942. memcpy(pwd->shell, pw.pw_shell, shell_size);
  943. /* Copy the uid and gid */
  944. pwd->uid = pw.pw_uid;
  945. pwd->gid = pw.pw_gid;
  946. uv__free(buf);
  947. return 0;
  948. }
  949. void uv_os_free_passwd(uv_passwd_t* pwd) {
  950. if (pwd == NULL)
  951. return;
  952. /*
  953. The memory for name, shell, and homedir are allocated in a single
  954. uv__malloc() call. The base of the pointer is stored in pwd->username, so
  955. that is the field that needs to be freed.
  956. */
  957. uv__free(pwd->username);
  958. pwd->username = NULL;
  959. pwd->shell = NULL;
  960. pwd->homedir = NULL;
  961. }
  962. int uv_os_get_passwd(uv_passwd_t* pwd) {
  963. return uv__getpwuid_r(pwd);
  964. }
  965. int uv_translate_sys_error(int sys_errno) {
  966. /* If < 0 then it's already a libuv error. */
  967. return sys_errno <= 0 ? sys_errno : -sys_errno;
  968. }
  969. int uv_os_getenv(const char* name, char* buffer, size_t* size) {
  970. char* var;
  971. size_t len;
  972. if (name == NULL || buffer == NULL || size == NULL || *size == 0)
  973. return -EINVAL;
  974. var = getenv(name);
  975. if (var == NULL)
  976. return -ENOENT;
  977. len = strlen(var);
  978. if (len >= *size) {
  979. *size = len + 1;
  980. return -ENOBUFS;
  981. }
  982. memcpy(buffer, var, len + 1);
  983. *size = len;
  984. return 0;
  985. }
  986. int uv_os_setenv(const char* name, const char* value) {
  987. if (name == NULL || value == NULL)
  988. return -EINVAL;
  989. if (setenv(name, value, 1) != 0)
  990. return -errno;
  991. return 0;
  992. }
  993. int uv_os_unsetenv(const char* name) {
  994. if (unsetenv(name) != 0)
  995. return -errno;
  996. return 0;
  997. }
  998. int uv_os_gethostname(char* buffer, size_t* size) {
  999. /*
  1000. On some platforms, if the input buffer is not large enough, gethostname()
  1001. succeeds, but truncates the result. libuv can detect this and return ENOBUFS
  1002. instead by creating a large enough buffer and comparing the hostname length
  1003. to the size input.
  1004. */
  1005. char buf[MAXHOSTNAMELEN + 1];
  1006. size_t len;
  1007. if (buffer == NULL || size == NULL || *size == 0)
  1008. return -EINVAL;
  1009. if (gethostname(buf, sizeof(buf)) != 0)
  1010. return -errno;
  1011. buf[sizeof(buf) - 1] = '\0'; /* Null terminate, just to be safe. */
  1012. len = strlen(buf);
  1013. if (len >= *size) {
  1014. *size = len + 1;
  1015. return -ENOBUFS;
  1016. }
  1017. memcpy(buffer, buf, len + 1);
  1018. *size = len;
  1019. return 0;
  1020. }