bsd.cpp 26 KB

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