Stream.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  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. ScopeGuard free_results = [results] { freeaddrinfo(results); };
  298. for (auto* result = results; result != nullptr; result = result->ai_next) {
  299. if (result->ai_family == AF_INET) {
  300. auto* socket_address = bit_cast<struct sockaddr_in*>(result->ai_addr);
  301. NetworkOrdered<u32> network_ordered_address { socket_address->sin_addr.s_addr };
  302. return IPv4Address { network_ordered_address };
  303. }
  304. }
  305. return Error::from_string_literal("Could not resolve to IPv4 address");
  306. }
  307. ErrorOr<void> Socket::connect_local(int fd, String const& path)
  308. {
  309. auto address = SocketAddress::local(path);
  310. auto maybe_sockaddr = address.to_sockaddr_un();
  311. if (!maybe_sockaddr.has_value()) {
  312. dbgln("Core::Stream::Socket::connect_local: Could not obtain a sockaddr_un");
  313. return Error::from_errno(EINVAL);
  314. }
  315. auto addr = maybe_sockaddr.release_value();
  316. return System::connect(fd, bit_cast<struct sockaddr*>(&addr), sizeof(addr));
  317. }
  318. ErrorOr<void> Socket::connect_inet(int fd, SocketAddress const& address)
  319. {
  320. auto addr = address.to_sockaddr_in();
  321. return System::connect(fd, bit_cast<struct sockaddr*>(&addr), sizeof(addr));
  322. }
  323. ErrorOr<Bytes> PosixSocketHelper::read(Bytes buffer, int flags)
  324. {
  325. if (!is_open()) {
  326. return Error::from_errno(ENOTCONN);
  327. }
  328. ssize_t nread = TRY(System::recv(m_fd, buffer.data(), buffer.size(), flags));
  329. m_last_read_was_eof = nread == 0;
  330. // If a socket read is EOF, then no more data can be read from it because
  331. // the protocol has disconnected. In this case, we can just disable the
  332. // notifier if we have one.
  333. if (m_last_read_was_eof && m_notifier)
  334. m_notifier->set_enabled(false);
  335. return buffer.trim(nread);
  336. }
  337. ErrorOr<size_t> PosixSocketHelper::write(ReadonlyBytes buffer)
  338. {
  339. if (!is_open()) {
  340. return Error::from_errno(ENOTCONN);
  341. }
  342. return TRY(System::send(m_fd, buffer.data(), buffer.size(), 0));
  343. }
  344. void PosixSocketHelper::close()
  345. {
  346. if (!is_open()) {
  347. return;
  348. }
  349. if (m_notifier)
  350. m_notifier->set_enabled(false);
  351. ErrorOr<void> result;
  352. do {
  353. result = System::close(m_fd);
  354. } while (result.is_error() && result.error().code() == EINTR);
  355. VERIFY(!result.is_error());
  356. m_fd = -1;
  357. }
  358. ErrorOr<bool> PosixSocketHelper::can_read_without_blocking(int timeout) const
  359. {
  360. struct pollfd the_fd = { .fd = m_fd, .events = POLLIN, .revents = 0 };
  361. // FIXME: Convert this to Core::System
  362. int rc;
  363. do {
  364. rc = ::poll(&the_fd, 1, timeout);
  365. } while (rc < 0 && errno == EINTR);
  366. if (rc < 0) {
  367. return Error::from_syscall("poll"sv, -errno);
  368. }
  369. return (the_fd.revents & POLLIN) > 0;
  370. }
  371. ErrorOr<void> PosixSocketHelper::set_blocking(bool enabled)
  372. {
  373. int value = enabled ? 0 : 1;
  374. return System::ioctl(m_fd, FIONBIO, &value);
  375. }
  376. ErrorOr<void> PosixSocketHelper::set_close_on_exec(bool enabled)
  377. {
  378. int flags = TRY(System::fcntl(m_fd, F_GETFD));
  379. if (enabled)
  380. flags |= FD_CLOEXEC;
  381. else
  382. flags &= ~FD_CLOEXEC;
  383. TRY(System::fcntl(m_fd, F_SETFD, flags));
  384. return {};
  385. }
  386. ErrorOr<void> PosixSocketHelper::set_receive_timeout(Time timeout)
  387. {
  388. auto timeout_spec = timeout.to_timespec();
  389. return System::setsockopt(m_fd, SOL_SOCKET, SO_RCVTIMEO, &timeout_spec, sizeof(timeout_spec));
  390. }
  391. void PosixSocketHelper::setup_notifier()
  392. {
  393. if (!m_notifier)
  394. m_notifier = Core::Notifier::construct(m_fd, Core::Notifier::Read);
  395. }
  396. ErrorOr<NonnullOwnPtr<TCPSocket>> TCPSocket::connect(String const& host, u16 port)
  397. {
  398. auto ip_address = TRY(resolve_host(host, SocketType::Stream));
  399. return connect(SocketAddress { ip_address, port });
  400. }
  401. ErrorOr<NonnullOwnPtr<TCPSocket>> TCPSocket::connect(SocketAddress const& address)
  402. {
  403. auto socket = TRY(adopt_nonnull_own_or_enomem(new (nothrow) TCPSocket()));
  404. auto fd = TRY(create_fd(SocketDomain::Inet, SocketType::Stream));
  405. socket->m_helper.set_fd(fd);
  406. TRY(connect_inet(fd, address));
  407. socket->setup_notifier();
  408. return socket;
  409. }
  410. ErrorOr<NonnullOwnPtr<TCPSocket>> TCPSocket::adopt_fd(int fd)
  411. {
  412. if (fd < 0) {
  413. return Error::from_errno(EBADF);
  414. }
  415. auto socket = TRY(adopt_nonnull_own_or_enomem(new (nothrow) TCPSocket()));
  416. socket->m_helper.set_fd(fd);
  417. socket->setup_notifier();
  418. return socket;
  419. }
  420. ErrorOr<size_t> PosixSocketHelper::pending_bytes() const
  421. {
  422. if (!is_open()) {
  423. return Error::from_errno(ENOTCONN);
  424. }
  425. int value;
  426. TRY(System::ioctl(m_fd, FIONREAD, &value));
  427. return static_cast<size_t>(value);
  428. }
  429. ErrorOr<NonnullOwnPtr<UDPSocket>> UDPSocket::connect(String const& host, u16 port, Optional<Time> timeout)
  430. {
  431. auto ip_address = TRY(resolve_host(host, SocketType::Datagram));
  432. return connect(SocketAddress { ip_address, port }, timeout);
  433. }
  434. ErrorOr<NonnullOwnPtr<UDPSocket>> UDPSocket::connect(SocketAddress const& address, Optional<Time> timeout)
  435. {
  436. auto socket = TRY(adopt_nonnull_own_or_enomem(new (nothrow) UDPSocket()));
  437. auto fd = TRY(create_fd(SocketDomain::Inet, SocketType::Datagram));
  438. socket->m_helper.set_fd(fd);
  439. if (timeout.has_value()) {
  440. TRY(socket->m_helper.set_receive_timeout(timeout.value()));
  441. }
  442. TRY(connect_inet(fd, address));
  443. socket->setup_notifier();
  444. return socket;
  445. }
  446. ErrorOr<NonnullOwnPtr<LocalSocket>> LocalSocket::connect(String const& path)
  447. {
  448. auto socket = TRY(adopt_nonnull_own_or_enomem(new (nothrow) LocalSocket()));
  449. auto fd = TRY(create_fd(SocketDomain::Local, SocketType::Stream));
  450. socket->m_helper.set_fd(fd);
  451. TRY(connect_local(fd, path));
  452. socket->setup_notifier();
  453. return socket;
  454. }
  455. ErrorOr<NonnullOwnPtr<LocalSocket>> LocalSocket::adopt_fd(int fd)
  456. {
  457. if (fd < 0) {
  458. return Error::from_errno(EBADF);
  459. }
  460. auto socket = TRY(adopt_nonnull_own_or_enomem(new (nothrow) LocalSocket()));
  461. socket->m_helper.set_fd(fd);
  462. socket->setup_notifier();
  463. return socket;
  464. }
  465. ErrorOr<int> LocalSocket::receive_fd(int flags)
  466. {
  467. #if defined(AK_OS_SERENITY)
  468. return Core::System::recvfd(m_helper.fd(), flags);
  469. #elif defined(AK_OS_LINUX) || defined(AK_OS_MACOS)
  470. union {
  471. struct cmsghdr cmsghdr;
  472. char control[CMSG_SPACE(sizeof(int))];
  473. } cmsgu {};
  474. char c = 0;
  475. struct iovec iov {
  476. .iov_base = &c,
  477. .iov_len = 1,
  478. };
  479. struct msghdr msg {
  480. .msg_name = NULL,
  481. .msg_namelen = 0,
  482. .msg_iov = &iov,
  483. .msg_iovlen = 1,
  484. .msg_control = cmsgu.control,
  485. .msg_controllen = sizeof(cmsgu.control),
  486. .msg_flags = 0,
  487. };
  488. TRY(Core::System::recvmsg(m_helper.fd(), &msg, 0));
  489. struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
  490. if (!cmsg || cmsg->cmsg_len != CMSG_LEN(sizeof(int)))
  491. return Error::from_string_literal("Malformed message when receiving file descriptor");
  492. VERIFY(cmsg->cmsg_level == SOL_SOCKET);
  493. VERIFY(cmsg->cmsg_type == SCM_RIGHTS);
  494. int fd = *((int*)CMSG_DATA(cmsg));
  495. if (flags & O_CLOEXEC) {
  496. auto fd_flags = TRY(Core::System::fcntl(fd, F_GETFD));
  497. TRY(Core::System::fcntl(fd, F_SETFD, fd_flags | FD_CLOEXEC));
  498. }
  499. return fd;
  500. #else
  501. (void)flags;
  502. return Error::from_string_literal("File descriptor passing not supported on this platform");
  503. #endif
  504. }
  505. ErrorOr<void> LocalSocket::send_fd(int fd)
  506. {
  507. #if defined(AK_OS_SERENITY)
  508. return Core::System::sendfd(m_helper.fd(), fd);
  509. #elif defined(AK_OS_LINUX) || defined(AK_OS_MACOS)
  510. char c = 'F';
  511. struct iovec iov {
  512. .iov_base = &c,
  513. .iov_len = sizeof(c)
  514. };
  515. union {
  516. struct cmsghdr cmsghdr;
  517. char control[CMSG_SPACE(sizeof(int))];
  518. } cmsgu {};
  519. struct msghdr msg {
  520. .msg_name = NULL,
  521. .msg_namelen = 0,
  522. .msg_iov = &iov,
  523. .msg_iovlen = 1,
  524. .msg_control = cmsgu.control,
  525. .msg_controllen = sizeof(cmsgu.control),
  526. .msg_flags = 0,
  527. };
  528. struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
  529. cmsg->cmsg_len = CMSG_LEN(sizeof(int));
  530. cmsg->cmsg_level = SOL_SOCKET;
  531. cmsg->cmsg_type = SCM_RIGHTS;
  532. *((int*)CMSG_DATA(cmsg)) = fd;
  533. TRY(Core::System::sendmsg(m_helper.fd(), &msg, 0));
  534. return {};
  535. #else
  536. (void)fd;
  537. return Error::from_string_literal("File descriptor passing not supported on this platform");
  538. #endif
  539. }
  540. ErrorOr<pid_t> LocalSocket::peer_pid() const
  541. {
  542. #ifdef AK_OS_MACOS
  543. pid_t pid;
  544. socklen_t pid_size = sizeof(pid);
  545. #elif defined(__FreeBSD__)
  546. struct xucred creds = {};
  547. socklen_t creds_size = sizeof(creds);
  548. #elif defined(__OpenBSD__)
  549. struct sockpeercred creds = {};
  550. socklen_t creds_size = sizeof(creds);
  551. #else
  552. struct ucred creds = {};
  553. socklen_t creds_size = sizeof(creds);
  554. #endif
  555. #ifdef AK_OS_MACOS
  556. TRY(System::getsockopt(m_helper.fd(), SOL_LOCAL, LOCAL_PEERPID, &pid, &pid_size));
  557. return pid;
  558. #elif defined(__FreeBSD__)
  559. TRY(System::getsockopt(m_helper.fd(), SOL_LOCAL, LOCAL_PEERCRED, &creds, &creds_size));
  560. return creds.cr_pid;
  561. #else
  562. TRY(System::getsockopt(m_helper.fd(), SOL_SOCKET, SO_PEERCRED, &creds, &creds_size));
  563. return creds.pid;
  564. #endif
  565. }
  566. ErrorOr<Bytes> LocalSocket::read_without_waiting(Bytes buffer)
  567. {
  568. return m_helper.read(buffer, MSG_DONTWAIT);
  569. }
  570. Optional<int> LocalSocket::fd() const
  571. {
  572. if (!is_open())
  573. return {};
  574. return m_helper.fd();
  575. }
  576. ErrorOr<int> LocalSocket::release_fd()
  577. {
  578. if (!is_open()) {
  579. return Error::from_errno(ENOTCONN);
  580. }
  581. auto fd = m_helper.fd();
  582. m_helper.set_fd(-1);
  583. return fd;
  584. }
  585. }