bsd.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  1. // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <array>
  4. #include <memory>
  5. #include <utility>
  6. #include <vector>
  7. #include <fmt/format.h>
  8. #include "common/microprofile.h"
  9. #include "common/socket_types.h"
  10. #include "core/core.h"
  11. #include "core/hle/ipc_helpers.h"
  12. #include "core/hle/kernel/k_thread.h"
  13. #include "core/hle/service/sockets/bsd.h"
  14. #include "core/hle/service/sockets/sockets_translate.h"
  15. #include "core/internal_network/network.h"
  16. #include "core/internal_network/socket_proxy.h"
  17. #include "core/internal_network/sockets.h"
  18. #include "network/network.h"
  19. namespace Service::Sockets {
  20. namespace {
  21. bool IsConnectionBased(Type type) {
  22. switch (type) {
  23. case Type::STREAM:
  24. return true;
  25. case Type::DGRAM:
  26. return false;
  27. default:
  28. UNIMPLEMENTED_MSG("Unimplemented type={}", type);
  29. return false;
  30. }
  31. }
  32. } // Anonymous namespace
  33. void BSD::PollWork::Execute(BSD* bsd) {
  34. std::tie(ret, bsd_errno) = bsd->PollImpl(write_buffer, read_buffer, nfds, timeout);
  35. }
  36. void BSD::PollWork::Response(Kernel::HLERequestContext& ctx) {
  37. if (write_buffer.size() > 0) {
  38. ctx.WriteBuffer(write_buffer);
  39. }
  40. IPC::ResponseBuilder rb{ctx, 4};
  41. rb.Push(ResultSuccess);
  42. rb.Push<s32>(ret);
  43. rb.PushEnum(bsd_errno);
  44. }
  45. void BSD::AcceptWork::Execute(BSD* bsd) {
  46. std::tie(ret, bsd_errno) = bsd->AcceptImpl(fd, write_buffer);
  47. }
  48. void BSD::AcceptWork::Response(Kernel::HLERequestContext& ctx) {
  49. if (write_buffer.size() > 0) {
  50. ctx.WriteBuffer(write_buffer);
  51. }
  52. IPC::ResponseBuilder rb{ctx, 5};
  53. rb.Push(ResultSuccess);
  54. rb.Push<s32>(ret);
  55. rb.PushEnum(bsd_errno);
  56. rb.Push<u32>(static_cast<u32>(write_buffer.size()));
  57. }
  58. void BSD::ConnectWork::Execute(BSD* bsd) {
  59. bsd_errno = bsd->ConnectImpl(fd, addr);
  60. }
  61. void BSD::ConnectWork::Response(Kernel::HLERequestContext& ctx) {
  62. IPC::ResponseBuilder rb{ctx, 4};
  63. rb.Push(ResultSuccess);
  64. rb.Push<s32>(bsd_errno == Errno::SUCCESS ? 0 : -1);
  65. rb.PushEnum(bsd_errno);
  66. }
  67. void BSD::RecvWork::Execute(BSD* bsd) {
  68. std::tie(ret, bsd_errno) = bsd->RecvImpl(fd, flags, message);
  69. }
  70. void BSD::RecvWork::Response(Kernel::HLERequestContext& ctx) {
  71. ctx.WriteBuffer(message);
  72. IPC::ResponseBuilder rb{ctx, 4};
  73. rb.Push(ResultSuccess);
  74. rb.Push<s32>(ret);
  75. rb.PushEnum(bsd_errno);
  76. }
  77. void BSD::RecvFromWork::Execute(BSD* bsd) {
  78. std::tie(ret, bsd_errno) = bsd->RecvFromImpl(fd, flags, message, addr);
  79. }
  80. void BSD::RecvFromWork::Response(Kernel::HLERequestContext& ctx) {
  81. ctx.WriteBuffer(message, 0);
  82. if (!addr.empty()) {
  83. ctx.WriteBuffer(addr, 1);
  84. }
  85. IPC::ResponseBuilder rb{ctx, 5};
  86. rb.Push(ResultSuccess);
  87. rb.Push<s32>(ret);
  88. rb.PushEnum(bsd_errno);
  89. rb.Push<u32>(static_cast<u32>(addr.size()));
  90. }
  91. void BSD::SendWork::Execute(BSD* bsd) {
  92. std::tie(ret, bsd_errno) = bsd->SendImpl(fd, flags, message);
  93. }
  94. void BSD::SendWork::Response(Kernel::HLERequestContext& ctx) {
  95. IPC::ResponseBuilder rb{ctx, 4};
  96. rb.Push(ResultSuccess);
  97. rb.Push<s32>(ret);
  98. rb.PushEnum(bsd_errno);
  99. }
  100. void BSD::SendToWork::Execute(BSD* bsd) {
  101. std::tie(ret, bsd_errno) = bsd->SendToImpl(fd, flags, message, addr);
  102. }
  103. void BSD::SendToWork::Response(Kernel::HLERequestContext& ctx) {
  104. IPC::ResponseBuilder rb{ctx, 4};
  105. rb.Push(ResultSuccess);
  106. rb.Push<s32>(ret);
  107. rb.PushEnum(bsd_errno);
  108. }
  109. void BSD::RegisterClient(Kernel::HLERequestContext& ctx) {
  110. LOG_WARNING(Service, "(STUBBED) called");
  111. IPC::ResponseBuilder rb{ctx, 3};
  112. rb.Push(ResultSuccess);
  113. rb.Push<s32>(0); // bsd errno
  114. }
  115. void BSD::StartMonitoring(Kernel::HLERequestContext& ctx) {
  116. LOG_WARNING(Service, "(STUBBED) called");
  117. IPC::ResponseBuilder rb{ctx, 2};
  118. rb.Push(ResultSuccess);
  119. }
  120. void BSD::Socket(Kernel::HLERequestContext& ctx) {
  121. IPC::RequestParser rp{ctx};
  122. const u32 domain = rp.Pop<u32>();
  123. const u32 type = rp.Pop<u32>();
  124. const u32 protocol = rp.Pop<u32>();
  125. LOG_DEBUG(Service, "called. domain={} type={} protocol={}", domain, type, protocol);
  126. const auto [fd, bsd_errno] = SocketImpl(static_cast<Domain>(domain), static_cast<Type>(type),
  127. static_cast<Protocol>(protocol));
  128. IPC::ResponseBuilder rb{ctx, 4};
  129. rb.Push(ResultSuccess);
  130. rb.Push<s32>(fd);
  131. rb.PushEnum(bsd_errno);
  132. }
  133. void BSD::Select(Kernel::HLERequestContext& ctx) {
  134. LOG_WARNING(Service, "(STUBBED) called");
  135. IPC::ResponseBuilder rb{ctx, 4};
  136. rb.Push(ResultSuccess);
  137. rb.Push<u32>(0); // ret
  138. rb.Push<u32>(0); // bsd errno
  139. }
  140. void BSD::Poll(Kernel::HLERequestContext& ctx) {
  141. IPC::RequestParser rp{ctx};
  142. const s32 nfds = rp.Pop<s32>();
  143. const s32 timeout = rp.Pop<s32>();
  144. LOG_DEBUG(Service, "called. nfds={} timeout={}", nfds, timeout);
  145. ExecuteWork(ctx, PollWork{
  146. .nfds = nfds,
  147. .timeout = timeout,
  148. .read_buffer = ctx.ReadBuffer(),
  149. .write_buffer = std::vector<u8>(ctx.GetWriteBufferSize()),
  150. });
  151. }
  152. void BSD::Accept(Kernel::HLERequestContext& ctx) {
  153. IPC::RequestParser rp{ctx};
  154. const s32 fd = rp.Pop<s32>();
  155. LOG_DEBUG(Service, "called. fd={}", fd);
  156. ExecuteWork(ctx, AcceptWork{
  157. .fd = fd,
  158. .write_buffer = std::vector<u8>(ctx.GetWriteBufferSize()),
  159. });
  160. }
  161. void BSD::Bind(Kernel::HLERequestContext& ctx) {
  162. IPC::RequestParser rp{ctx};
  163. const s32 fd = rp.Pop<s32>();
  164. LOG_DEBUG(Service, "called. fd={} addrlen={}", fd, ctx.GetReadBufferSize());
  165. BuildErrnoResponse(ctx, BindImpl(fd, ctx.ReadBuffer()));
  166. }
  167. void BSD::Connect(Kernel::HLERequestContext& ctx) {
  168. IPC::RequestParser rp{ctx};
  169. const s32 fd = rp.Pop<s32>();
  170. LOG_DEBUG(Service, "called. fd={} addrlen={}", fd, ctx.GetReadBufferSize());
  171. ExecuteWork(ctx, ConnectWork{
  172. .fd = fd,
  173. .addr = ctx.ReadBuffer(),
  174. });
  175. }
  176. void BSD::GetPeerName(Kernel::HLERequestContext& ctx) {
  177. IPC::RequestParser rp{ctx};
  178. const s32 fd = rp.Pop<s32>();
  179. LOG_DEBUG(Service, "called. fd={}", fd);
  180. std::vector<u8> write_buffer(ctx.GetWriteBufferSize());
  181. const Errno bsd_errno = GetPeerNameImpl(fd, write_buffer);
  182. ctx.WriteBuffer(write_buffer);
  183. IPC::ResponseBuilder rb{ctx, 5};
  184. rb.Push(ResultSuccess);
  185. rb.Push<s32>(bsd_errno != Errno::SUCCESS ? -1 : 0);
  186. rb.PushEnum(bsd_errno);
  187. rb.Push<u32>(static_cast<u32>(write_buffer.size()));
  188. }
  189. void BSD::GetSockName(Kernel::HLERequestContext& ctx) {
  190. IPC::RequestParser rp{ctx};
  191. const s32 fd = rp.Pop<s32>();
  192. LOG_DEBUG(Service, "called. fd={}", fd);
  193. std::vector<u8> write_buffer(ctx.GetWriteBufferSize());
  194. const Errno bsd_errno = GetSockNameImpl(fd, write_buffer);
  195. ctx.WriteBuffer(write_buffer);
  196. IPC::ResponseBuilder rb{ctx, 5};
  197. rb.Push(ResultSuccess);
  198. rb.Push<s32>(bsd_errno != Errno::SUCCESS ? -1 : 0);
  199. rb.PushEnum(bsd_errno);
  200. rb.Push<u32>(static_cast<u32>(write_buffer.size()));
  201. }
  202. void BSD::GetSockOpt(Kernel::HLERequestContext& ctx) {
  203. IPC::RequestParser rp{ctx};
  204. const s32 fd = rp.Pop<s32>();
  205. const u32 level = rp.Pop<u32>();
  206. const auto optname = static_cast<OptName>(rp.Pop<u32>());
  207. LOG_WARNING(Service, "(STUBBED) called. fd={} level={} optname=0x{:x}", fd, level, optname);
  208. std::vector<u8> optval(ctx.GetWriteBufferSize());
  209. ctx.WriteBuffer(optval);
  210. IPC::ResponseBuilder rb{ctx, 5};
  211. rb.Push(ResultSuccess);
  212. rb.Push<s32>(-1);
  213. rb.PushEnum(Errno::NOTCONN);
  214. rb.Push<u32>(static_cast<u32>(optval.size()));
  215. }
  216. void BSD::Listen(Kernel::HLERequestContext& ctx) {
  217. IPC::RequestParser rp{ctx};
  218. const s32 fd = rp.Pop<s32>();
  219. const s32 backlog = rp.Pop<s32>();
  220. LOG_DEBUG(Service, "called. fd={} backlog={}", fd, backlog);
  221. BuildErrnoResponse(ctx, ListenImpl(fd, backlog));
  222. }
  223. void BSD::Fcntl(Kernel::HLERequestContext& ctx) {
  224. IPC::RequestParser rp{ctx};
  225. const s32 fd = rp.Pop<s32>();
  226. const s32 cmd = rp.Pop<s32>();
  227. const s32 arg = rp.Pop<s32>();
  228. LOG_DEBUG(Service, "called. fd={} cmd={} arg={}", fd, cmd, arg);
  229. const auto [ret, bsd_errno] = FcntlImpl(fd, static_cast<FcntlCmd>(cmd), arg);
  230. IPC::ResponseBuilder rb{ctx, 4};
  231. rb.Push(ResultSuccess);
  232. rb.Push<s32>(ret);
  233. rb.PushEnum(bsd_errno);
  234. }
  235. void BSD::SetSockOpt(Kernel::HLERequestContext& ctx) {
  236. IPC::RequestParser rp{ctx};
  237. const s32 fd = rp.Pop<s32>();
  238. const u32 level = rp.Pop<u32>();
  239. const OptName optname = static_cast<OptName>(rp.Pop<u32>());
  240. const std::vector<u8> buffer = ctx.ReadBuffer();
  241. const u8* optval = buffer.empty() ? nullptr : buffer.data();
  242. size_t optlen = buffer.size();
  243. std::array<u64, 2> values;
  244. if ((optname == OptName::SNDTIMEO || optname == OptName::RCVTIMEO) && buffer.size() == 8) {
  245. std::memcpy(values.data(), buffer.data(), sizeof(values));
  246. optlen = sizeof(values);
  247. optval = reinterpret_cast<const u8*>(values.data());
  248. }
  249. LOG_DEBUG(Service, "called. fd={} level={} optname=0x{:x} optlen={}", fd, level,
  250. static_cast<u32>(optname), optlen);
  251. BuildErrnoResponse(ctx, SetSockOptImpl(fd, level, optname, optlen, optval));
  252. }
  253. void BSD::Shutdown(Kernel::HLERequestContext& ctx) {
  254. IPC::RequestParser rp{ctx};
  255. const s32 fd = rp.Pop<s32>();
  256. const s32 how = rp.Pop<s32>();
  257. LOG_DEBUG(Service, "called. fd={} how={}", fd, how);
  258. BuildErrnoResponse(ctx, ShutdownImpl(fd, how));
  259. }
  260. void BSD::Recv(Kernel::HLERequestContext& ctx) {
  261. IPC::RequestParser rp{ctx};
  262. const s32 fd = rp.Pop<s32>();
  263. const u32 flags = rp.Pop<u32>();
  264. LOG_DEBUG(Service, "called. fd={} flags=0x{:x} len={}", fd, flags, ctx.GetWriteBufferSize());
  265. ExecuteWork(ctx, RecvWork{
  266. .fd = fd,
  267. .flags = flags,
  268. .message = std::vector<u8>(ctx.GetWriteBufferSize()),
  269. });
  270. }
  271. void BSD::RecvFrom(Kernel::HLERequestContext& ctx) {
  272. IPC::RequestParser rp{ctx};
  273. const s32 fd = rp.Pop<s32>();
  274. const u32 flags = rp.Pop<u32>();
  275. LOG_DEBUG(Service, "called. fd={} flags=0x{:x} len={} addrlen={}", fd, flags,
  276. ctx.GetWriteBufferSize(0), ctx.GetWriteBufferSize(1));
  277. ExecuteWork(ctx, RecvFromWork{
  278. .fd = fd,
  279. .flags = flags,
  280. .message = std::vector<u8>(ctx.GetWriteBufferSize(0)),
  281. .addr = std::vector<u8>(ctx.GetWriteBufferSize(1)),
  282. });
  283. }
  284. void BSD::Send(Kernel::HLERequestContext& ctx) {
  285. IPC::RequestParser rp{ctx};
  286. const s32 fd = rp.Pop<s32>();
  287. const u32 flags = rp.Pop<u32>();
  288. LOG_DEBUG(Service, "called. fd={} flags=0x{:x} len={}", fd, flags, ctx.GetReadBufferSize());
  289. ExecuteWork(ctx, SendWork{
  290. .fd = fd,
  291. .flags = flags,
  292. .message = ctx.ReadBuffer(),
  293. });
  294. }
  295. void BSD::SendTo(Kernel::HLERequestContext& ctx) {
  296. IPC::RequestParser rp{ctx};
  297. const s32 fd = rp.Pop<s32>();
  298. const u32 flags = rp.Pop<u32>();
  299. LOG_DEBUG(Service, "called. fd={} flags=0x{} len={} addrlen={}", fd, flags,
  300. ctx.GetReadBufferSize(0), ctx.GetReadBufferSize(1));
  301. ExecuteWork(ctx, SendToWork{
  302. .fd = fd,
  303. .flags = flags,
  304. .message = ctx.ReadBuffer(0),
  305. .addr = ctx.ReadBuffer(1),
  306. });
  307. }
  308. void BSD::Write(Kernel::HLERequestContext& ctx) {
  309. IPC::RequestParser rp{ctx};
  310. const s32 fd = rp.Pop<s32>();
  311. LOG_DEBUG(Service, "called. fd={} len={}", fd, ctx.GetReadBufferSize());
  312. ExecuteWork(ctx, SendWork{
  313. .fd = fd,
  314. .flags = 0,
  315. .message = ctx.ReadBuffer(),
  316. });
  317. }
  318. void BSD::Read(Kernel::HLERequestContext& ctx) {
  319. IPC::RequestParser rp{ctx};
  320. const s32 fd = rp.Pop<s32>();
  321. LOG_WARNING(Service, "(STUBBED) called. fd={} len={}", fd, ctx.GetWriteBufferSize());
  322. IPC::ResponseBuilder rb{ctx, 4};
  323. rb.Push(ResultSuccess);
  324. rb.Push<u32>(0); // ret
  325. rb.Push<u32>(0); // bsd errno
  326. }
  327. void BSD::Close(Kernel::HLERequestContext& ctx) {
  328. IPC::RequestParser rp{ctx};
  329. const s32 fd = rp.Pop<s32>();
  330. LOG_DEBUG(Service, "called. fd={}", fd);
  331. BuildErrnoResponse(ctx, CloseImpl(fd));
  332. }
  333. void BSD::EventFd(Kernel::HLERequestContext& ctx) {
  334. IPC::RequestParser rp{ctx};
  335. const u64 initval = rp.Pop<u64>();
  336. const u32 flags = rp.Pop<u32>();
  337. LOG_WARNING(Service, "(STUBBED) called. initval={}, flags={}", initval, flags);
  338. BuildErrnoResponse(ctx, Errno::SUCCESS);
  339. }
  340. template <typename Work>
  341. void BSD::ExecuteWork(Kernel::HLERequestContext& ctx, Work work) {
  342. work.Execute(this);
  343. work.Response(ctx);
  344. }
  345. std::pair<s32, Errno> BSD::SocketImpl(Domain domain, Type type, Protocol protocol) {
  346. if (type == Type::SEQPACKET) {
  347. UNIMPLEMENTED_MSG("SOCK_SEQPACKET errno management");
  348. } else if (type == Type::RAW && (domain != Domain::INET || protocol != Protocol::ICMP)) {
  349. UNIMPLEMENTED_MSG("SOCK_RAW errno management");
  350. }
  351. [[maybe_unused]] const bool unk_flag = (static_cast<u32>(type) & 0x20000000) != 0;
  352. UNIMPLEMENTED_IF_MSG(unk_flag, "Unknown flag in type");
  353. type = static_cast<Type>(static_cast<u32>(type) & ~0x20000000);
  354. const s32 fd = FindFreeFileDescriptorHandle();
  355. if (fd < 0) {
  356. LOG_ERROR(Service, "No more file descriptors available");
  357. return {-1, Errno::MFILE};
  358. }
  359. file_descriptors[fd] = FileDescriptor{};
  360. FileDescriptor& descriptor = *file_descriptors[fd];
  361. // ENONMEM might be thrown here
  362. LOG_INFO(Service, "New socket fd={}", fd);
  363. auto room_member = room_network.GetRoomMember().lock();
  364. if (room_member && room_member->IsConnected()) {
  365. descriptor.socket = std::make_unique<Network::ProxySocket>(room_network);
  366. } else {
  367. descriptor.socket = std::make_unique<Network::Socket>();
  368. }
  369. descriptor.socket->Initialize(Translate(domain), Translate(type), Translate(type, protocol));
  370. descriptor.is_connection_based = IsConnectionBased(type);
  371. return {fd, Errno::SUCCESS};
  372. }
  373. std::pair<s32, Errno> BSD::PollImpl(std::vector<u8>& write_buffer, std::vector<u8> read_buffer,
  374. s32 nfds, s32 timeout) {
  375. if (write_buffer.size() < nfds * sizeof(PollFD)) {
  376. return {-1, Errno::INVAL};
  377. }
  378. if (nfds == 0) {
  379. // When no entries are provided, -1 is returned with errno zero
  380. return {-1, Errno::SUCCESS};
  381. }
  382. const size_t length = std::min(read_buffer.size(), write_buffer.size());
  383. std::vector<PollFD> fds(nfds);
  384. std::memcpy(fds.data(), read_buffer.data(), length);
  385. if (timeout >= 0) {
  386. const s64 seconds = timeout / 1000;
  387. const u64 nanoseconds = 1'000'000 * (static_cast<u64>(timeout) % 1000);
  388. if (seconds < 0) {
  389. return {-1, Errno::INVAL};
  390. }
  391. if (nanoseconds > 999'999'999) {
  392. return {-1, Errno::INVAL};
  393. }
  394. } else if (timeout != -1) {
  395. return {-1, Errno::INVAL};
  396. }
  397. for (PollFD& pollfd : fds) {
  398. ASSERT(False(pollfd.revents));
  399. if (pollfd.fd > static_cast<s32>(MAX_FD) || pollfd.fd < 0) {
  400. LOG_ERROR(Service, "File descriptor handle={} is invalid", pollfd.fd);
  401. pollfd.revents = PollEvents{};
  402. return {0, Errno::SUCCESS};
  403. }
  404. const std::optional<FileDescriptor>& descriptor = file_descriptors[pollfd.fd];
  405. if (!descriptor) {
  406. LOG_ERROR(Service, "File descriptor handle={} is not allocated", pollfd.fd);
  407. pollfd.revents = PollEvents::Nval;
  408. return {0, Errno::SUCCESS};
  409. }
  410. }
  411. std::vector<Network::PollFD> host_pollfds(fds.size());
  412. std::transform(fds.begin(), fds.end(), host_pollfds.begin(), [this](PollFD pollfd) {
  413. Network::PollFD result;
  414. result.socket = file_descriptors[pollfd.fd]->socket.get();
  415. result.events = TranslatePollEventsToHost(pollfd.events);
  416. result.revents = Network::PollEvents{};
  417. return result;
  418. });
  419. const auto result = Network::Poll(host_pollfds, timeout);
  420. const size_t num = host_pollfds.size();
  421. for (size_t i = 0; i < num; ++i) {
  422. fds[i].revents = TranslatePollEventsToGuest(host_pollfds[i].revents);
  423. }
  424. std::memcpy(write_buffer.data(), fds.data(), length);
  425. return Translate(result);
  426. }
  427. std::pair<s32, Errno> BSD::AcceptImpl(s32 fd, std::vector<u8>& write_buffer) {
  428. if (!IsFileDescriptorValid(fd)) {
  429. return {-1, Errno::BADF};
  430. }
  431. const s32 new_fd = FindFreeFileDescriptorHandle();
  432. if (new_fd < 0) {
  433. LOG_ERROR(Service, "No more file descriptors available");
  434. return {-1, Errno::MFILE};
  435. }
  436. FileDescriptor& descriptor = *file_descriptors[fd];
  437. auto [result, bsd_errno] = descriptor.socket->Accept();
  438. if (bsd_errno != Network::Errno::SUCCESS) {
  439. return {-1, Translate(bsd_errno)};
  440. }
  441. file_descriptors[new_fd] = FileDescriptor{};
  442. FileDescriptor& new_descriptor = *file_descriptors[new_fd];
  443. new_descriptor.socket = std::move(result.socket);
  444. new_descriptor.is_connection_based = descriptor.is_connection_based;
  445. const SockAddrIn guest_addr_in = Translate(result.sockaddr_in);
  446. const size_t length = std::min(sizeof(guest_addr_in), write_buffer.size());
  447. std::memcpy(write_buffer.data(), &guest_addr_in, length);
  448. return {new_fd, Errno::SUCCESS};
  449. }
  450. Errno BSD::BindImpl(s32 fd, const std::vector<u8>& addr) {
  451. if (!IsFileDescriptorValid(fd)) {
  452. return Errno::BADF;
  453. }
  454. ASSERT(addr.size() == sizeof(SockAddrIn));
  455. SockAddrIn addr_in;
  456. std::memcpy(&addr_in, addr.data(), sizeof(addr_in));
  457. return Translate(file_descriptors[fd]->socket->Bind(Translate(addr_in)));
  458. }
  459. Errno BSD::ConnectImpl(s32 fd, const std::vector<u8>& addr) {
  460. if (!IsFileDescriptorValid(fd)) {
  461. return Errno::BADF;
  462. }
  463. UNIMPLEMENTED_IF(addr.size() != sizeof(SockAddrIn));
  464. SockAddrIn addr_in;
  465. std::memcpy(&addr_in, addr.data(), sizeof(addr_in));
  466. return Translate(file_descriptors[fd]->socket->Connect(Translate(addr_in)));
  467. }
  468. Errno BSD::GetPeerNameImpl(s32 fd, std::vector<u8>& write_buffer) {
  469. if (!IsFileDescriptorValid(fd)) {
  470. return Errno::BADF;
  471. }
  472. const auto [addr_in, bsd_errno] = file_descriptors[fd]->socket->GetPeerName();
  473. if (bsd_errno != Network::Errno::SUCCESS) {
  474. return Translate(bsd_errno);
  475. }
  476. const SockAddrIn guest_addrin = Translate(addr_in);
  477. ASSERT(write_buffer.size() == sizeof(guest_addrin));
  478. std::memcpy(write_buffer.data(), &guest_addrin, sizeof(guest_addrin));
  479. return Translate(bsd_errno);
  480. }
  481. Errno BSD::GetSockNameImpl(s32 fd, std::vector<u8>& write_buffer) {
  482. if (!IsFileDescriptorValid(fd)) {
  483. return Errno::BADF;
  484. }
  485. const auto [addr_in, bsd_errno] = file_descriptors[fd]->socket->GetSockName();
  486. if (bsd_errno != Network::Errno::SUCCESS) {
  487. return Translate(bsd_errno);
  488. }
  489. const SockAddrIn guest_addrin = Translate(addr_in);
  490. ASSERT(write_buffer.size() == sizeof(guest_addrin));
  491. std::memcpy(write_buffer.data(), &guest_addrin, sizeof(guest_addrin));
  492. return Translate(bsd_errno);
  493. }
  494. Errno BSD::ListenImpl(s32 fd, s32 backlog) {
  495. if (!IsFileDescriptorValid(fd)) {
  496. return Errno::BADF;
  497. }
  498. return Translate(file_descriptors[fd]->socket->Listen(backlog));
  499. }
  500. std::pair<s32, Errno> BSD::FcntlImpl(s32 fd, FcntlCmd cmd, s32 arg) {
  501. if (!IsFileDescriptorValid(fd)) {
  502. return {-1, Errno::BADF};
  503. }
  504. FileDescriptor& descriptor = *file_descriptors[fd];
  505. switch (cmd) {
  506. case FcntlCmd::GETFL:
  507. ASSERT(arg == 0);
  508. return {descriptor.flags, Errno::SUCCESS};
  509. case FcntlCmd::SETFL: {
  510. const bool enable = (arg & Network::FLAG_O_NONBLOCK) != 0;
  511. const Errno bsd_errno = Translate(descriptor.socket->SetNonBlock(enable));
  512. if (bsd_errno != Errno::SUCCESS) {
  513. return {-1, bsd_errno};
  514. }
  515. descriptor.flags = arg;
  516. return {0, Errno::SUCCESS};
  517. }
  518. default:
  519. UNIMPLEMENTED_MSG("Unimplemented cmd={}", cmd);
  520. return {-1, Errno::SUCCESS};
  521. }
  522. }
  523. Errno BSD::SetSockOptImpl(s32 fd, u32 level, OptName optname, size_t optlen, const void* optval) {
  524. UNIMPLEMENTED_IF(level != 0xffff); // SOL_SOCKET
  525. if (!IsFileDescriptorValid(fd)) {
  526. return Errno::BADF;
  527. }
  528. Network::SocketBase* const socket = file_descriptors[fd]->socket.get();
  529. if (optname == OptName::LINGER) {
  530. ASSERT(optlen == sizeof(Linger));
  531. Linger linger;
  532. std::memcpy(&linger, optval, sizeof(linger));
  533. ASSERT(linger.onoff == 0 || linger.onoff == 1);
  534. return Translate(socket->SetLinger(linger.onoff != 0, linger.linger));
  535. }
  536. ASSERT(optlen == sizeof(u32));
  537. u32 value;
  538. std::memcpy(&value, optval, sizeof(value));
  539. switch (optname) {
  540. case OptName::REUSEADDR:
  541. ASSERT(value == 0 || value == 1);
  542. return Translate(socket->SetReuseAddr(value != 0));
  543. case OptName::KEEPALIVE:
  544. ASSERT(value == 0 || value == 1);
  545. return Translate(socket->SetKeepAlive(value != 0));
  546. case OptName::BROADCAST:
  547. ASSERT(value == 0 || value == 1);
  548. return Translate(socket->SetBroadcast(value != 0));
  549. case OptName::SNDBUF:
  550. return Translate(socket->SetSndBuf(value));
  551. case OptName::RCVBUF:
  552. return Translate(socket->SetRcvBuf(value));
  553. case OptName::SNDTIMEO:
  554. return Translate(socket->SetSndTimeo(value));
  555. case OptName::RCVTIMEO:
  556. return Translate(socket->SetRcvTimeo(value));
  557. default:
  558. UNIMPLEMENTED_MSG("Unimplemented optname={}", optname);
  559. return Errno::SUCCESS;
  560. }
  561. }
  562. Errno BSD::ShutdownImpl(s32 fd, s32 how) {
  563. if (!IsFileDescriptorValid(fd)) {
  564. return Errno::BADF;
  565. }
  566. const Network::ShutdownHow host_how = Translate(static_cast<ShutdownHow>(how));
  567. return Translate(file_descriptors[fd]->socket->Shutdown(host_how));
  568. }
  569. std::pair<s32, Errno> BSD::RecvImpl(s32 fd, u32 flags, std::vector<u8>& message) {
  570. if (!IsFileDescriptorValid(fd)) {
  571. return {-1, Errno::BADF};
  572. }
  573. FileDescriptor& descriptor = *file_descriptors[fd];
  574. // Apply flags
  575. using Network::FLAG_MSG_DONTWAIT;
  576. using Network::FLAG_O_NONBLOCK;
  577. if ((flags & FLAG_MSG_DONTWAIT) != 0) {
  578. flags &= ~FLAG_MSG_DONTWAIT;
  579. if ((descriptor.flags & FLAG_O_NONBLOCK) == 0) {
  580. descriptor.socket->SetNonBlock(true);
  581. }
  582. }
  583. const auto [ret, bsd_errno] = Translate(descriptor.socket->Recv(flags, message));
  584. // Restore original state
  585. if ((descriptor.flags & FLAG_O_NONBLOCK) == 0) {
  586. descriptor.socket->SetNonBlock(false);
  587. }
  588. return {ret, bsd_errno};
  589. }
  590. std::pair<s32, Errno> BSD::RecvFromImpl(s32 fd, u32 flags, std::vector<u8>& message,
  591. std::vector<u8>& addr) {
  592. if (!IsFileDescriptorValid(fd)) {
  593. return {-1, Errno::BADF};
  594. }
  595. FileDescriptor& descriptor = *file_descriptors[fd];
  596. Network::SockAddrIn addr_in{};
  597. Network::SockAddrIn* p_addr_in = nullptr;
  598. if (descriptor.is_connection_based) {
  599. // Connection based file descriptors (e.g. TCP) zero addr
  600. addr.clear();
  601. } else {
  602. p_addr_in = &addr_in;
  603. }
  604. // Apply flags
  605. using Network::FLAG_MSG_DONTWAIT;
  606. using Network::FLAG_O_NONBLOCK;
  607. if ((flags & FLAG_MSG_DONTWAIT) != 0) {
  608. flags &= ~FLAG_MSG_DONTWAIT;
  609. if ((descriptor.flags & FLAG_O_NONBLOCK) == 0) {
  610. descriptor.socket->SetNonBlock(true);
  611. }
  612. }
  613. const auto [ret, bsd_errno] = Translate(descriptor.socket->RecvFrom(flags, message, p_addr_in));
  614. // Restore original state
  615. if ((descriptor.flags & FLAG_O_NONBLOCK) == 0) {
  616. descriptor.socket->SetNonBlock(false);
  617. }
  618. if (p_addr_in) {
  619. if (ret < 0) {
  620. addr.clear();
  621. } else {
  622. ASSERT(addr.size() == sizeof(SockAddrIn));
  623. const SockAddrIn result = Translate(addr_in);
  624. std::memcpy(addr.data(), &result, sizeof(result));
  625. }
  626. }
  627. return {ret, bsd_errno};
  628. }
  629. std::pair<s32, Errno> BSD::SendImpl(s32 fd, u32 flags, const std::vector<u8>& message) {
  630. if (!IsFileDescriptorValid(fd)) {
  631. return {-1, Errno::BADF};
  632. }
  633. return Translate(file_descriptors[fd]->socket->Send(message, flags));
  634. }
  635. std::pair<s32, Errno> BSD::SendToImpl(s32 fd, u32 flags, const std::vector<u8>& message,
  636. const std::vector<u8>& addr) {
  637. if (!IsFileDescriptorValid(fd)) {
  638. return {-1, Errno::BADF};
  639. }
  640. Network::SockAddrIn addr_in;
  641. Network::SockAddrIn* p_addr_in = nullptr;
  642. if (!addr.empty()) {
  643. ASSERT(addr.size() == sizeof(SockAddrIn));
  644. SockAddrIn guest_addr_in;
  645. std::memcpy(&guest_addr_in, addr.data(), sizeof(guest_addr_in));
  646. addr_in = Translate(guest_addr_in);
  647. p_addr_in = &addr_in;
  648. }
  649. return Translate(file_descriptors[fd]->socket->SendTo(flags, message, p_addr_in));
  650. }
  651. Errno BSD::CloseImpl(s32 fd) {
  652. if (!IsFileDescriptorValid(fd)) {
  653. return Errno::BADF;
  654. }
  655. const Errno bsd_errno = Translate(file_descriptors[fd]->socket->Close());
  656. if (bsd_errno != Errno::SUCCESS) {
  657. return bsd_errno;
  658. }
  659. LOG_INFO(Service, "Close socket fd={}", fd);
  660. file_descriptors[fd].reset();
  661. return bsd_errno;
  662. }
  663. s32 BSD::FindFreeFileDescriptorHandle() noexcept {
  664. for (s32 fd = 0; fd < static_cast<s32>(file_descriptors.size()); ++fd) {
  665. if (!file_descriptors[fd]) {
  666. return fd;
  667. }
  668. }
  669. return -1;
  670. }
  671. bool BSD::IsFileDescriptorValid(s32 fd) const noexcept {
  672. if (fd > static_cast<s32>(MAX_FD) || fd < 0) {
  673. LOG_ERROR(Service, "Invalid file descriptor handle={}", fd);
  674. return false;
  675. }
  676. if (!file_descriptors[fd]) {
  677. LOG_ERROR(Service, "File descriptor handle={} is not allocated", fd);
  678. return false;
  679. }
  680. return true;
  681. }
  682. void BSD::BuildErrnoResponse(Kernel::HLERequestContext& ctx, Errno bsd_errno) const noexcept {
  683. IPC::ResponseBuilder rb{ctx, 4};
  684. rb.Push(ResultSuccess);
  685. rb.Push<s32>(bsd_errno == Errno::SUCCESS ? 0 : -1);
  686. rb.PushEnum(bsd_errno);
  687. }
  688. void BSD::OnProxyPacketReceived(const Network::ProxyPacket& packet) {
  689. for (auto& optional_descriptor : file_descriptors) {
  690. if (!optional_descriptor.has_value()) {
  691. continue;
  692. }
  693. FileDescriptor& descriptor = *optional_descriptor;
  694. descriptor.socket.get()->HandleProxyPacket(packet);
  695. }
  696. }
  697. BSD::BSD(Core::System& system_, const char* name)
  698. : ServiceFramework{system_, name, ServiceThreadType::CreateNew}, room_network{
  699. system_.GetRoomNetwork()} {
  700. // clang-format off
  701. static const FunctionInfo functions[] = {
  702. {0, &BSD::RegisterClient, "RegisterClient"},
  703. {1, &BSD::StartMonitoring, "StartMonitoring"},
  704. {2, &BSD::Socket, "Socket"},
  705. {3, nullptr, "SocketExempt"},
  706. {4, nullptr, "Open"},
  707. {5, &BSD::Select, "Select"},
  708. {6, &BSD::Poll, "Poll"},
  709. {7, nullptr, "Sysctl"},
  710. {8, &BSD::Recv, "Recv"},
  711. {9, &BSD::RecvFrom, "RecvFrom"},
  712. {10, &BSD::Send, "Send"},
  713. {11, &BSD::SendTo, "SendTo"},
  714. {12, &BSD::Accept, "Accept"},
  715. {13, &BSD::Bind, "Bind"},
  716. {14, &BSD::Connect, "Connect"},
  717. {15, &BSD::GetPeerName, "GetPeerName"},
  718. {16, &BSD::GetSockName, "GetSockName"},
  719. {17, &BSD::GetSockOpt, "GetSockOpt"},
  720. {18, &BSD::Listen, "Listen"},
  721. {19, nullptr, "Ioctl"},
  722. {20, &BSD::Fcntl, "Fcntl"},
  723. {21, &BSD::SetSockOpt, "SetSockOpt"},
  724. {22, &BSD::Shutdown, "Shutdown"},
  725. {23, nullptr, "ShutdownAllSockets"},
  726. {24, &BSD::Write, "Write"},
  727. {25, &BSD::Read, "Read"},
  728. {26, &BSD::Close, "Close"},
  729. {27, nullptr, "DuplicateSocket"},
  730. {28, nullptr, "GetResourceStatistics"},
  731. {29, nullptr, "RecvMMsg"},
  732. {30, nullptr, "SendMMsg"},
  733. {31, &BSD::EventFd, "EventFd"},
  734. {32, nullptr, "RegisterResourceStatisticsName"},
  735. {33, nullptr, "Initialize2"},
  736. };
  737. // clang-format on
  738. RegisterHandlers(functions);
  739. if (auto room_member = room_network.GetRoomMember().lock()) {
  740. proxy_packet_received = room_member->BindOnProxyPacketReceived(
  741. [this](const Network::ProxyPacket& packet) { OnProxyPacketReceived(packet); });
  742. } else {
  743. LOG_ERROR(Service, "Network isn't initalized");
  744. }
  745. }
  746. BSD::~BSD() = default;
  747. BSDCFG::BSDCFG(Core::System& system_) : ServiceFramework{system_, "bsdcfg"} {
  748. // clang-format off
  749. static const FunctionInfo functions[] = {
  750. {0, nullptr, "SetIfUp"},
  751. {1, nullptr, "SetIfUpWithEvent"},
  752. {2, nullptr, "CancelIf"},
  753. {3, nullptr, "SetIfDown"},
  754. {4, nullptr, "GetIfState"},
  755. {5, nullptr, "DhcpRenew"},
  756. {6, nullptr, "AddStaticArpEntry"},
  757. {7, nullptr, "RemoveArpEntry"},
  758. {8, nullptr, "LookupArpEntry"},
  759. {9, nullptr, "LookupArpEntry2"},
  760. {10, nullptr, "ClearArpEntries"},
  761. {11, nullptr, "ClearArpEntries2"},
  762. {12, nullptr, "PrintArpEntries"},
  763. };
  764. // clang-format on
  765. RegisterHandlers(functions);
  766. }
  767. BSDCFG::~BSDCFG() = default;
  768. } // namespace Service::Sockets