LocalSocket.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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/StringBuilder.h>
  27. #include <Kernel/FileSystem/FileDescription.h>
  28. #include <Kernel/FileSystem/VirtualFileSystem.h>
  29. #include <Kernel/Net/LocalSocket.h>
  30. #include <Kernel/Process.h>
  31. #include <Kernel/UnixTypes.h>
  32. #include <LibBareMetal/StdLib.h>
  33. #include <LibC/errno_numbers.h>
  34. //#define DEBUG_LOCAL_SOCKET
  35. namespace Kernel {
  36. Lockable<InlineLinkedList<LocalSocket>>& LocalSocket::all_sockets()
  37. {
  38. static Lockable<InlineLinkedList<LocalSocket>>* s_list;
  39. if (!s_list)
  40. s_list = new Lockable<InlineLinkedList<LocalSocket>>();
  41. return *s_list;
  42. }
  43. void LocalSocket::for_each(Function<void(LocalSocket&)> callback)
  44. {
  45. LOCKER(all_sockets().lock());
  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. m_prebind_uid = Process::current->uid();
  59. m_prebind_gid = Process::current->gid();
  60. m_prebind_mode = 0666;
  61. #ifdef DEBUG_LOCAL_SOCKET
  62. kprintf("%s(%u) LocalSocket{%p} created with type=%u\n", Process::current->name().characters(), Process::current->pid(), this, 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(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. copy_from_user(&address, user_address, sizeof(sockaddr_un));
  87. if (address.sun_family != AF_LOCAL)
  88. return KResult(-EINVAL);
  89. auto path = String(address.sun_path, strnlen(address.sun_path, sizeof(address.sun_path)));
  90. #ifdef DEBUG_LOCAL_SOCKET
  91. kprintf("%s(%u) LocalSocket{%p} bind(%s)\n", Process::current->name().characters(), Process::current->pid(), this, safe_address);
  92. #endif
  93. mode_t mode = S_IFSOCK | (m_prebind_mode & 04777);
  94. UidAndGid owner { m_prebind_uid, m_prebind_gid };
  95. auto result = VFS::the().open(path, O_CREAT | O_EXCL | O_NOFOLLOW_NOERROR, mode, Process::current->current_directory(), owner);
  96. if (result.is_error()) {
  97. if (result.error() == -EEXIST)
  98. return KResult(-EADDRINUSE);
  99. return result.error();
  100. }
  101. auto file = move(result.value());
  102. ASSERT(file->inode());
  103. if (!file->inode()->bind_socket(*this))
  104. return KResult(-EADDRINUSE);
  105. m_file = move(file);
  106. m_address = address;
  107. m_bound = true;
  108. return KSuccess;
  109. }
  110. KResult LocalSocket::connect(FileDescription& description, const sockaddr* address, socklen_t address_size, ShouldBlock)
  111. {
  112. ASSERT(!m_bound);
  113. if (address_size != sizeof(sockaddr_un))
  114. return KResult(-EINVAL);
  115. if (address->sa_family != AF_LOCAL)
  116. return KResult(-EINVAL);
  117. if (is_connected())
  118. return KResult(-EISCONN);
  119. const sockaddr_un& local_address = *reinterpret_cast<const sockaddr_un*>(address);
  120. char safe_address[sizeof(local_address.sun_path) + 1] = { 0 };
  121. memcpy(safe_address, local_address.sun_path, sizeof(local_address.sun_path));
  122. #ifdef DEBUG_LOCAL_SOCKET
  123. kprintf("%s(%u) LocalSocket{%p} connect(%s)\n", Process::current->name().characters(), Process::current->pid(), this, safe_address);
  124. #endif
  125. auto description_or_error = VFS::the().open(safe_address, O_RDWR, 0, Process::current->current_directory());
  126. if (description_or_error.is_error())
  127. return KResult(-ECONNREFUSED);
  128. m_file = move(description_or_error.value());
  129. ASSERT(m_file->inode());
  130. if (!m_file->inode()->socket())
  131. return KResult(-ECONNREFUSED);
  132. m_address = local_address;
  133. ASSERT(m_connect_side_fd == &description);
  134. m_connect_side_role = Role::Connecting;
  135. auto peer = m_file->inode()->socket();
  136. auto result = peer->queue_connection_from(*this);
  137. if (result.is_error()) {
  138. m_connect_side_role = Role::None;
  139. return result;
  140. }
  141. if (is_connected()) {
  142. m_connect_side_role = Role::Connected;
  143. return KSuccess;
  144. }
  145. if (Thread::current->block<Thread::ConnectBlocker>(description) != Thread::BlockResult::WokeNormally) {
  146. m_connect_side_role = Role::None;
  147. return KResult(-EINTR);
  148. }
  149. #ifdef DEBUG_LOCAL_SOCKET
  150. kprintf("%s(%u) LocalSocket{%p} connect(%s) status is %s\n", Process::current->name().characters(), Process::current->pid(), this, safe_address, to_string(setup_state()));
  151. #endif
  152. if (!is_connected()) {
  153. m_connect_side_role = Role::None;
  154. return KResult(-ECONNREFUSED);
  155. }
  156. m_connect_side_role = Role::Connected;
  157. return KSuccess;
  158. }
  159. KResult LocalSocket::listen(size_t backlog)
  160. {
  161. LOCKER(lock());
  162. if (type() != SOCK_STREAM)
  163. return KResult(-EOPNOTSUPP);
  164. set_backlog(backlog);
  165. m_connect_side_role = m_role = Role::Listener;
  166. #ifdef DEBUG_LOCAL_SOCKET
  167. kprintf("LocalSocket{%p} listening with backlog=%zu\n", this, backlog);
  168. #endif
  169. return KSuccess;
  170. }
  171. void LocalSocket::attach(FileDescription& description)
  172. {
  173. ASSERT(!m_accept_side_fd_open);
  174. if (m_connect_side_role == Role::None) {
  175. ASSERT(m_connect_side_fd == nullptr);
  176. m_connect_side_fd = &description;
  177. } else {
  178. ASSERT(m_connect_side_fd != &description);
  179. m_accept_side_fd_open = true;
  180. }
  181. }
  182. void LocalSocket::detach(FileDescription& description)
  183. {
  184. if (m_connect_side_fd == &description) {
  185. m_connect_side_fd = nullptr;
  186. } else {
  187. ASSERT(m_accept_side_fd_open);
  188. m_accept_side_fd_open = false;
  189. }
  190. }
  191. bool LocalSocket::can_read(const FileDescription& description) const
  192. {
  193. auto role = this->role(description);
  194. if (role == Role::Listener)
  195. return can_accept();
  196. if (role == Role::Accepted)
  197. return !has_attached_peer(description) || !m_for_server.is_empty();
  198. if (role == Role::Connected)
  199. return !has_attached_peer(description) || !m_for_client.is_empty();
  200. return false;
  201. }
  202. bool LocalSocket::has_attached_peer(const FileDescription& description) const
  203. {
  204. auto role = this->role(description);
  205. if (role == Role::Accepted)
  206. return m_connect_side_fd != nullptr;
  207. if (role == Role::Connected)
  208. return m_accept_side_fd_open;
  209. ASSERT_NOT_REACHED();
  210. }
  211. bool LocalSocket::can_write(const FileDescription& description) const
  212. {
  213. auto role = this->role(description);
  214. if (role == Role::Accepted)
  215. return !has_attached_peer(description) || m_for_client.space_for_writing();
  216. if (role == Role::Connected)
  217. return !has_attached_peer(description) || m_for_server.space_for_writing();
  218. return false;
  219. }
  220. ssize_t LocalSocket::sendto(FileDescription& description, const void* data, size_t data_size, int, const sockaddr*, socklen_t)
  221. {
  222. if (!has_attached_peer(description))
  223. return -EPIPE;
  224. ssize_t nwritten = send_buffer_for(description).write((const u8*)data, data_size);
  225. if (nwritten > 0)
  226. Thread::current->did_unix_socket_write(nwritten);
  227. return nwritten;
  228. }
  229. DoubleBuffer& LocalSocket::receive_buffer_for(FileDescription& description)
  230. {
  231. auto role = this->role(description);
  232. if (role == Role::Accepted)
  233. return m_for_server;
  234. if (role == Role::Connected)
  235. return m_for_client;
  236. ASSERT_NOT_REACHED();
  237. }
  238. DoubleBuffer& LocalSocket::send_buffer_for(FileDescription& description)
  239. {
  240. auto role = this->role(description);
  241. if (role == Role::Connected)
  242. return m_for_server;
  243. if (role == Role::Accepted)
  244. return m_for_client;
  245. ASSERT_NOT_REACHED();
  246. }
  247. ssize_t LocalSocket::recvfrom(FileDescription& description, void* buffer, size_t buffer_size, int, sockaddr*, socklen_t*)
  248. {
  249. auto& buffer_for_me = receive_buffer_for(description);
  250. if (!description.is_blocking()) {
  251. if (buffer_for_me.is_empty()) {
  252. if (!has_attached_peer(description))
  253. return 0;
  254. return -EAGAIN;
  255. }
  256. } else if (!can_read(description)) {
  257. auto result = Thread::current->block<Thread::ReadBlocker>(description);
  258. if (result != Thread::BlockResult::WokeNormally)
  259. return -EINTR;
  260. }
  261. if (!has_attached_peer(description) && buffer_for_me.is_empty())
  262. return 0;
  263. ASSERT(!buffer_for_me.is_empty());
  264. int nread = buffer_for_me.read((u8*)buffer, buffer_size);
  265. if (nread > 0)
  266. Thread::current->did_unix_socket_read(nread);
  267. return nread;
  268. }
  269. StringView LocalSocket::socket_path() const
  270. {
  271. size_t len = strnlen(m_address.sun_path, sizeof(m_address.sun_path));
  272. return { m_address.sun_path, len };
  273. }
  274. String LocalSocket::absolute_path(const FileDescription& description) const
  275. {
  276. StringBuilder builder;
  277. builder.append("socket:");
  278. builder.append(socket_path());
  279. switch (role(description)) {
  280. case Role::Listener:
  281. builder.append(" (listening)");
  282. break;
  283. case Role::Accepted:
  284. builder.appendf(" (accepted from pid %d)", origin_pid());
  285. break;
  286. case Role::Connected:
  287. builder.appendf(" (connected to pid %d)", acceptor_pid());
  288. break;
  289. case Role::Connecting:
  290. builder.append(" (connecting)");
  291. break;
  292. default:
  293. break;
  294. }
  295. return builder.to_string();
  296. }
  297. KResult LocalSocket::getsockopt(FileDescription& description, int level, int option, void* value, socklen_t* value_size)
  298. {
  299. if (level != SOL_SOCKET)
  300. return Socket::getsockopt(description, level, option, value, value_size);
  301. switch (option) {
  302. case SO_PEERCRED: {
  303. if (*value_size < sizeof(ucred))
  304. return KResult(-EINVAL);
  305. auto& creds = *(ucred*)value;
  306. switch (role(description)) {
  307. case Role::Accepted:
  308. creds = m_origin;
  309. *value_size = sizeof(ucred);
  310. return KSuccess;
  311. case Role::Connected:
  312. creds = m_acceptor;
  313. *value_size = sizeof(ucred);
  314. return KSuccess;
  315. case Role::Connecting:
  316. return KResult(-ENOTCONN);
  317. default:
  318. return KResult(-EINVAL);
  319. }
  320. break;
  321. }
  322. default:
  323. return Socket::getsockopt(description, level, option, value, value_size);
  324. }
  325. }
  326. KResult LocalSocket::chmod(mode_t mode)
  327. {
  328. if (m_file)
  329. return m_file->chmod(mode);
  330. m_prebind_mode = mode & 04777;
  331. return KSuccess;
  332. }
  333. KResult LocalSocket::chown(uid_t uid, gid_t gid)
  334. {
  335. if (m_file)
  336. return m_file->chown(uid, gid);
  337. if (!Process::current->is_superuser() && (Process::current->euid() != uid || !Process::current->in_group(gid)))
  338. return KResult(-EPERM);
  339. m_prebind_uid = uid;
  340. m_prebind_gid = gid;
  341. return KSuccess;
  342. }
  343. }