bsd.cpp 27 KB

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