LocalSocket.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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/FileSystem/FileDescription.h>
  29. #include <Kernel/FileSystem/VirtualFileSystem.h>
  30. #include <Kernel/Net/LocalSocket.h>
  31. #include <Kernel/Process.h>
  32. #include <Kernel/StdLib.h>
  33. #include <Kernel/UnixTypes.h>
  34. #include <LibC/errno_numbers.h>
  35. //#define DEBUG_LOCAL_SOCKET
  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->uid();
  59. m_prebind_gid = current_process->gid();
  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. #ifdef DEBUG_LOCAL_SOCKET
  68. dbg() << "LocalSocket{" << this << "} created with type=" << type;
  69. #endif
  70. }
  71. LocalSocket::~LocalSocket()
  72. {
  73. LOCKER(all_sockets().lock());
  74. all_sockets().resource().remove(this);
  75. }
  76. void LocalSocket::get_local_address(sockaddr* address, socklen_t* address_size)
  77. {
  78. size_t bytes_to_copy = min(static_cast<size_t>(*address_size), sizeof(sockaddr_un));
  79. memcpy(address, &m_address, bytes_to_copy);
  80. *address_size = sizeof(sockaddr_un);
  81. }
  82. void LocalSocket::get_peer_address(sockaddr* address, socklen_t* address_size)
  83. {
  84. get_local_address(address, address_size);
  85. }
  86. KResult LocalSocket::bind(Userspace<const sockaddr*> user_address, socklen_t address_size)
  87. {
  88. ASSERT(setup_state() == SetupState::Unstarted);
  89. if (address_size != sizeof(sockaddr_un))
  90. return KResult(-EINVAL);
  91. sockaddr_un address;
  92. if (!copy_from_user(&address, user_address, sizeof(sockaddr_un)))
  93. return KResult(-EFAULT);
  94. if (address.sun_family != AF_LOCAL)
  95. return KResult(-EINVAL);
  96. auto path = String(address.sun_path, strnlen(address.sun_path, sizeof(address.sun_path)));
  97. #ifdef DEBUG_LOCAL_SOCKET
  98. dbg() << "LocalSocket{" << this << "} bind(" << path << ")";
  99. #endif
  100. mode_t mode = S_IFSOCK | (m_prebind_mode & 04777);
  101. UidAndGid owner { m_prebind_uid, m_prebind_gid };
  102. auto result = VFS::the().open(path, O_CREAT | O_EXCL | O_NOFOLLOW_NOERROR, mode, Process::current()->current_directory(), owner);
  103. if (result.is_error()) {
  104. if (result.error() == -EEXIST)
  105. return KResult(-EADDRINUSE);
  106. return result.error();
  107. }
  108. auto file = move(result.value());
  109. ASSERT(file->inode());
  110. if (!file->inode()->bind_socket(*this))
  111. return KResult(-EADDRINUSE);
  112. m_file = move(file);
  113. m_address = address;
  114. m_bound = true;
  115. return KSuccess;
  116. }
  117. KResult LocalSocket::connect(FileDescription& description, Userspace<const sockaddr*> address, socklen_t address_size, ShouldBlock)
  118. {
  119. ASSERT(!m_bound);
  120. if (address_size != sizeof(sockaddr_un))
  121. return KResult(-EINVAL);
  122. u16 sa_family_copy;
  123. auto* user_address = reinterpret_cast<const sockaddr*>(address.unsafe_userspace_ptr());
  124. if (!copy_from_user(&sa_family_copy, &user_address->sa_family, sizeof(u16)))
  125. return KResult(-EFAULT);
  126. if (sa_family_copy != AF_LOCAL)
  127. return KResult(-EINVAL);
  128. if (is_connected())
  129. return KResult(-EISCONN);
  130. const auto& local_address = *reinterpret_cast<const sockaddr_un*>(user_address);
  131. char safe_address[sizeof(local_address.sun_path) + 1] = { 0 };
  132. if (!copy_from_user(&safe_address[0], &local_address.sun_path[0], sizeof(safe_address) - 1))
  133. return KResult(-EFAULT);
  134. safe_address[sizeof(safe_address) - 1] = '\0';
  135. #ifdef DEBUG_LOCAL_SOCKET
  136. dbg() << "LocalSocket{" << this << "} connect(" << safe_address << ")";
  137. #endif
  138. auto description_or_error = VFS::the().open(safe_address, O_RDWR, 0, Process::current()->current_directory());
  139. if (description_or_error.is_error())
  140. return KResult(-ECONNREFUSED);
  141. m_file = move(description_or_error.value());
  142. ASSERT(m_file->inode());
  143. if (!m_file->inode()->socket())
  144. return KResult(-ECONNREFUSED);
  145. m_address.sun_family = sa_family_copy;
  146. memcpy(m_address.sun_path, safe_address, sizeof(m_address.sun_path));
  147. ASSERT(m_connect_side_fd == &description);
  148. set_connect_side_role(Role::Connecting);
  149. auto peer = m_file->inode()->socket();
  150. auto result = peer->queue_connection_from(*this);
  151. if (result.is_error()) {
  152. set_connect_side_role(Role::None);
  153. return result;
  154. }
  155. if (is_connected()) {
  156. set_connect_side_role(Role::Connected);
  157. return KSuccess;
  158. }
  159. auto unblock_flags = Thread::FileDescriptionBlocker::BlockFlags::None;
  160. if (Thread::current()->block<Thread::ConnectBlocker>(nullptr, description, unblock_flags).was_interrupted()) {
  161. set_connect_side_role(Role::None);
  162. return KResult(-EINTR);
  163. }
  164. #ifdef DEBUG_LOCAL_SOCKET
  165. dbg() << "LocalSocket{" << this << "} connect(" << safe_address << ") status is " << to_string(setup_state());
  166. #endif
  167. if (!((u32)unblock_flags & (u32)Thread::FileDescriptionBlocker::BlockFlags::Connect)) {
  168. set_connect_side_role(Role::None);
  169. return KResult(-ECONNREFUSED);
  170. }
  171. set_connect_side_role(Role::Connected);
  172. return KSuccess;
  173. }
  174. KResult LocalSocket::listen(size_t backlog)
  175. {
  176. LOCKER(lock());
  177. if (type() != SOCK_STREAM)
  178. return KResult(-EOPNOTSUPP);
  179. set_backlog(backlog);
  180. auto previous_role = m_role;
  181. m_role = Role::Listener;
  182. set_connect_side_role(Role::Listener, previous_role != m_role);
  183. #ifdef DEBUG_LOCAL_SOCKET
  184. dbg() << "LocalSocket{" << this << "} listening with backlog=" << backlog;
  185. #endif
  186. return KSuccess;
  187. }
  188. void LocalSocket::attach(FileDescription& description)
  189. {
  190. ASSERT(!m_accept_side_fd_open);
  191. if (m_connect_side_role == Role::None) {
  192. ASSERT(m_connect_side_fd == nullptr);
  193. m_connect_side_fd = &description;
  194. } else {
  195. ASSERT(m_connect_side_fd != &description);
  196. m_accept_side_fd_open = true;
  197. }
  198. evaluate_block_conditions();
  199. }
  200. void LocalSocket::detach(FileDescription& description)
  201. {
  202. if (m_connect_side_fd == &description) {
  203. m_connect_side_fd = nullptr;
  204. } else {
  205. ASSERT(m_accept_side_fd_open);
  206. m_accept_side_fd_open = false;
  207. }
  208. evaluate_block_conditions();
  209. }
  210. bool LocalSocket::can_read(const FileDescription& description, size_t) const
  211. {
  212. auto role = this->role(description);
  213. if (role == Role::Listener)
  214. return can_accept();
  215. if (role == Role::Accepted)
  216. return !has_attached_peer(description) || !m_for_server.is_empty();
  217. if (role == Role::Connected)
  218. return !has_attached_peer(description) || !m_for_client.is_empty();
  219. return false;
  220. }
  221. bool LocalSocket::has_attached_peer(const FileDescription& description) const
  222. {
  223. auto role = this->role(description);
  224. if (role == Role::Accepted)
  225. return m_connect_side_fd != nullptr;
  226. if (role == Role::Connected)
  227. return m_accept_side_fd_open;
  228. ASSERT_NOT_REACHED();
  229. }
  230. bool LocalSocket::can_write(const FileDescription& description, size_t) const
  231. {
  232. auto role = this->role(description);
  233. if (role == Role::Accepted)
  234. return !has_attached_peer(description) || m_for_client.space_for_writing();
  235. if (role == Role::Connected)
  236. return !has_attached_peer(description) || m_for_server.space_for_writing();
  237. return false;
  238. }
  239. KResultOr<size_t> LocalSocket::sendto(FileDescription& description, const UserOrKernelBuffer& data, size_t data_size, int, Userspace<const sockaddr*>, socklen_t)
  240. {
  241. if (!has_attached_peer(description))
  242. return KResult(-EPIPE);
  243. auto* socket_buffer = send_buffer_for(description);
  244. if (!socket_buffer)
  245. return KResult(-EINVAL);
  246. ssize_t nwritten = socket_buffer->write(data, data_size);
  247. if (nwritten > 0)
  248. Thread::current()->did_unix_socket_write(nwritten);
  249. return nwritten;
  250. }
  251. DoubleBuffer* LocalSocket::receive_buffer_for(FileDescription& description)
  252. {
  253. auto role = this->role(description);
  254. if (role == Role::Accepted)
  255. return &m_for_server;
  256. if (role == Role::Connected)
  257. return &m_for_client;
  258. return nullptr;
  259. }
  260. DoubleBuffer* LocalSocket::send_buffer_for(FileDescription& description)
  261. {
  262. auto role = this->role(description);
  263. if (role == Role::Connected)
  264. return &m_for_server;
  265. if (role == Role::Accepted)
  266. return &m_for_client;
  267. return nullptr;
  268. }
  269. KResultOr<size_t> LocalSocket::recvfrom(FileDescription& description, UserOrKernelBuffer& buffer, size_t buffer_size, int, Userspace<sockaddr*>, Userspace<socklen_t*>, timeval&)
  270. {
  271. auto* socket_buffer = receive_buffer_for(description);
  272. if (!socket_buffer)
  273. return KResult(-EINVAL);
  274. if (!description.is_blocking()) {
  275. if (socket_buffer->is_empty()) {
  276. if (!has_attached_peer(description))
  277. return 0;
  278. return KResult(-EAGAIN);
  279. }
  280. } else if (!can_read(description, 0)) {
  281. auto unblock_flags = Thread::FileDescriptionBlocker::BlockFlags::None;
  282. if (Thread::current()->block<Thread::ReadBlocker>(nullptr, description, unblock_flags).was_interrupted())
  283. return KResult(-EINTR);
  284. }
  285. if (!has_attached_peer(description) && socket_buffer->is_empty())
  286. return 0;
  287. ASSERT(!socket_buffer->is_empty());
  288. auto nread = socket_buffer->read(buffer, buffer_size);
  289. if (nread > 0)
  290. Thread::current()->did_unix_socket_read(nread);
  291. return nread;
  292. }
  293. StringView LocalSocket::socket_path() const
  294. {
  295. size_t len = strnlen(m_address.sun_path, sizeof(m_address.sun_path));
  296. return { m_address.sun_path, len };
  297. }
  298. String LocalSocket::absolute_path(const FileDescription& description) const
  299. {
  300. StringBuilder builder;
  301. builder.append("socket:");
  302. builder.append(socket_path());
  303. switch (role(description)) {
  304. case Role::Listener:
  305. builder.append(" (listening)");
  306. break;
  307. case Role::Accepted:
  308. builder.appendf(" (accepted from pid %d)", origin_pid());
  309. break;
  310. case Role::Connected:
  311. builder.appendf(" (connected to pid %d)", acceptor_pid());
  312. break;
  313. case Role::Connecting:
  314. builder.append(" (connecting)");
  315. break;
  316. default:
  317. break;
  318. }
  319. return builder.to_string();
  320. }
  321. KResult LocalSocket::getsockopt(FileDescription& description, int level, int option, Userspace<void*> value, Userspace<socklen_t*> value_size)
  322. {
  323. if (level != SOL_SOCKET)
  324. return Socket::getsockopt(description, level, option, value, value_size);
  325. socklen_t size;
  326. if (!copy_from_user(&size, value_size.unsafe_userspace_ptr()))
  327. return KResult(-EFAULT);
  328. switch (option) {
  329. case SO_PEERCRED: {
  330. if (size < sizeof(ucred))
  331. return KResult(-EINVAL);
  332. switch (role(description)) {
  333. case Role::Accepted:
  334. if (!copy_to_user(static_ptr_cast<ucred*>(value), &m_origin))
  335. return KResult(-EFAULT);
  336. size = sizeof(ucred);
  337. if (!copy_to_user(value_size, &size))
  338. return KResult(-EFAULT);
  339. return KSuccess;
  340. case Role::Connected:
  341. if (!copy_to_user(static_ptr_cast<ucred*>(value), &m_acceptor))
  342. return KResult(-EFAULT);
  343. size = sizeof(ucred);
  344. if (!copy_to_user(value_size, &size))
  345. return KResult(-EFAULT);
  346. return KSuccess;
  347. case Role::Connecting:
  348. return KResult(-ENOTCONN);
  349. default:
  350. return KResult(-EINVAL);
  351. }
  352. break;
  353. }
  354. default:
  355. return Socket::getsockopt(description, level, option, value, value_size);
  356. }
  357. }
  358. KResult LocalSocket::chmod(FileDescription&, mode_t mode)
  359. {
  360. if (m_file)
  361. return m_file->chmod(mode);
  362. m_prebind_mode = mode & 04777;
  363. return KSuccess;
  364. }
  365. KResult LocalSocket::chown(FileDescription&, uid_t uid, gid_t gid)
  366. {
  367. if (m_file)
  368. return m_file->chown(uid, gid);
  369. auto current_process = Process::current();
  370. if (!current_process->is_superuser() && (current_process->euid() != uid || !current_process->in_group(gid)))
  371. return KResult(-EPERM);
  372. m_prebind_uid = uid;
  373. m_prebind_gid = gid;
  374. return KSuccess;
  375. }
  376. NonnullRefPtrVector<FileDescription>& LocalSocket::recvfd_queue_for(const FileDescription& description)
  377. {
  378. auto role = this->role(description);
  379. if (role == Role::Connected)
  380. return m_fds_for_client;
  381. if (role == Role::Accepted)
  382. return m_fds_for_server;
  383. ASSERT_NOT_REACHED();
  384. }
  385. NonnullRefPtrVector<FileDescription>& LocalSocket::sendfd_queue_for(const FileDescription& description)
  386. {
  387. auto role = this->role(description);
  388. if (role == Role::Connected)
  389. return m_fds_for_server;
  390. if (role == Role::Accepted)
  391. return m_fds_for_client;
  392. ASSERT_NOT_REACHED();
  393. }
  394. KResult LocalSocket::sendfd(const FileDescription& socket_description, FileDescription& passing_description)
  395. {
  396. LOCKER(lock());
  397. auto role = this->role(socket_description);
  398. if (role != Role::Connected && role != Role::Accepted)
  399. return KResult(-EINVAL);
  400. auto& queue = sendfd_queue_for(socket_description);
  401. // FIXME: Figure out how we should limit this properly.
  402. if (queue.size() > 16)
  403. return KResult(-EBUSY);
  404. queue.append(move(passing_description));
  405. return KSuccess;
  406. }
  407. KResultOr<NonnullRefPtr<FileDescription>> LocalSocket::recvfd(const FileDescription& socket_description)
  408. {
  409. LOCKER(lock());
  410. auto role = this->role(socket_description);
  411. if (role != Role::Connected && role != Role::Accepted)
  412. return KResult(-EINVAL);
  413. auto& queue = recvfd_queue_for(socket_description);
  414. if (queue.is_empty()) {
  415. // FIXME: Figure out the perfect error code for this.
  416. return KResult(-EAGAIN);
  417. }
  418. return queue.take_first();
  419. }
  420. }