LocalSocket.cpp 15 KB

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