LocalSocket.cpp 15 KB

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