LocalSocket.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Singleton.h>
  27. #include <AK/StringBuilder.h>
  28. #include <Kernel/Debug.h>
  29. #include <Kernel/FileSystem/FileDescription.h>
  30. #include <Kernel/FileSystem/VirtualFileSystem.h>
  31. #include <Kernel/Net/LocalSocket.h>
  32. #include <Kernel/Process.h>
  33. #include <Kernel/StdLib.h>
  34. #include <Kernel/UnixTypes.h>
  35. #include <LibC/errno_numbers.h>
  36. namespace Kernel {
  37. static AK::Singleton<Lockable<InlineLinkedList<LocalSocket>>> s_list;
  38. Lockable<InlineLinkedList<LocalSocket>>& LocalSocket::all_sockets()
  39. {
  40. return *s_list;
  41. }
  42. void LocalSocket::for_each(Function<void(const LocalSocket&)> callback)
  43. {
  44. LOCKER(all_sockets().lock(), Lock::Mode::Shared);
  45. for (auto& socket : all_sockets().resource())
  46. callback(socket);
  47. }
  48. KResultOr<NonnullRefPtr<Socket>> LocalSocket::create(int type)
  49. {
  50. return adopt(*new LocalSocket(type));
  51. }
  52. LocalSocket::LocalSocket(int type)
  53. : Socket(AF_LOCAL, type, 0)
  54. {
  55. LOCKER(all_sockets().lock());
  56. all_sockets().resource().append(this);
  57. auto current_process = Process::current();
  58. m_prebind_uid = current_process->euid();
  59. m_prebind_gid = current_process->egid();
  60. m_prebind_mode = 0666;
  61. m_for_client.set_unblock_callback([this]() {
  62. evaluate_block_conditions();
  63. });
  64. m_for_server.set_unblock_callback([this]() {
  65. evaluate_block_conditions();
  66. });
  67. dbgln<LOCAL_SOCKET_DEBUG>("LocalSocket({}) created with type={}", this, type);
  68. }
  69. LocalSocket::~LocalSocket()
  70. {
  71. LOCKER(all_sockets().lock());
  72. all_sockets().resource().remove(this);
  73. }
  74. void LocalSocket::get_local_address(sockaddr* address, socklen_t* address_size)
  75. {
  76. size_t bytes_to_copy = min(static_cast<size_t>(*address_size), sizeof(sockaddr_un));
  77. memcpy(address, &m_address, bytes_to_copy);
  78. *address_size = sizeof(sockaddr_un);
  79. }
  80. void LocalSocket::get_peer_address(sockaddr* address, socklen_t* address_size)
  81. {
  82. get_local_address(address, address_size);
  83. }
  84. KResult LocalSocket::bind(Userspace<const sockaddr*> user_address, socklen_t address_size)
  85. {
  86. ASSERT(setup_state() == SetupState::Unstarted);
  87. if (address_size != sizeof(sockaddr_un))
  88. return EINVAL;
  89. sockaddr_un address;
  90. if (!copy_from_user(&address, user_address, sizeof(sockaddr_un)))
  91. return EFAULT;
  92. if (address.sun_family != AF_LOCAL)
  93. return EINVAL;
  94. auto path = String(address.sun_path, strnlen(address.sun_path, sizeof(address.sun_path)));
  95. dbgln<LOCAL_SOCKET_DEBUG>("LocalSocket({}) bind({})", this, path);
  96. mode_t mode = S_IFSOCK | (m_prebind_mode & 0777);
  97. UidAndGid owner { m_prebind_uid, m_prebind_gid };
  98. auto result = VFS::the().open(path, O_CREAT | O_EXCL | O_NOFOLLOW_NOERROR, mode, Process::current()->current_directory(), owner);
  99. if (result.is_error()) {
  100. if (result.error() == -EEXIST)
  101. return EADDRINUSE;
  102. return result.error();
  103. }
  104. auto file = move(result.value());
  105. ASSERT(file->inode());
  106. if (!file->inode()->bind_socket(*this))
  107. return EADDRINUSE;
  108. m_file = move(file);
  109. m_address = address;
  110. m_bound = true;
  111. return KSuccess;
  112. }
  113. KResult LocalSocket::connect(FileDescription& description, Userspace<const sockaddr*> address, socklen_t address_size, ShouldBlock)
  114. {
  115. ASSERT(!m_bound);
  116. if (address_size != sizeof(sockaddr_un))
  117. return EINVAL;
  118. u16 sa_family_copy;
  119. auto* user_address = reinterpret_cast<const sockaddr*>(address.unsafe_userspace_ptr());
  120. if (!copy_from_user(&sa_family_copy, &user_address->sa_family, sizeof(u16)))
  121. return EFAULT;
  122. if (sa_family_copy != AF_LOCAL)
  123. return EINVAL;
  124. if (is_connected())
  125. return EISCONN;
  126. const auto& local_address = *reinterpret_cast<const sockaddr_un*>(user_address);
  127. char safe_address[sizeof(local_address.sun_path) + 1] = { 0 };
  128. if (!copy_from_user(&safe_address[0], &local_address.sun_path[0], sizeof(safe_address) - 1))
  129. return EFAULT;
  130. safe_address[sizeof(safe_address) - 1] = '\0';
  131. dbgln<LOCAL_SOCKET_DEBUG>("LocalSocket({}) connect({})", this, safe_address);
  132. auto description_or_error = VFS::the().open(safe_address, O_RDWR, 0, Process::current()->current_directory());
  133. if (description_or_error.is_error())
  134. return ECONNREFUSED;
  135. m_file = move(description_or_error.value());
  136. ASSERT(m_file->inode());
  137. if (!m_file->inode()->socket())
  138. return ECONNREFUSED;
  139. m_address.sun_family = sa_family_copy;
  140. memcpy(m_address.sun_path, safe_address, sizeof(m_address.sun_path));
  141. ASSERT(m_connect_side_fd == &description);
  142. set_connect_side_role(Role::Connecting);
  143. auto peer = m_file->inode()->socket();
  144. auto result = peer->queue_connection_from(*this);
  145. if (result.is_error()) {
  146. set_connect_side_role(Role::None);
  147. return result;
  148. }
  149. if (is_connected()) {
  150. set_connect_side_role(Role::Connected);
  151. return KSuccess;
  152. }
  153. auto unblock_flags = Thread::FileDescriptionBlocker::BlockFlags::None;
  154. if (Thread::current()->block<Thread::ConnectBlocker>({}, description, unblock_flags).was_interrupted()) {
  155. set_connect_side_role(Role::None);
  156. return EINTR;
  157. }
  158. dbgln<LOCAL_SOCKET_DEBUG>("LocalSocket({}) connect({}) status is {}", this, safe_address, to_string(setup_state()));
  159. if (!((u32)unblock_flags & (u32)Thread::FileDescriptionBlocker::BlockFlags::Connect)) {
  160. set_connect_side_role(Role::None);
  161. return ECONNREFUSED;
  162. }
  163. set_connect_side_role(Role::Connected);
  164. return KSuccess;
  165. }
  166. KResult LocalSocket::listen(size_t backlog)
  167. {
  168. LOCKER(lock());
  169. if (type() != SOCK_STREAM)
  170. return EOPNOTSUPP;
  171. set_backlog(backlog);
  172. auto previous_role = m_role;
  173. m_role = Role::Listener;
  174. set_connect_side_role(Role::Listener, previous_role != m_role);
  175. dbgln<LOCAL_SOCKET_DEBUG>("LocalSocket({}) listening with backlog={}", this, backlog);
  176. return KSuccess;
  177. }
  178. KResult LocalSocket::attach(FileDescription& description)
  179. {
  180. ASSERT(!m_accept_side_fd_open);
  181. if (m_connect_side_role == Role::None) {
  182. ASSERT(m_connect_side_fd == nullptr);
  183. m_connect_side_fd = &description;
  184. } else {
  185. ASSERT(m_connect_side_fd != &description);
  186. m_accept_side_fd_open = true;
  187. }
  188. evaluate_block_conditions();
  189. return KSuccess;
  190. }
  191. void LocalSocket::detach(FileDescription& description)
  192. {
  193. if (m_connect_side_fd == &description) {
  194. m_connect_side_fd = nullptr;
  195. } else {
  196. ASSERT(m_accept_side_fd_open);
  197. m_accept_side_fd_open = false;
  198. }
  199. evaluate_block_conditions();
  200. }
  201. bool LocalSocket::can_read(const FileDescription& description, size_t) const
  202. {
  203. auto role = this->role(description);
  204. if (role == Role::Listener)
  205. return can_accept();
  206. if (role == Role::Accepted)
  207. return !has_attached_peer(description) || !m_for_server.is_empty();
  208. if (role == Role::Connected)
  209. return !has_attached_peer(description) || !m_for_client.is_empty();
  210. return false;
  211. }
  212. bool LocalSocket::has_attached_peer(const FileDescription& description) const
  213. {
  214. auto role = this->role(description);
  215. if (role == Role::Accepted)
  216. return m_connect_side_fd != nullptr;
  217. if (role == Role::Connected)
  218. return m_accept_side_fd_open;
  219. ASSERT_NOT_REACHED();
  220. }
  221. bool LocalSocket::can_write(const FileDescription& description, size_t) const
  222. {
  223. auto role = this->role(description);
  224. if (role == Role::Accepted)
  225. return !has_attached_peer(description) || m_for_client.space_for_writing();
  226. if (role == Role::Connected)
  227. return !has_attached_peer(description) || m_for_server.space_for_writing();
  228. return false;
  229. }
  230. KResultOr<size_t> LocalSocket::sendto(FileDescription& description, const UserOrKernelBuffer& data, size_t data_size, int, Userspace<const sockaddr*>, socklen_t)
  231. {
  232. if (!has_attached_peer(description))
  233. return EPIPE;
  234. auto* socket_buffer = send_buffer_for(description);
  235. if (!socket_buffer)
  236. return EINVAL;
  237. ssize_t nwritten = socket_buffer->write(data, data_size);
  238. if (nwritten > 0)
  239. Thread::current()->did_unix_socket_write(nwritten);
  240. return nwritten;
  241. }
  242. DoubleBuffer* LocalSocket::receive_buffer_for(FileDescription& description)
  243. {
  244. auto role = this->role(description);
  245. if (role == Role::Accepted)
  246. return &m_for_server;
  247. if (role == Role::Connected)
  248. return &m_for_client;
  249. return nullptr;
  250. }
  251. DoubleBuffer* LocalSocket::send_buffer_for(FileDescription& description)
  252. {
  253. auto role = this->role(description);
  254. if (role == Role::Connected)
  255. return &m_for_server;
  256. if (role == Role::Accepted)
  257. return &m_for_client;
  258. return nullptr;
  259. }
  260. KResultOr<size_t> LocalSocket::recvfrom(FileDescription& description, UserOrKernelBuffer& buffer, size_t buffer_size, int, Userspace<sockaddr*>, Userspace<socklen_t*>, timeval&)
  261. {
  262. auto* socket_buffer = receive_buffer_for(description);
  263. if (!socket_buffer)
  264. return EINVAL;
  265. if (!description.is_blocking()) {
  266. if (socket_buffer->is_empty()) {
  267. if (!has_attached_peer(description))
  268. return 0;
  269. return EAGAIN;
  270. }
  271. } else if (!can_read(description, 0)) {
  272. auto unblock_flags = Thread::FileDescriptionBlocker::BlockFlags::None;
  273. if (Thread::current()->block<Thread::ReadBlocker>({}, description, unblock_flags).was_interrupted())
  274. return EINTR;
  275. }
  276. if (!has_attached_peer(description) && socket_buffer->is_empty())
  277. return 0;
  278. ASSERT(!socket_buffer->is_empty());
  279. auto nread = socket_buffer->read(buffer, buffer_size);
  280. if (nread > 0)
  281. Thread::current()->did_unix_socket_read(nread);
  282. return nread;
  283. }
  284. StringView LocalSocket::socket_path() const
  285. {
  286. size_t len = strnlen(m_address.sun_path, sizeof(m_address.sun_path));
  287. return { m_address.sun_path, len };
  288. }
  289. String LocalSocket::absolute_path(const FileDescription& description) const
  290. {
  291. StringBuilder builder;
  292. builder.append("socket:");
  293. builder.append(socket_path());
  294. switch (role(description)) {
  295. case Role::Listener:
  296. builder.append(" (listening)");
  297. break;
  298. case Role::Accepted:
  299. builder.appendf(" (accepted from pid %d)", origin_pid());
  300. break;
  301. case Role::Connected:
  302. builder.appendf(" (connected to pid %d)", acceptor_pid());
  303. break;
  304. case Role::Connecting:
  305. builder.append(" (connecting)");
  306. break;
  307. default:
  308. break;
  309. }
  310. return builder.to_string();
  311. }
  312. KResult LocalSocket::getsockopt(FileDescription& description, int level, int option, Userspace<void*> value, Userspace<socklen_t*> value_size)
  313. {
  314. if (level != SOL_SOCKET)
  315. return Socket::getsockopt(description, level, option, value, value_size);
  316. socklen_t size;
  317. if (!copy_from_user(&size, value_size.unsafe_userspace_ptr()))
  318. return EFAULT;
  319. switch (option) {
  320. case SO_PEERCRED: {
  321. if (size < sizeof(ucred))
  322. return EINVAL;
  323. switch (role(description)) {
  324. case Role::Accepted:
  325. if (!copy_to_user(static_ptr_cast<ucred*>(value), &m_origin))
  326. return EFAULT;
  327. size = sizeof(ucred);
  328. if (!copy_to_user(value_size, &size))
  329. return EFAULT;
  330. return KSuccess;
  331. case Role::Connected:
  332. if (!copy_to_user(static_ptr_cast<ucred*>(value), &m_acceptor))
  333. return EFAULT;
  334. size = sizeof(ucred);
  335. if (!copy_to_user(value_size, &size))
  336. return EFAULT;
  337. return KSuccess;
  338. case Role::Connecting:
  339. return ENOTCONN;
  340. default:
  341. return EINVAL;
  342. }
  343. break;
  344. }
  345. default:
  346. return Socket::getsockopt(description, level, option, value, value_size);
  347. }
  348. }
  349. KResult LocalSocket::chmod(FileDescription&, mode_t mode)
  350. {
  351. if (m_file)
  352. return m_file->chmod(mode);
  353. m_prebind_mode = mode & 0777;
  354. return KSuccess;
  355. }
  356. KResult LocalSocket::chown(FileDescription&, uid_t uid, gid_t gid)
  357. {
  358. if (m_file)
  359. return m_file->chown(uid, gid);
  360. auto current_process = Process::current();
  361. if (!current_process->is_superuser() && (current_process->euid() != uid || !current_process->in_group(gid)))
  362. return EPERM;
  363. m_prebind_uid = uid;
  364. m_prebind_gid = gid;
  365. return KSuccess;
  366. }
  367. NonnullRefPtrVector<FileDescription>& LocalSocket::recvfd_queue_for(const FileDescription& description)
  368. {
  369. auto role = this->role(description);
  370. if (role == Role::Connected)
  371. return m_fds_for_client;
  372. if (role == Role::Accepted)
  373. return m_fds_for_server;
  374. ASSERT_NOT_REACHED();
  375. }
  376. NonnullRefPtrVector<FileDescription>& LocalSocket::sendfd_queue_for(const FileDescription& description)
  377. {
  378. auto role = this->role(description);
  379. if (role == Role::Connected)
  380. return m_fds_for_server;
  381. if (role == Role::Accepted)
  382. return m_fds_for_client;
  383. ASSERT_NOT_REACHED();
  384. }
  385. KResult LocalSocket::sendfd(const FileDescription& socket_description, FileDescription& passing_description)
  386. {
  387. LOCKER(lock());
  388. auto role = this->role(socket_description);
  389. if (role != Role::Connected && role != Role::Accepted)
  390. return EINVAL;
  391. auto& queue = sendfd_queue_for(socket_description);
  392. // FIXME: Figure out how we should limit this properly.
  393. if (queue.size() > 16)
  394. return EBUSY;
  395. queue.append(move(passing_description));
  396. return KSuccess;
  397. }
  398. KResultOr<NonnullRefPtr<FileDescription>> LocalSocket::recvfd(const FileDescription& socket_description)
  399. {
  400. LOCKER(lock());
  401. auto role = this->role(socket_description);
  402. if (role != Role::Connected && role != Role::Accepted)
  403. return EINVAL;
  404. auto& queue = recvfd_queue_for(socket_description);
  405. if (queue.is_empty()) {
  406. // FIXME: Figure out the perfect error code for this.
  407. return EAGAIN;
  408. }
  409. return queue.take_first();
  410. }
  411. }