Stream.cpp 13 KB

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