Socket.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/StringView.h>
  7. #include <Kernel/API/POSIX/errno.h>
  8. #include <Kernel/Debug.h>
  9. #include <Kernel/FileSystem/OpenFileDescription.h>
  10. #include <Kernel/Net/IPv4Socket.h>
  11. #include <Kernel/Net/LocalSocket.h>
  12. #include <Kernel/Net/NetworkingManagement.h>
  13. #include <Kernel/Net/Socket.h>
  14. #include <Kernel/Process.h>
  15. #include <Kernel/UnixTypes.h>
  16. namespace Kernel {
  17. ErrorOr<NonnullRefPtr<Socket>> Socket::create(int domain, int type, int protocol)
  18. {
  19. switch (domain) {
  20. case AF_LOCAL:
  21. return TRY(LocalSocket::try_create(type & SOCK_TYPE_MASK));
  22. case AF_INET:
  23. return IPv4Socket::create(type & SOCK_TYPE_MASK, protocol);
  24. default:
  25. return EAFNOSUPPORT;
  26. }
  27. }
  28. Socket::Socket(int domain, int type, int protocol)
  29. : m_domain(domain)
  30. , m_type(type)
  31. , m_protocol(protocol)
  32. {
  33. set_origin(Process::current());
  34. }
  35. Socket::~Socket() = default;
  36. void Socket::set_setup_state(SetupState new_setup_state)
  37. {
  38. dbgln_if(SOCKET_DEBUG, "Socket({}) setup state moving from {} to {}", this, to_string(m_setup_state), to_string(new_setup_state));
  39. m_setup_state = new_setup_state;
  40. evaluate_block_conditions();
  41. }
  42. RefPtr<Socket> Socket::accept()
  43. {
  44. MutexLocker locker(mutex());
  45. if (m_pending.is_empty())
  46. return nullptr;
  47. dbgln_if(SOCKET_DEBUG, "Socket({}) de-queueing connection", this);
  48. auto client = m_pending.take_first();
  49. VERIFY(!client->is_connected());
  50. auto& process = Process::current();
  51. client->set_acceptor(process);
  52. client->m_connected = true;
  53. client->set_role(Role::Accepted);
  54. if (!m_pending.is_empty())
  55. evaluate_block_conditions();
  56. return client;
  57. }
  58. ErrorOr<void> Socket::queue_connection_from(NonnullRefPtr<Socket> peer)
  59. {
  60. dbgln_if(SOCKET_DEBUG, "Socket({}) queueing connection", this);
  61. MutexLocker locker(mutex());
  62. if (m_pending.size() >= m_backlog)
  63. return set_so_error(ECONNREFUSED);
  64. SOCKET_TRY(m_pending.try_append(move(peer)));
  65. evaluate_block_conditions();
  66. return {};
  67. }
  68. ErrorOr<void> Socket::setsockopt(int level, int option, Userspace<void const*> user_value, socklen_t user_value_size)
  69. {
  70. MutexLocker locker(mutex());
  71. if (level != SOL_SOCKET)
  72. return ENOPROTOOPT;
  73. VERIFY(level == SOL_SOCKET);
  74. switch (option) {
  75. case SO_SNDTIMEO:
  76. if (user_value_size != sizeof(timeval))
  77. return EINVAL;
  78. m_send_timeout = TRY(copy_time_from_user(static_ptr_cast<timeval const*>(user_value)));
  79. return {};
  80. case SO_RCVTIMEO:
  81. if (user_value_size != sizeof(timeval))
  82. return EINVAL;
  83. m_receive_timeout = TRY(copy_time_from_user(static_ptr_cast<timeval const*>(user_value)));
  84. return {};
  85. case SO_BINDTODEVICE: {
  86. if (user_value_size != IFNAMSIZ)
  87. return EINVAL;
  88. auto user_string = static_ptr_cast<char const*>(user_value);
  89. auto ifname = TRY(try_copy_kstring_from_user(user_string, user_value_size));
  90. auto device = NetworkingManagement::the().lookup_by_name(ifname->view());
  91. if (!device)
  92. return ENODEV;
  93. m_bound_interface.with([&device](auto& bound_device) {
  94. bound_device = move(device);
  95. });
  96. return {};
  97. }
  98. case SO_DEBUG:
  99. // NOTE: This is supposed to toggle collection of debugging information on/off, we don't have any right now, so this is a no-op.
  100. return {};
  101. case SO_KEEPALIVE:
  102. // FIXME: Obviously, this is not a real keepalive.
  103. return {};
  104. case SO_TIMESTAMP:
  105. if (user_value_size != sizeof(int))
  106. return EINVAL;
  107. m_timestamp = TRY(copy_typed_from_user(static_ptr_cast<int const*>(user_value)));
  108. if (m_timestamp != 0 && (domain() != AF_INET || type() == SOCK_STREAM)) {
  109. // FIXME: Support SO_TIMESTAMP for more protocols?
  110. m_timestamp = 0;
  111. return ENOTSUP;
  112. }
  113. return {};
  114. case SO_DONTROUTE: {
  115. if (user_value_size != sizeof(int))
  116. return EINVAL;
  117. m_routing_disabled = TRY(copy_typed_from_user(static_ptr_cast<int const*>(user_value))) != 0;
  118. return {};
  119. }
  120. case SO_REUSEADDR:
  121. dbgln("FIXME: SO_REUSEADDR requested, but not implemented.");
  122. return {};
  123. default:
  124. dbgln("setsockopt({}) at SOL_SOCKET not implemented.", option);
  125. return ENOPROTOOPT;
  126. }
  127. }
  128. ErrorOr<void> Socket::getsockopt(OpenFileDescription&, int level, int option, Userspace<void*> value, Userspace<socklen_t*> value_size)
  129. {
  130. MutexLocker locker(mutex());
  131. socklen_t size;
  132. TRY(copy_from_user(&size, value_size.unsafe_userspace_ptr()));
  133. // FIXME: Add TCP_NODELAY, IPPROTO_TCP and IPPROTO_IP (used in OpenSSH)
  134. if (level != SOL_SOCKET) {
  135. // Not sure if this is the correct error code, but it's only temporary until other levels are implemented.
  136. return ENOPROTOOPT;
  137. }
  138. switch (option) {
  139. case SO_SNDTIMEO:
  140. if (size < sizeof(timeval))
  141. return EINVAL;
  142. {
  143. timeval tv = m_send_timeout.to_timeval();
  144. TRY(copy_to_user(static_ptr_cast<timeval*>(value), &tv));
  145. }
  146. size = sizeof(timeval);
  147. return copy_to_user(value_size, &size);
  148. case SO_RCVTIMEO:
  149. if (size < sizeof(timeval))
  150. return EINVAL;
  151. {
  152. timeval tv = m_receive_timeout.to_timeval();
  153. TRY(copy_to_user(static_ptr_cast<timeval*>(value), &tv));
  154. }
  155. size = sizeof(timeval);
  156. return copy_to_user(value_size, &size);
  157. case SO_ERROR: {
  158. if (size < sizeof(int))
  159. return EINVAL;
  160. return so_error().with([&size, value, value_size](auto& error) -> ErrorOr<void> {
  161. int errno = 0;
  162. if (error.has_value())
  163. errno = error.value();
  164. TRY(copy_to_user(static_ptr_cast<int*>(value), &errno));
  165. size = sizeof(int);
  166. TRY(copy_to_user(value_size, &size));
  167. error = {};
  168. return {};
  169. });
  170. }
  171. case SO_BINDTODEVICE:
  172. if (size < IFNAMSIZ)
  173. return EINVAL;
  174. return m_bound_interface.with([&](auto& bound_device) -> ErrorOr<void> {
  175. if (bound_device) {
  176. auto name = bound_device->name();
  177. auto length = name.length() + 1;
  178. auto characters = name.characters_without_null_termination();
  179. TRY(copy_to_user(static_ptr_cast<char*>(value), characters, length));
  180. size = length;
  181. return copy_to_user(value_size, &size);
  182. } else {
  183. size = 0;
  184. TRY(copy_to_user(value_size, &size));
  185. // FIXME: This return value looks suspicious.
  186. return EFAULT;
  187. }
  188. });
  189. case SO_TIMESTAMP:
  190. if (size < sizeof(int))
  191. return EINVAL;
  192. TRY(copy_to_user(static_ptr_cast<int*>(value), &m_timestamp));
  193. size = sizeof(int);
  194. return copy_to_user(value_size, &size);
  195. case SO_TYPE:
  196. if (size < sizeof(int))
  197. return EINVAL;
  198. TRY(copy_to_user(static_ptr_cast<int*>(value), &m_type));
  199. size = sizeof(int);
  200. return copy_to_user(value_size, &size);
  201. case SO_DEBUG:
  202. // NOTE: This is supposed to toggle collection of debugging information on/off, we don't have any right now, so we just claim it's always off.
  203. if (size < sizeof(int))
  204. return EINVAL;
  205. TRY(memset_user(value.unsafe_userspace_ptr(), 0, sizeof(int)));
  206. size = sizeof(int);
  207. return copy_to_user(value_size, &size);
  208. case SO_ACCEPTCONN: {
  209. int accepting_connections = (m_role == Role::Listener) ? 1 : 0;
  210. if (size < sizeof(accepting_connections))
  211. return EINVAL;
  212. TRY(copy_to_user(static_ptr_cast<int*>(value), &accepting_connections));
  213. size = sizeof(accepting_connections);
  214. return copy_to_user(value_size, &size);
  215. }
  216. case SO_DONTROUTE: {
  217. int routing_disabled = m_routing_disabled ? 1 : 0;
  218. if (size < sizeof(routing_disabled))
  219. return EINVAL;
  220. TRY(copy_to_user(static_ptr_cast<int*>(value), &routing_disabled));
  221. size = sizeof(routing_disabled);
  222. return copy_to_user(value_size, &size);
  223. }
  224. default:
  225. dbgln("getsockopt({}) at SOL_SOCKET not implemented.", option);
  226. return ENOPROTOOPT;
  227. }
  228. }
  229. ErrorOr<size_t> Socket::read(OpenFileDescription& description, u64, UserOrKernelBuffer& buffer, size_t size)
  230. {
  231. if (is_shut_down_for_reading())
  232. return 0;
  233. Time t {};
  234. return recvfrom(description, buffer, size, 0, {}, 0, t, description.is_blocking());
  235. }
  236. ErrorOr<size_t> Socket::write(OpenFileDescription& description, u64, UserOrKernelBuffer const& data, size_t size)
  237. {
  238. if (is_shut_down_for_writing())
  239. return set_so_error(EPIPE);
  240. return sendto(description, data, size, 0, {}, 0);
  241. }
  242. ErrorOr<void> Socket::shutdown(int how)
  243. {
  244. MutexLocker locker(mutex());
  245. if (type() == SOCK_STREAM && !is_connected())
  246. return set_so_error(ENOTCONN);
  247. if (m_role == Role::Listener)
  248. return set_so_error(ENOTCONN);
  249. if (!m_shut_down_for_writing && (how == SHUT_WR || how == SHUT_RDWR)) {
  250. shut_down_for_writing();
  251. m_shut_down_for_writing = true;
  252. }
  253. if (!m_shut_down_for_reading && (how == SHUT_RD || how == SHUT_RDWR)) {
  254. shut_down_for_reading();
  255. m_shut_down_for_reading = true;
  256. }
  257. return {};
  258. }
  259. ErrorOr<struct stat> Socket::stat() const
  260. {
  261. struct stat st = {};
  262. st.st_mode = S_IFSOCK;
  263. return st;
  264. }
  265. void Socket::set_connected(bool connected)
  266. {
  267. MutexLocker locker(mutex());
  268. if (m_connected == connected)
  269. return;
  270. m_connected = connected;
  271. evaluate_block_conditions();
  272. }
  273. void Socket::set_origin(Process const& process)
  274. {
  275. auto credentials = process.credentials();
  276. m_origin = { process.pid().value(), credentials->uid().value(), credentials->gid().value() };
  277. }
  278. void Socket::set_acceptor(Process const& process)
  279. {
  280. auto credentials = process.credentials();
  281. m_acceptor = { process.pid().value(), credentials->uid().value(), credentials->gid().value() };
  282. }
  283. }