Stream.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, sin-ack <sin-ack@protonmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "Stream.h"
  8. #include <LibCore/System.h>
  9. #include <fcntl.h>
  10. #include <netdb.h>
  11. #include <poll.h>
  12. #include <sys/ioctl.h>
  13. #include <sys/socket.h>
  14. #include <sys/types.h>
  15. #include <unistd.h>
  16. #ifdef __serenity__
  17. # include <serenity.h>
  18. #endif
  19. #ifdef __FreeBSD__
  20. # include <sys/ucred.h>
  21. #endif
  22. namespace Core::Stream {
  23. bool Stream::read_or_error(Bytes buffer)
  24. {
  25. VERIFY(buffer.size());
  26. size_t nread = 0;
  27. do {
  28. if (is_eof())
  29. return false;
  30. auto result = read(buffer.slice(nread));
  31. if (result.is_error()) {
  32. if (result.error().is_errno() && result.error().code() == EINTR) {
  33. continue;
  34. }
  35. return false;
  36. }
  37. nread += result.value().size();
  38. } while (nread < buffer.size());
  39. return true;
  40. }
  41. ErrorOr<ByteBuffer> Stream::read_all(size_t block_size)
  42. {
  43. return read_all_impl(block_size);
  44. }
  45. ErrorOr<ByteBuffer> Stream::read_all_impl(size_t block_size, size_t expected_file_size)
  46. {
  47. ByteBuffer data;
  48. data.ensure_capacity(expected_file_size);
  49. size_t total_read = 0;
  50. Bytes buffer;
  51. while (!is_eof()) {
  52. if (buffer.is_empty()) {
  53. buffer = TRY(data.get_bytes_for_writing(block_size));
  54. }
  55. auto nread = TRY(read(buffer)).size();
  56. total_read += nread;
  57. buffer = buffer.slice(nread);
  58. }
  59. data.resize(total_read);
  60. return data;
  61. }
  62. bool Stream::write_or_error(ReadonlyBytes buffer)
  63. {
  64. VERIFY(buffer.size());
  65. size_t nwritten = 0;
  66. do {
  67. auto result = write(buffer.slice(nwritten));
  68. if (result.is_error()) {
  69. if (result.error().is_errno() && result.error().code() == EINTR) {
  70. continue;
  71. }
  72. return false;
  73. }
  74. nwritten += result.value();
  75. } while (nwritten < buffer.size());
  76. return true;
  77. }
  78. ErrorOr<off_t> SeekableStream::tell() const
  79. {
  80. // Seek with 0 and SEEK_CUR does not modify anything despite the const_cast,
  81. // so it's safe to do this.
  82. return const_cast<SeekableStream*>(this)->seek(0, SeekMode::FromCurrentPosition);
  83. }
  84. ErrorOr<off_t> SeekableStream::size()
  85. {
  86. auto original_position = TRY(tell());
  87. auto seek_result = seek(0, SeekMode::FromEndPosition);
  88. if (seek_result.is_error()) {
  89. // Let's try to restore the original position, just in case.
  90. auto restore_result = seek(original_position, SeekMode::SetPosition);
  91. if (restore_result.is_error()) {
  92. dbgln("Core::SeekableStream::size: Couldn't restore initial position, stream might have incorrect position now!");
  93. }
  94. return seek_result.release_error();
  95. }
  96. TRY(seek(original_position, SeekMode::SetPosition));
  97. return seek_result.value();
  98. }
  99. ErrorOr<NonnullOwnPtr<File>> File::open(StringView filename, OpenMode mode, mode_t permissions)
  100. {
  101. auto file = TRY(adopt_nonnull_own_or_enomem(new (nothrow) File(mode)));
  102. TRY(file->open_path(filename, permissions));
  103. return file;
  104. }
  105. ErrorOr<NonnullOwnPtr<File>> File::adopt_fd(int fd, OpenMode mode)
  106. {
  107. if (fd < 0) {
  108. return Error::from_errno(EBADF);
  109. }
  110. if (!has_any_flag(mode, OpenMode::ReadWrite)) {
  111. dbgln("Core::File::adopt_fd: Attempting to adopt a file with neither Read nor Write specified in mode");
  112. return Error::from_errno(EINVAL);
  113. }
  114. auto file = TRY(adopt_nonnull_own_or_enomem(new (nothrow) File(mode)));
  115. file->m_fd = fd;
  116. return file;
  117. }
  118. bool File::exists(StringView filename)
  119. {
  120. return !Core::System::stat(filename).is_error();
  121. }
  122. ErrorOr<NonnullOwnPtr<File>> File::open_file_or_standard_stream(StringView filename, OpenMode mode)
  123. {
  124. if (!filename.is_empty() && filename != "-"sv)
  125. return File::open(filename, mode);
  126. switch (mode) {
  127. case OpenMode::Read:
  128. return File::adopt_fd(STDIN_FILENO, mode);
  129. case OpenMode::Write:
  130. return File::adopt_fd(STDOUT_FILENO, mode);
  131. default:
  132. VERIFY_NOT_REACHED();
  133. }
  134. }
  135. int File::open_mode_to_options(OpenMode mode)
  136. {
  137. int flags = 0;
  138. if (has_flag(mode, OpenMode::ReadWrite)) {
  139. flags |= O_RDWR | O_CREAT;
  140. } else if (has_flag(mode, OpenMode::Read)) {
  141. flags |= O_RDONLY;
  142. } else if (has_flag(mode, OpenMode::Write)) {
  143. flags |= O_WRONLY | O_CREAT;
  144. bool should_truncate = !has_any_flag(mode, OpenMode::Append | OpenMode::MustBeNew);
  145. if (should_truncate)
  146. flags |= O_TRUNC;
  147. }
  148. if (has_flag(mode, OpenMode::Append))
  149. flags |= O_APPEND;
  150. if (has_flag(mode, OpenMode::Truncate))
  151. flags |= O_TRUNC;
  152. if (has_flag(mode, OpenMode::MustBeNew))
  153. flags |= O_EXCL;
  154. if (!has_flag(mode, OpenMode::KeepOnExec))
  155. flags |= O_CLOEXEC;
  156. if (!has_flag(mode, OpenMode::Nonblocking))
  157. flags |= O_NONBLOCK;
  158. return flags;
  159. }
  160. ErrorOr<void> File::open_path(StringView filename, mode_t permissions)
  161. {
  162. VERIFY(m_fd == -1);
  163. auto flags = open_mode_to_options(m_mode);
  164. m_fd = TRY(System::open(filename, flags, permissions));
  165. return {};
  166. }
  167. bool File::is_readable() const { return has_flag(m_mode, OpenMode::Read); }
  168. bool File::is_writable() const { return has_flag(m_mode, OpenMode::Write); }
  169. ErrorOr<Bytes> File::read(Bytes buffer)
  170. {
  171. if (!has_flag(m_mode, OpenMode::Read)) {
  172. // NOTE: POSIX says that if the fd is not open for reading, the call
  173. // will return EBADF. Since we already know whether we can or
  174. // can't read the file, let's avoid a syscall.
  175. return Error::from_errno(EBADF);
  176. }
  177. ssize_t nread = TRY(System::read(m_fd, buffer));
  178. m_last_read_was_eof = nread == 0;
  179. return buffer.trim(nread);
  180. }
  181. ErrorOr<ByteBuffer> File::read_all(size_t block_size)
  182. {
  183. // Note: This is used as a heuristic, it's not valid for devices or virtual files.
  184. auto const potential_file_size = TRY(System::fstat(m_fd)).st_size;
  185. return read_all_impl(block_size, potential_file_size);
  186. }
  187. ErrorOr<size_t> File::write(ReadonlyBytes buffer)
  188. {
  189. if (!has_flag(m_mode, OpenMode::Write)) {
  190. // NOTE: Same deal as Read.
  191. return Error::from_errno(EBADF);
  192. }
  193. return TRY(System::write(m_fd, buffer));
  194. }
  195. bool File::is_eof() const { return m_last_read_was_eof; }
  196. bool File::is_open() const { return m_fd >= 0; }
  197. void File::close()
  198. {
  199. if (!is_open()) {
  200. return;
  201. }
  202. // NOTE: The closing of the file can be interrupted by a signal, in which
  203. // case EINTR will be returned by the close syscall. So let's try closing
  204. // the file until we aren't interrupted by rude signals. :^)
  205. ErrorOr<void> result;
  206. do {
  207. result = System::close(m_fd);
  208. } while (result.is_error() && result.error().code() == EINTR);
  209. VERIFY(!result.is_error());
  210. m_fd = -1;
  211. }
  212. ErrorOr<off_t> File::seek(i64 offset, SeekMode mode)
  213. {
  214. int syscall_mode;
  215. switch (mode) {
  216. case SeekMode::SetPosition:
  217. syscall_mode = SEEK_SET;
  218. break;
  219. case SeekMode::FromCurrentPosition:
  220. syscall_mode = SEEK_CUR;
  221. break;
  222. case SeekMode::FromEndPosition:
  223. syscall_mode = SEEK_END;
  224. break;
  225. default:
  226. VERIFY_NOT_REACHED();
  227. }
  228. off_t seek_result = TRY(System::lseek(m_fd, offset, syscall_mode));
  229. m_last_read_was_eof = false;
  230. return seek_result;
  231. }
  232. ErrorOr<void> File::truncate(off_t length)
  233. {
  234. return System::ftruncate(m_fd, length);
  235. }
  236. ErrorOr<int> Socket::create_fd(SocketDomain domain, SocketType type)
  237. {
  238. int socket_domain;
  239. switch (domain) {
  240. case SocketDomain::Inet:
  241. socket_domain = AF_INET;
  242. break;
  243. case SocketDomain::Local:
  244. socket_domain = AF_LOCAL;
  245. break;
  246. default:
  247. VERIFY_NOT_REACHED();
  248. }
  249. int socket_type;
  250. switch (type) {
  251. case SocketType::Stream:
  252. socket_type = SOCK_STREAM;
  253. break;
  254. case SocketType::Datagram:
  255. socket_type = SOCK_DGRAM;
  256. break;
  257. default:
  258. VERIFY_NOT_REACHED();
  259. }
  260. // Let's have a safe default of CLOEXEC. :^)
  261. #ifdef SOCK_CLOEXEC
  262. return System::socket(socket_domain, socket_type | SOCK_CLOEXEC, 0);
  263. #else
  264. auto fd = TRY(System::socket(socket_domain, socket_type, 0));
  265. TRY(System::fcntl(fd, F_SETFD, FD_CLOEXEC));
  266. return fd;
  267. #endif
  268. }
  269. ErrorOr<IPv4Address> Socket::resolve_host(String const& host, SocketType type)
  270. {
  271. int socket_type;
  272. switch (type) {
  273. case SocketType::Stream:
  274. socket_type = SOCK_STREAM;
  275. break;
  276. case SocketType::Datagram:
  277. socket_type = SOCK_DGRAM;
  278. break;
  279. default:
  280. VERIFY_NOT_REACHED();
  281. }
  282. struct addrinfo hints = {};
  283. hints.ai_family = AF_UNSPEC;
  284. hints.ai_socktype = socket_type;
  285. hints.ai_flags = 0;
  286. hints.ai_protocol = 0;
  287. // FIXME: Convert this to Core::System
  288. struct addrinfo* results = nullptr;
  289. int rc = getaddrinfo(host.characters(), nullptr, &hints, &results);
  290. if (rc != 0) {
  291. if (rc == EAI_SYSTEM) {
  292. return Error::from_syscall("getaddrinfo"sv, -errno);
  293. }
  294. auto const* error_string = gai_strerror(rc);
  295. return Error::from_string_view({ error_string, strlen(error_string) });
  296. }
  297. auto* socket_address = bit_cast<struct sockaddr_in*>(results->ai_addr);
  298. NetworkOrdered<u32> network_ordered_address { socket_address->sin_addr.s_addr };
  299. freeaddrinfo(results);
  300. return IPv4Address { network_ordered_address };
  301. }
  302. ErrorOr<void> Socket::connect_local(int fd, String const& path)
  303. {
  304. auto address = SocketAddress::local(path);
  305. auto maybe_sockaddr = address.to_sockaddr_un();
  306. if (!maybe_sockaddr.has_value()) {
  307. dbgln("Core::Stream::Socket::connect_local: Could not obtain a sockaddr_un");
  308. return Error::from_errno(EINVAL);
  309. }
  310. auto addr = maybe_sockaddr.release_value();
  311. return System::connect(fd, bit_cast<struct sockaddr*>(&addr), sizeof(addr));
  312. }
  313. ErrorOr<void> Socket::connect_inet(int fd, SocketAddress const& address)
  314. {
  315. auto addr = address.to_sockaddr_in();
  316. return System::connect(fd, bit_cast<struct sockaddr*>(&addr), sizeof(addr));
  317. }
  318. ErrorOr<Bytes> PosixSocketHelper::read(Bytes buffer, int flags)
  319. {
  320. if (!is_open()) {
  321. return Error::from_errno(ENOTCONN);
  322. }
  323. ssize_t nread = TRY(System::recv(m_fd, buffer.data(), buffer.size(), flags));
  324. m_last_read_was_eof = nread == 0;
  325. // If a socket read is EOF, then no more data can be read from it because
  326. // the protocol has disconnected. In this case, we can just disable the
  327. // notifier if we have one.
  328. if (m_last_read_was_eof && m_notifier)
  329. m_notifier->set_enabled(false);
  330. return buffer.trim(nread);
  331. }
  332. ErrorOr<size_t> PosixSocketHelper::write(ReadonlyBytes buffer)
  333. {
  334. if (!is_open()) {
  335. return Error::from_errno(ENOTCONN);
  336. }
  337. return TRY(System::send(m_fd, buffer.data(), buffer.size(), 0));
  338. }
  339. void PosixSocketHelper::close()
  340. {
  341. if (!is_open()) {
  342. return;
  343. }
  344. if (m_notifier)
  345. m_notifier->set_enabled(false);
  346. ErrorOr<void> result;
  347. do {
  348. result = System::close(m_fd);
  349. } while (result.is_error() && result.error().code() == EINTR);
  350. VERIFY(!result.is_error());
  351. m_fd = -1;
  352. }
  353. ErrorOr<bool> PosixSocketHelper::can_read_without_blocking(int timeout) const
  354. {
  355. struct pollfd the_fd = { .fd = m_fd, .events = POLLIN, .revents = 0 };
  356. // FIXME: Convert this to Core::System
  357. int rc;
  358. do {
  359. rc = ::poll(&the_fd, 1, timeout);
  360. } while (rc < 0 && errno == EINTR);
  361. if (rc < 0) {
  362. return Error::from_syscall("poll"sv, -errno);
  363. }
  364. return (the_fd.revents & POLLIN) > 0;
  365. }
  366. ErrorOr<void> PosixSocketHelper::set_blocking(bool enabled)
  367. {
  368. int value = enabled ? 0 : 1;
  369. return System::ioctl(m_fd, FIONBIO, &value);
  370. }
  371. ErrorOr<void> PosixSocketHelper::set_close_on_exec(bool enabled)
  372. {
  373. int flags = TRY(System::fcntl(m_fd, F_GETFD));
  374. if (enabled)
  375. flags |= FD_CLOEXEC;
  376. else
  377. flags &= ~FD_CLOEXEC;
  378. TRY(System::fcntl(m_fd, F_SETFD, flags));
  379. return {};
  380. }
  381. ErrorOr<void> PosixSocketHelper::set_receive_timeout(Time timeout)
  382. {
  383. auto timeout_spec = timeout.to_timespec();
  384. return System::setsockopt(m_fd, SOL_SOCKET, SO_RCVTIMEO, &timeout_spec, sizeof(timeout_spec));
  385. }
  386. void PosixSocketHelper::setup_notifier()
  387. {
  388. if (!m_notifier)
  389. m_notifier = Core::Notifier::construct(m_fd, Core::Notifier::Read);
  390. }
  391. ErrorOr<NonnullOwnPtr<TCPSocket>> TCPSocket::connect(String const& host, u16 port)
  392. {
  393. auto ip_address = TRY(resolve_host(host, SocketType::Stream));
  394. return connect(SocketAddress { ip_address, port });
  395. }
  396. ErrorOr<NonnullOwnPtr<TCPSocket>> TCPSocket::connect(SocketAddress const& address)
  397. {
  398. auto socket = TRY(adopt_nonnull_own_or_enomem(new (nothrow) TCPSocket()));
  399. auto fd = TRY(create_fd(SocketDomain::Inet, SocketType::Stream));
  400. socket->m_helper.set_fd(fd);
  401. TRY(connect_inet(fd, address));
  402. socket->setup_notifier();
  403. return socket;
  404. }
  405. ErrorOr<NonnullOwnPtr<TCPSocket>> TCPSocket::adopt_fd(int fd)
  406. {
  407. if (fd < 0) {
  408. return Error::from_errno(EBADF);
  409. }
  410. auto socket = TRY(adopt_nonnull_own_or_enomem(new (nothrow) TCPSocket()));
  411. socket->m_helper.set_fd(fd);
  412. socket->setup_notifier();
  413. return socket;
  414. }
  415. ErrorOr<size_t> PosixSocketHelper::pending_bytes() const
  416. {
  417. if (!is_open()) {
  418. return Error::from_errno(ENOTCONN);
  419. }
  420. int value;
  421. TRY(System::ioctl(m_fd, FIONREAD, &value));
  422. return static_cast<size_t>(value);
  423. }
  424. ErrorOr<NonnullOwnPtr<UDPSocket>> UDPSocket::connect(String const& host, u16 port, Optional<Time> timeout)
  425. {
  426. auto ip_address = TRY(resolve_host(host, SocketType::Datagram));
  427. return connect(SocketAddress { ip_address, port }, timeout);
  428. }
  429. ErrorOr<NonnullOwnPtr<UDPSocket>> UDPSocket::connect(SocketAddress const& address, Optional<Time> timeout)
  430. {
  431. auto socket = TRY(adopt_nonnull_own_or_enomem(new (nothrow) UDPSocket()));
  432. auto fd = TRY(create_fd(SocketDomain::Inet, SocketType::Datagram));
  433. socket->m_helper.set_fd(fd);
  434. if (timeout.has_value()) {
  435. TRY(socket->m_helper.set_receive_timeout(timeout.value()));
  436. }
  437. TRY(connect_inet(fd, address));
  438. socket->setup_notifier();
  439. return socket;
  440. }
  441. ErrorOr<NonnullOwnPtr<LocalSocket>> LocalSocket::connect(String const& path)
  442. {
  443. auto socket = TRY(adopt_nonnull_own_or_enomem(new (nothrow) LocalSocket()));
  444. auto fd = TRY(create_fd(SocketDomain::Local, SocketType::Stream));
  445. socket->m_helper.set_fd(fd);
  446. TRY(connect_local(fd, path));
  447. socket->setup_notifier();
  448. return socket;
  449. }
  450. ErrorOr<NonnullOwnPtr<LocalSocket>> LocalSocket::adopt_fd(int fd)
  451. {
  452. if (fd < 0) {
  453. return Error::from_errno(EBADF);
  454. }
  455. auto socket = TRY(adopt_nonnull_own_or_enomem(new (nothrow) LocalSocket()));
  456. socket->m_helper.set_fd(fd);
  457. socket->setup_notifier();
  458. return socket;
  459. }
  460. ErrorOr<int> LocalSocket::receive_fd(int flags)
  461. {
  462. #if defined(AK_OS_SERENITY)
  463. return Core::System::recvfd(m_helper.fd(), flags);
  464. #elif defined(AK_OS_LINUX) || defined(AK_OS_MACOS)
  465. union {
  466. struct cmsghdr cmsghdr;
  467. char control[CMSG_SPACE(sizeof(int))];
  468. } cmsgu {};
  469. char c = 0;
  470. struct iovec iov {
  471. .iov_base = &c,
  472. .iov_len = 1,
  473. };
  474. struct msghdr msg {
  475. .msg_name = NULL,
  476. .msg_namelen = 0,
  477. .msg_iov = &iov,
  478. .msg_iovlen = 1,
  479. .msg_control = cmsgu.control,
  480. .msg_controllen = sizeof(cmsgu.control),
  481. .msg_flags = 0,
  482. };
  483. TRY(Core::System::recvmsg(m_helper.fd(), &msg, 0));
  484. struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
  485. if (!cmsg || cmsg->cmsg_len != CMSG_LEN(sizeof(int)))
  486. return Error::from_string_literal("Malformed message when receiving file descriptor");
  487. VERIFY(cmsg->cmsg_level == SOL_SOCKET);
  488. VERIFY(cmsg->cmsg_type == SCM_RIGHTS);
  489. int fd = *((int*)CMSG_DATA(cmsg));
  490. if (flags & O_CLOEXEC) {
  491. auto fd_flags = TRY(Core::System::fcntl(fd, F_GETFD));
  492. TRY(Core::System::fcntl(fd, F_SETFD, fd_flags | FD_CLOEXEC));
  493. }
  494. return fd;
  495. #else
  496. (void)flags;
  497. return Error::from_string_literal("File descriptor passing not supported on this platform");
  498. #endif
  499. }
  500. ErrorOr<void> LocalSocket::send_fd(int fd)
  501. {
  502. #if defined(AK_OS_SERENITY)
  503. return Core::System::sendfd(m_helper.fd(), fd);
  504. #elif defined(AK_OS_LINUX) || defined(AK_OS_MACOS)
  505. char c = 'F';
  506. struct iovec iov {
  507. .iov_base = &c,
  508. .iov_len = sizeof(c)
  509. };
  510. union {
  511. struct cmsghdr cmsghdr;
  512. char control[CMSG_SPACE(sizeof(int))];
  513. } cmsgu {};
  514. struct msghdr msg {
  515. .msg_name = NULL,
  516. .msg_namelen = 0,
  517. .msg_iov = &iov,
  518. .msg_iovlen = 1,
  519. .msg_control = cmsgu.control,
  520. .msg_controllen = sizeof(cmsgu.control),
  521. .msg_flags = 0,
  522. };
  523. struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
  524. cmsg->cmsg_len = CMSG_LEN(sizeof(int));
  525. cmsg->cmsg_level = SOL_SOCKET;
  526. cmsg->cmsg_type = SCM_RIGHTS;
  527. *((int*)CMSG_DATA(cmsg)) = fd;
  528. TRY(Core::System::sendmsg(m_helper.fd(), &msg, 0));
  529. return {};
  530. #else
  531. (void)fd;
  532. return Error::from_string_literal("File descriptor passing not supported on this platform");
  533. #endif
  534. }
  535. ErrorOr<pid_t> LocalSocket::peer_pid() const
  536. {
  537. #ifdef AK_OS_MACOS
  538. pid_t pid;
  539. socklen_t pid_size = sizeof(pid);
  540. #elif defined(__FreeBSD__)
  541. struct xucred creds = {};
  542. socklen_t creds_size = sizeof(creds);
  543. #elif defined(__OpenBSD__)
  544. struct sockpeercred creds = {};
  545. socklen_t creds_size = sizeof(creds);
  546. #else
  547. struct ucred creds = {};
  548. socklen_t creds_size = sizeof(creds);
  549. #endif
  550. #ifdef AK_OS_MACOS
  551. TRY(System::getsockopt(m_helper.fd(), SOL_LOCAL, LOCAL_PEERPID, &pid, &pid_size));
  552. return pid;
  553. #elif defined(__FreeBSD__)
  554. TRY(System::getsockopt(m_helper.fd(), SOL_LOCAL, LOCAL_PEERCRED, &creds, &creds_size));
  555. return creds.cr_pid;
  556. #else
  557. TRY(System::getsockopt(m_helper.fd(), SOL_SOCKET, SO_PEERCRED, &creds, &creds_size));
  558. return creds.pid;
  559. #endif
  560. }
  561. ErrorOr<Bytes> LocalSocket::read_without_waiting(Bytes buffer)
  562. {
  563. return m_helper.read(buffer, MSG_DONTWAIT);
  564. }
  565. Optional<int> LocalSocket::fd() const
  566. {
  567. if (!is_open())
  568. return {};
  569. return m_helper.fd();
  570. }
  571. ErrorOr<int> LocalSocket::release_fd()
  572. {
  573. if (!is_open()) {
  574. return Error::from_errno(ENOTCONN);
  575. }
  576. auto fd = m_helper.fd();
  577. m_helper.set_fd(-1);
  578. return fd;
  579. }
  580. }