LocalSocket.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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/StdLib.h>
  32. #include <Kernel/UnixTypes.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(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. #ifdef DEBUG_LOCAL_SOCKET
  63. dbg() << "LocalSocket{" << this << "} created with type=" << type;
  64. #endif
  65. }
  66. LocalSocket::~LocalSocket()
  67. {
  68. LOCKER(all_sockets().lock());
  69. all_sockets().resource().remove(this);
  70. }
  71. void LocalSocket::get_local_address(sockaddr* address, socklen_t* address_size)
  72. {
  73. size_t bytes_to_copy = min(static_cast<size_t>(*address_size), sizeof(sockaddr_un));
  74. memcpy(address, &m_address, bytes_to_copy);
  75. *address_size = sizeof(sockaddr_un);
  76. }
  77. void LocalSocket::get_peer_address(sockaddr* address, socklen_t* address_size)
  78. {
  79. get_local_address(address, address_size);
  80. }
  81. KResult LocalSocket::bind(const sockaddr* user_address, socklen_t address_size)
  82. {
  83. ASSERT(setup_state() == SetupState::Unstarted);
  84. if (address_size != sizeof(sockaddr_un))
  85. return KResult(-EINVAL);
  86. sockaddr_un address;
  87. copy_from_user(&address, user_address, sizeof(sockaddr_un));
  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(" << safe_address << ")";
  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, 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. if (address->sa_family != AF_LOCAL)
  117. return KResult(-EINVAL);
  118. if (is_connected())
  119. return KResult(-EISCONN);
  120. const sockaddr_un& local_address = *reinterpret_cast<const sockaddr_un*>(address);
  121. char safe_address[sizeof(local_address.sun_path) + 1] = { 0 };
  122. memcpy(safe_address, local_address.sun_path, sizeof(local_address.sun_path));
  123. #ifdef DEBUG_LOCAL_SOCKET
  124. dbg() << "LocalSocket{" << this << "} connect(" << safe_address << ")";
  125. #endif
  126. auto description_or_error = VFS::the().open(safe_address, O_RDWR, 0, Process::current()->current_directory());
  127. if (description_or_error.is_error())
  128. return KResult(-ECONNREFUSED);
  129. m_file = move(description_or_error.value());
  130. ASSERT(m_file->inode());
  131. if (!m_file->inode()->socket())
  132. return KResult(-ECONNREFUSED);
  133. m_address = local_address;
  134. ASSERT(m_connect_side_fd == &description);
  135. m_connect_side_role = Role::Connecting;
  136. auto peer = m_file->inode()->socket();
  137. auto result = peer->queue_connection_from(*this);
  138. if (result.is_error()) {
  139. m_connect_side_role = Role::None;
  140. return result;
  141. }
  142. if (is_connected()) {
  143. m_connect_side_role = Role::Connected;
  144. return KSuccess;
  145. }
  146. if (Thread::current()->block<Thread::ConnectBlocker>(nullptr, description).was_interrupted()) {
  147. m_connect_side_role = Role::None;
  148. return KResult(-EINTR);
  149. }
  150. #ifdef DEBUG_LOCAL_SOCKET
  151. dbg() << "LocalSocket{" << this << "} connect(" << safe_address << ") status is " << to_string(setup_state());
  152. #endif
  153. if (!is_connected()) {
  154. m_connect_side_role = Role::None;
  155. return KResult(-ECONNREFUSED);
  156. }
  157. m_connect_side_role = Role::Connected;
  158. return KSuccess;
  159. }
  160. KResult LocalSocket::listen(size_t backlog)
  161. {
  162. LOCKER(lock());
  163. if (type() != SOCK_STREAM)
  164. return KResult(-EOPNOTSUPP);
  165. set_backlog(backlog);
  166. m_connect_side_role = m_role = Role::Listener;
  167. #ifdef DEBUG_LOCAL_SOCKET
  168. dbg() << "LocalSocket{" << this << "} listening with backlog=" << backlog;
  169. #endif
  170. return KSuccess;
  171. }
  172. void LocalSocket::attach(FileDescription& description)
  173. {
  174. ASSERT(!m_accept_side_fd_open);
  175. if (m_connect_side_role == Role::None) {
  176. ASSERT(m_connect_side_fd == nullptr);
  177. m_connect_side_fd = &description;
  178. } else {
  179. ASSERT(m_connect_side_fd != &description);
  180. m_accept_side_fd_open = true;
  181. }
  182. }
  183. void LocalSocket::detach(FileDescription& description)
  184. {
  185. if (m_connect_side_fd == &description) {
  186. m_connect_side_fd = nullptr;
  187. } else {
  188. ASSERT(m_accept_side_fd_open);
  189. m_accept_side_fd_open = false;
  190. }
  191. }
  192. bool LocalSocket::can_read(const FileDescription& description, size_t) const
  193. {
  194. auto role = this->role(description);
  195. if (role == Role::Listener)
  196. return can_accept();
  197. if (role == Role::Accepted)
  198. return !has_attached_peer(description) || !m_for_server.is_empty();
  199. if (role == Role::Connected)
  200. return !has_attached_peer(description) || !m_for_client.is_empty();
  201. return false;
  202. }
  203. bool LocalSocket::has_attached_peer(const FileDescription& description) const
  204. {
  205. auto role = this->role(description);
  206. if (role == Role::Accepted)
  207. return m_connect_side_fd != nullptr;
  208. if (role == Role::Connected)
  209. return m_accept_side_fd_open;
  210. ASSERT_NOT_REACHED();
  211. }
  212. bool LocalSocket::can_write(const FileDescription& description, size_t) const
  213. {
  214. auto role = this->role(description);
  215. if (role == Role::Accepted)
  216. return !has_attached_peer(description) || m_for_client.space_for_writing();
  217. if (role == Role::Connected)
  218. return !has_attached_peer(description) || m_for_server.space_for_writing();
  219. return false;
  220. }
  221. ssize_t LocalSocket::sendto(FileDescription& description, const void* data, size_t data_size, int, const sockaddr*, socklen_t)
  222. {
  223. if (!has_attached_peer(description))
  224. return -EPIPE;
  225. ssize_t nwritten = send_buffer_for(description).write((const u8*)data, data_size);
  226. if (nwritten > 0)
  227. Thread::current()->did_unix_socket_write(nwritten);
  228. return nwritten;
  229. }
  230. DoubleBuffer& LocalSocket::receive_buffer_for(FileDescription& description)
  231. {
  232. auto role = this->role(description);
  233. if (role == Role::Accepted)
  234. return m_for_server;
  235. if (role == Role::Connected)
  236. return m_for_client;
  237. ASSERT_NOT_REACHED();
  238. }
  239. DoubleBuffer& LocalSocket::send_buffer_for(FileDescription& description)
  240. {
  241. auto role = this->role(description);
  242. if (role == Role::Connected)
  243. return m_for_server;
  244. if (role == Role::Accepted)
  245. return m_for_client;
  246. ASSERT_NOT_REACHED();
  247. }
  248. ssize_t LocalSocket::recvfrom(FileDescription& description, void* buffer, size_t buffer_size, int, sockaddr*, socklen_t*)
  249. {
  250. auto& buffer_for_me = receive_buffer_for(description);
  251. if (!description.is_blocking()) {
  252. if (buffer_for_me.is_empty()) {
  253. if (!has_attached_peer(description))
  254. return 0;
  255. return -EAGAIN;
  256. }
  257. } else if (!can_read(description, 0)) {
  258. if (Thread::current()->block<Thread::ReadBlocker>(nullptr, description).was_interrupted())
  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(FileDescription&, 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(FileDescription&, uid_t uid, gid_t gid)
  334. {
  335. if (m_file)
  336. return m_file->chown(uid, gid);
  337. auto current_process = Process::current();
  338. if (!current_process->is_superuser() && (current_process->euid() != uid || !current_process->in_group(gid)))
  339. return KResult(-EPERM);
  340. m_prebind_uid = uid;
  341. m_prebind_gid = gid;
  342. return KSuccess;
  343. }
  344. NonnullRefPtrVector<FileDescription>& LocalSocket::recvfd_queue_for(const FileDescription& description)
  345. {
  346. auto role = this->role(description);
  347. if (role == Role::Connected)
  348. return m_fds_for_client;
  349. if (role == Role::Accepted)
  350. return m_fds_for_server;
  351. ASSERT_NOT_REACHED();
  352. }
  353. NonnullRefPtrVector<FileDescription>& LocalSocket::sendfd_queue_for(const FileDescription& description)
  354. {
  355. auto role = this->role(description);
  356. if (role == Role::Connected)
  357. return m_fds_for_server;
  358. if (role == Role::Accepted)
  359. return m_fds_for_client;
  360. ASSERT_NOT_REACHED();
  361. }
  362. KResult LocalSocket::sendfd(const FileDescription& socket_description, FileDescription& passing_description)
  363. {
  364. LOCKER(lock());
  365. auto role = this->role(socket_description);
  366. if (role != Role::Connected && role != Role::Accepted)
  367. return KResult(-EINVAL);
  368. auto& queue = sendfd_queue_for(socket_description);
  369. // FIXME: Figure out how we should limit this properly.
  370. if (queue.size() > 16)
  371. return KResult(-EBUSY);
  372. queue.append(move(passing_description));
  373. return KSuccess;
  374. }
  375. KResultOr<NonnullRefPtr<FileDescription>> LocalSocket::recvfd(const FileDescription& socket_description)
  376. {
  377. LOCKER(lock());
  378. auto role = this->role(socket_description);
  379. if (role != Role::Connected && role != Role::Accepted)
  380. return KResult(-EINVAL);
  381. auto& queue = recvfd_queue_for(socket_description);
  382. if (queue.is_empty()) {
  383. // FIXME: Figure out the perfect error code for this.
  384. return KResult(-EAGAIN);
  385. }
  386. return queue.take_first();
  387. }
  388. }