Stream.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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. bool Stream::write_or_error(ReadonlyBytes buffer)
  42. {
  43. VERIFY(buffer.size());
  44. size_t nwritten = 0;
  45. do {
  46. auto result = write(buffer.slice(nwritten));
  47. if (result.is_error()) {
  48. if (result.error().is_errno() && result.error().code() == EINTR) {
  49. continue;
  50. }
  51. return false;
  52. }
  53. nwritten += result.value();
  54. } while (nwritten < buffer.size());
  55. return true;
  56. }
  57. ErrorOr<off_t> SeekableStream::tell() const
  58. {
  59. // Seek with 0 and SEEK_CUR does not modify anything despite the const_cast,
  60. // so it's safe to do this.
  61. return const_cast<SeekableStream*>(this)->seek(0, SeekMode::FromCurrentPosition);
  62. }
  63. ErrorOr<off_t> SeekableStream::size()
  64. {
  65. auto original_position = TRY(tell());
  66. auto seek_result = seek(0, SeekMode::FromEndPosition);
  67. if (seek_result.is_error()) {
  68. // Let's try to restore the original position, just in case.
  69. auto restore_result = seek(original_position, SeekMode::SetPosition);
  70. if (restore_result.is_error()) {
  71. dbgln("Core::SeekableStream::size: Couldn't restore initial position, stream might have incorrect position now!");
  72. }
  73. return seek_result.release_error();
  74. }
  75. TRY(seek(original_position, SeekMode::SetPosition));
  76. return seek_result.value();
  77. }
  78. ErrorOr<NonnullOwnPtr<File>> File::open(StringView filename, OpenMode mode, mode_t permissions)
  79. {
  80. auto file = TRY(adopt_nonnull_own_or_enomem(new (nothrow) File(mode)));
  81. TRY(file->open_path(filename, permissions));
  82. return file;
  83. }
  84. ErrorOr<NonnullOwnPtr<File>> File::adopt_fd(int fd, OpenMode mode)
  85. {
  86. if (fd < 0) {
  87. return Error::from_errno(EBADF);
  88. }
  89. if (!has_any_flag(mode, OpenMode::ReadWrite)) {
  90. dbgln("Core::File::adopt_fd: Attempting to adopt a file with neither Read nor Write specified in mode");
  91. return Error::from_errno(EINVAL);
  92. }
  93. auto file = TRY(adopt_nonnull_own_or_enomem(new (nothrow) File(mode)));
  94. file->m_fd = fd;
  95. return file;
  96. }
  97. int File::open_mode_to_options(OpenMode mode)
  98. {
  99. int flags = 0;
  100. if (has_flag(mode, OpenMode::ReadWrite)) {
  101. flags |= O_RDWR | O_CREAT;
  102. } else if (has_flag(mode, OpenMode::Read)) {
  103. flags |= O_RDONLY;
  104. } else if (has_flag(mode, OpenMode::Write)) {
  105. flags |= O_WRONLY | O_CREAT;
  106. bool should_truncate = !has_any_flag(mode, OpenMode::Append | OpenMode::MustBeNew);
  107. if (should_truncate)
  108. flags |= O_TRUNC;
  109. }
  110. if (has_flag(mode, OpenMode::Append))
  111. flags |= O_APPEND;
  112. if (has_flag(mode, OpenMode::Truncate))
  113. flags |= O_TRUNC;
  114. if (has_flag(mode, OpenMode::MustBeNew))
  115. flags |= O_EXCL;
  116. if (!has_flag(mode, OpenMode::KeepOnExec))
  117. flags |= O_CLOEXEC;
  118. if (!has_flag(mode, OpenMode::Nonblocking))
  119. flags |= O_NONBLOCK;
  120. return flags;
  121. }
  122. ErrorOr<void> File::open_path(StringView filename, mode_t permissions)
  123. {
  124. VERIFY(m_fd == -1);
  125. auto flags = open_mode_to_options(m_mode);
  126. m_fd = TRY(System::open(filename.characters_without_null_termination(), flags, permissions));
  127. return {};
  128. }
  129. bool File::is_readable() const { return has_flag(m_mode, OpenMode::Read); }
  130. bool File::is_writable() const { return has_flag(m_mode, OpenMode::Write); }
  131. ErrorOr<Bytes> File::read(Bytes buffer)
  132. {
  133. if (!has_flag(m_mode, OpenMode::Read)) {
  134. // NOTE: POSIX says that if the fd is not open for reading, the call
  135. // will return EBADF. Since we already know whether we can or
  136. // can't read the file, let's avoid a syscall.
  137. return Error::from_errno(EBADF);
  138. }
  139. ssize_t nread = TRY(System::read(m_fd, buffer));
  140. m_last_read_was_eof = nread == 0;
  141. return buffer.trim(nread);
  142. }
  143. ErrorOr<size_t> File::write(ReadonlyBytes buffer)
  144. {
  145. if (!has_flag(m_mode, OpenMode::Write)) {
  146. // NOTE: Same deal as Read.
  147. return Error::from_errno(EBADF);
  148. }
  149. return TRY(System::write(m_fd, buffer));
  150. }
  151. bool File::is_eof() const { return m_last_read_was_eof; }
  152. bool File::is_open() const { return m_fd >= 0; }
  153. void File::close()
  154. {
  155. if (!is_open()) {
  156. return;
  157. }
  158. // NOTE: The closing of the file can be interrupted by a signal, in which
  159. // case EINTR will be returned by the close syscall. So let's try closing
  160. // the file until we aren't interrupted by rude signals. :^)
  161. ErrorOr<void> result;
  162. do {
  163. result = System::close(m_fd);
  164. } while (result.is_error() && result.error().code() == EINTR);
  165. VERIFY(!result.is_error());
  166. m_fd = -1;
  167. }
  168. ErrorOr<off_t> File::seek(i64 offset, SeekMode mode)
  169. {
  170. int syscall_mode;
  171. switch (mode) {
  172. case SeekMode::SetPosition:
  173. syscall_mode = SEEK_SET;
  174. break;
  175. case SeekMode::FromCurrentPosition:
  176. syscall_mode = SEEK_CUR;
  177. break;
  178. case SeekMode::FromEndPosition:
  179. syscall_mode = SEEK_END;
  180. break;
  181. default:
  182. VERIFY_NOT_REACHED();
  183. }
  184. off_t seek_result = TRY(System::lseek(m_fd, offset, syscall_mode));
  185. m_last_read_was_eof = false;
  186. return seek_result;
  187. }
  188. ErrorOr<void> File::truncate(off_t length)
  189. {
  190. return System::ftruncate(m_fd, length);
  191. }
  192. ErrorOr<int> Socket::create_fd(SocketDomain domain, SocketType type)
  193. {
  194. int socket_domain;
  195. switch (domain) {
  196. case SocketDomain::Inet:
  197. socket_domain = AF_INET;
  198. break;
  199. case SocketDomain::Local:
  200. socket_domain = AF_LOCAL;
  201. break;
  202. default:
  203. VERIFY_NOT_REACHED();
  204. }
  205. int socket_type;
  206. switch (type) {
  207. case SocketType::Stream:
  208. socket_type = SOCK_STREAM;
  209. break;
  210. case SocketType::Datagram:
  211. socket_type = SOCK_DGRAM;
  212. break;
  213. default:
  214. VERIFY_NOT_REACHED();
  215. }
  216. // Let's have a safe default of CLOEXEC. :^)
  217. #ifdef SOCK_CLOEXEC
  218. return System::socket(socket_domain, socket_type | SOCK_CLOEXEC, 0);
  219. #else
  220. auto fd = TRY(System::socket(socket_domain, socket_type, 0));
  221. TRY(System::fcntl(fd, F_SETFD, FD_CLOEXEC));
  222. return fd;
  223. #endif
  224. }
  225. ErrorOr<IPv4Address> Socket::resolve_host(String const& host, SocketType type)
  226. {
  227. int socket_type;
  228. switch (type) {
  229. case SocketType::Stream:
  230. socket_type = SOCK_STREAM;
  231. break;
  232. case SocketType::Datagram:
  233. socket_type = SOCK_DGRAM;
  234. break;
  235. default:
  236. VERIFY_NOT_REACHED();
  237. }
  238. struct addrinfo hints = {};
  239. hints.ai_family = AF_UNSPEC;
  240. hints.ai_socktype = socket_type;
  241. hints.ai_flags = 0;
  242. hints.ai_protocol = 0;
  243. // FIXME: Convert this to Core::System
  244. struct addrinfo* results = nullptr;
  245. int rc = getaddrinfo(host.characters(), nullptr, &hints, &results);
  246. if (rc != 0) {
  247. if (rc == EAI_SYSTEM) {
  248. return Error::from_syscall("getaddrinfo", -errno);
  249. }
  250. return Error::from_string_literal(gai_strerror(rc));
  251. }
  252. auto* socket_address = bit_cast<struct sockaddr_in*>(results->ai_addr);
  253. NetworkOrdered<u32> network_ordered_address { socket_address->sin_addr.s_addr };
  254. freeaddrinfo(results);
  255. return IPv4Address { network_ordered_address };
  256. }
  257. ErrorOr<void> Socket::connect_local(int fd, String const& path)
  258. {
  259. auto address = SocketAddress::local(path);
  260. auto maybe_sockaddr = address.to_sockaddr_un();
  261. if (!maybe_sockaddr.has_value()) {
  262. dbgln("Core::Stream::Socket::connect_local: Could not obtain a sockaddr_un");
  263. return Error::from_errno(EINVAL);
  264. }
  265. auto addr = maybe_sockaddr.release_value();
  266. return System::connect(fd, bit_cast<struct sockaddr*>(&addr), sizeof(addr));
  267. }
  268. ErrorOr<void> Socket::connect_inet(int fd, SocketAddress const& address)
  269. {
  270. auto addr = address.to_sockaddr_in();
  271. return System::connect(fd, bit_cast<struct sockaddr*>(&addr), sizeof(addr));
  272. }
  273. ErrorOr<Bytes> PosixSocketHelper::read(Bytes buffer, int flags)
  274. {
  275. if (!is_open()) {
  276. return Error::from_errno(ENOTCONN);
  277. }
  278. ssize_t nread = TRY(System::recv(m_fd, buffer.data(), buffer.size(), flags));
  279. m_last_read_was_eof = nread == 0;
  280. // If a socket read is EOF, then no more data can be read from it because
  281. // the protocol has disconnected. In this case, we can just disable the
  282. // notifier if we have one.
  283. if (m_last_read_was_eof && m_notifier)
  284. m_notifier->set_enabled(false);
  285. return buffer.trim(nread);
  286. }
  287. ErrorOr<size_t> PosixSocketHelper::write(ReadonlyBytes buffer)
  288. {
  289. if (!is_open()) {
  290. return Error::from_errno(ENOTCONN);
  291. }
  292. return TRY(System::send(m_fd, buffer.data(), buffer.size(), 0));
  293. }
  294. void PosixSocketHelper::close()
  295. {
  296. if (!is_open()) {
  297. return;
  298. }
  299. if (m_notifier)
  300. m_notifier->set_enabled(false);
  301. ErrorOr<void> result;
  302. do {
  303. result = System::close(m_fd);
  304. } while (result.is_error() && result.error().code() == EINTR);
  305. VERIFY(!result.is_error());
  306. m_fd = -1;
  307. }
  308. ErrorOr<bool> PosixSocketHelper::can_read_without_blocking(int timeout) const
  309. {
  310. struct pollfd the_fd = { .fd = m_fd, .events = POLLIN, .revents = 0 };
  311. // FIXME: Convert this to Core::System
  312. int rc;
  313. do {
  314. rc = ::poll(&the_fd, 1, timeout);
  315. } while (rc < 0 && errno == EINTR);
  316. if (rc < 0) {
  317. return Error::from_syscall("poll", -errno);
  318. }
  319. return (the_fd.revents & POLLIN) > 0;
  320. }
  321. ErrorOr<void> PosixSocketHelper::set_blocking(bool enabled)
  322. {
  323. int value = enabled ? 0 : 1;
  324. return System::ioctl(m_fd, FIONBIO, &value);
  325. }
  326. ErrorOr<void> PosixSocketHelper::set_close_on_exec(bool enabled)
  327. {
  328. int flags = TRY(System::fcntl(m_fd, F_GETFD));
  329. if (enabled)
  330. flags |= FD_CLOEXEC;
  331. else
  332. flags &= ~FD_CLOEXEC;
  333. TRY(System::fcntl(m_fd, F_SETFD, flags));
  334. return {};
  335. }
  336. ErrorOr<void> PosixSocketHelper::set_receive_timeout(Time timeout)
  337. {
  338. auto timeout_spec = timeout.to_timespec();
  339. return System::setsockopt(m_fd, SOL_SOCKET, SO_RCVTIMEO, &timeout_spec, sizeof(timeout_spec));
  340. }
  341. void PosixSocketHelper::setup_notifier()
  342. {
  343. if (!m_notifier)
  344. m_notifier = Core::Notifier::construct(m_fd, Core::Notifier::Read);
  345. }
  346. ErrorOr<NonnullOwnPtr<TCPSocket>> TCPSocket::connect(String const& host, u16 port)
  347. {
  348. auto ip_address = TRY(resolve_host(host, SocketType::Stream));
  349. return connect(SocketAddress { ip_address, port });
  350. }
  351. ErrorOr<NonnullOwnPtr<TCPSocket>> TCPSocket::connect(SocketAddress const& address)
  352. {
  353. auto socket = TRY(adopt_nonnull_own_or_enomem(new (nothrow) TCPSocket()));
  354. auto fd = TRY(create_fd(SocketDomain::Inet, SocketType::Stream));
  355. socket->m_helper.set_fd(fd);
  356. TRY(connect_inet(fd, address));
  357. socket->setup_notifier();
  358. return socket;
  359. }
  360. ErrorOr<NonnullOwnPtr<TCPSocket>> TCPSocket::adopt_fd(int fd)
  361. {
  362. if (fd < 0) {
  363. return Error::from_errno(EBADF);
  364. }
  365. auto socket = TRY(adopt_nonnull_own_or_enomem(new (nothrow) TCPSocket()));
  366. socket->m_helper.set_fd(fd);
  367. socket->setup_notifier();
  368. return socket;
  369. }
  370. ErrorOr<size_t> PosixSocketHelper::pending_bytes() const
  371. {
  372. if (!is_open()) {
  373. return Error::from_errno(ENOTCONN);
  374. }
  375. int value;
  376. TRY(System::ioctl(m_fd, FIONREAD, &value));
  377. return static_cast<size_t>(value);
  378. }
  379. ErrorOr<NonnullOwnPtr<UDPSocket>> UDPSocket::connect(String const& host, u16 port, Optional<Time> timeout)
  380. {
  381. auto ip_address = TRY(resolve_host(host, SocketType::Datagram));
  382. return connect(SocketAddress { ip_address, port }, timeout);
  383. }
  384. ErrorOr<NonnullOwnPtr<UDPSocket>> UDPSocket::connect(SocketAddress const& address, Optional<Time> timeout)
  385. {
  386. auto socket = TRY(adopt_nonnull_own_or_enomem(new (nothrow) UDPSocket()));
  387. auto fd = TRY(create_fd(SocketDomain::Inet, SocketType::Datagram));
  388. socket->m_helper.set_fd(fd);
  389. if (timeout.has_value()) {
  390. TRY(socket->m_helper.set_receive_timeout(timeout.value()));
  391. }
  392. TRY(connect_inet(fd, address));
  393. socket->setup_notifier();
  394. return socket;
  395. }
  396. ErrorOr<NonnullOwnPtr<LocalSocket>> LocalSocket::connect(String const& path)
  397. {
  398. auto socket = TRY(adopt_nonnull_own_or_enomem(new (nothrow) LocalSocket()));
  399. auto fd = TRY(create_fd(SocketDomain::Local, SocketType::Stream));
  400. socket->m_helper.set_fd(fd);
  401. TRY(connect_local(fd, path));
  402. socket->setup_notifier();
  403. return socket;
  404. }
  405. ErrorOr<NonnullOwnPtr<LocalSocket>> LocalSocket::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) LocalSocket()));
  411. socket->m_helper.set_fd(fd);
  412. socket->setup_notifier();
  413. return socket;
  414. }
  415. ErrorOr<int> LocalSocket::receive_fd(int flags)
  416. {
  417. #ifdef __serenity__
  418. return Core::System::recvfd(m_helper.fd(), flags);
  419. #else
  420. (void)flags;
  421. return Error::from_string_literal("File descriptor passing not supported on this platform");
  422. #endif
  423. }
  424. ErrorOr<void> LocalSocket::send_fd(int fd)
  425. {
  426. #ifdef __serenity__
  427. return Core::System::sendfd(m_helper.fd(), fd);
  428. #else
  429. (void)fd;
  430. return Error::from_string_literal("File descriptor passing not supported on this platform");
  431. #endif
  432. }
  433. ErrorOr<pid_t> LocalSocket::peer_pid() const
  434. {
  435. #ifdef AK_OS_MACOS
  436. pid_t pid;
  437. socklen_t pid_size = sizeof(pid);
  438. #elif defined(__FreeBSD__)
  439. struct xucred creds = {};
  440. socklen_t creds_size = sizeof(creds);
  441. #elif defined(__OpenBSD__)
  442. struct sockpeercred creds = {};
  443. socklen_t creds_size = sizeof(creds);
  444. #else
  445. struct ucred creds = {};
  446. socklen_t creds_size = sizeof(creds);
  447. #endif
  448. #ifdef AK_OS_MACOS
  449. TRY(System::getsockopt(m_helper.fd(), SOL_LOCAL, LOCAL_PEERPID, &pid, &pid_size));
  450. return pid;
  451. #elif defined(__FreeBSD__)
  452. TRY(System::getsockopt(m_helper.fd(), SOL_LOCAL, LOCAL_PEERCRED, &creds, &creds_size));
  453. return creds.cr_pid;
  454. #else
  455. TRY(System::getsockopt(m_helper.fd(), SOL_SOCKET, SO_PEERCRED, &creds, &creds_size));
  456. return creds.pid;
  457. #endif
  458. }
  459. ErrorOr<Bytes> LocalSocket::read_without_waiting(Bytes buffer)
  460. {
  461. return m_helper.read(buffer, MSG_DONTWAIT);
  462. }
  463. ErrorOr<int> LocalSocket::release_fd()
  464. {
  465. if (!is_open()) {
  466. return Error::from_errno(ENOTCONN);
  467. }
  468. auto fd = m_helper.fd();
  469. m_helper.set_fd(-1);
  470. return fd;
  471. }
  472. }