git subrepo clone https://github.com/Atmosphere-NX/Atmosphere-libs libraries
subrepo: subdir: "libraries" merged: "07af583b" upstream: origin: "https://github.com/Atmosphere-NX/Atmosphere-libs" branch: "master" commit: "07af583b" git-subrepo: version: "0.4.0" origin: "https://github.com/ingydotnet/git-subrepo" commit: "5d6aba9"
This commit is contained in:
86
libraries/libstratosphere/source/sf/hipc/sf_hipc_api.cpp
Normal file
86
libraries/libstratosphere/source/sf/hipc/sf_hipc_api.cpp
Normal file
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* Copyright (c) 2018-2019 Atmosphère-NX
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms and conditions of the GNU General Public License,
|
||||
* version 2, as published by the Free Software Foundation.
|
||||
*
|
||||
* This program is distributed in the hope it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include <stratosphere.hpp>
|
||||
|
||||
namespace ams::sf::hipc {
|
||||
|
||||
namespace {
|
||||
|
||||
NX_INLINE Result ReceiveImpl(Handle session_handle, void *message_buf, size_t message_buf_size) {
|
||||
s32 unused_index;
|
||||
if (message_buf == armGetTls()) {
|
||||
/* Consider: AMS_ASSERT(message_buf_size == TlsMessageBufferSize); */
|
||||
return svcReplyAndReceive(&unused_index, &session_handle, 1, INVALID_HANDLE, U64_MAX);
|
||||
} else {
|
||||
return svcReplyAndReceiveWithUserBuffer(&unused_index, message_buf, message_buf_size, &session_handle, 1, INVALID_HANDLE, U64_MAX);
|
||||
}
|
||||
}
|
||||
|
||||
NX_INLINE Result ReplyImpl(Handle session_handle, void *message_buf, size_t message_buf_size) {
|
||||
s32 unused_index;
|
||||
if (message_buf == armGetTls()) {
|
||||
/* Consider: AMS_ASSERT(message_buf_size == TlsMessageBufferSize); */
|
||||
return svcReplyAndReceive(&unused_index, &session_handle, 0, session_handle, 0);
|
||||
} else {
|
||||
return svcReplyAndReceiveWithUserBuffer(&unused_index, message_buf, message_buf_size, &session_handle, 0, session_handle, 0);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Result Receive(ReceiveResult *out_recv_result, Handle session_handle, const cmif::PointerAndSize &message_buffer) {
|
||||
R_TRY_CATCH(ReceiveImpl(session_handle, message_buffer.GetPointer(), message_buffer.GetSize())) {
|
||||
R_CATCH(svc::ResultSessionClosed) {
|
||||
*out_recv_result = ReceiveResult::Closed;
|
||||
return ResultSuccess();
|
||||
}
|
||||
R_CATCH(svc::ResultReceiveListBroken) {
|
||||
*out_recv_result = ReceiveResult::NeedsRetry;
|
||||
return ResultSuccess();
|
||||
}
|
||||
} R_END_TRY_CATCH;
|
||||
*out_recv_result = ReceiveResult::Success;
|
||||
return ResultSuccess();
|
||||
}
|
||||
|
||||
Result Receive(bool *out_closed, Handle session_handle, const cmif::PointerAndSize &message_buffer) {
|
||||
R_TRY_CATCH(ReceiveImpl(session_handle, message_buffer.GetPointer(), message_buffer.GetSize())) {
|
||||
R_CATCH(svc::ResultSessionClosed) {
|
||||
*out_closed = true;
|
||||
return ResultSuccess();
|
||||
}
|
||||
} R_END_TRY_CATCH;
|
||||
*out_closed = false;
|
||||
return ResultSuccess();
|
||||
}
|
||||
|
||||
Result Reply(Handle session_handle, const cmif::PointerAndSize &message_buffer) {
|
||||
R_TRY_CATCH(ReplyImpl(session_handle, message_buffer.GetPointer(), message_buffer.GetSize())) {
|
||||
R_CONVERT(svc::ResultTimedOut, ResultSuccess())
|
||||
R_CONVERT(svc::ResultSessionClosed, ResultSuccess())
|
||||
} R_END_TRY_CATCH;
|
||||
/* ReplyImpl should *always* return an error. */
|
||||
AMS_ASSERT(false);
|
||||
}
|
||||
|
||||
Result CreateSession(Handle *out_server_handle, Handle *out_client_handle) {
|
||||
R_TRY_CATCH(svcCreateSession(out_server_handle, out_client_handle, 0, 0)) {
|
||||
R_CONVERT(svc::ResultOutOfResource, sf::hipc::ResultOutOfSessions());
|
||||
} R_END_TRY_CATCH;
|
||||
return ResultSuccess();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* Copyright (c) 2018-2019 Atmosphère-NX
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms and conditions of the GNU General Public License,
|
||||
* version 2, as published by the Free Software Foundation.
|
||||
*
|
||||
* This program is distributed in the hope it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include <stratosphere.hpp>
|
||||
#include "sf_hipc_mitm_query_api.hpp"
|
||||
|
||||
namespace ams::sf::hipc::impl {
|
||||
|
||||
namespace {
|
||||
|
||||
class MitmQueryService : public IServiceObject {
|
||||
private:
|
||||
enum class CommandId {
|
||||
ShouldMitm = 65000,
|
||||
};
|
||||
private:
|
||||
ServerManagerBase::MitmQueryFunction query_function;
|
||||
public:
|
||||
MitmQueryService(ServerManagerBase::MitmQueryFunction qf) : query_function(qf) { /* ... */ }
|
||||
|
||||
void ShouldMitm(sf::Out<bool> out, const sm::MitmProcessInfo &client_info) {
|
||||
out.SetValue(this->query_function(client_info));
|
||||
}
|
||||
public:
|
||||
DEFINE_SERVICE_DISPATCH_TABLE {
|
||||
MAKE_SERVICE_COMMAND_META(ShouldMitm),
|
||||
};
|
||||
};
|
||||
|
||||
/* Globals. */
|
||||
os::Mutex g_query_server_lock;
|
||||
bool g_constructed_server = false;
|
||||
bool g_registered_any = false;
|
||||
|
||||
void QueryServerProcessThreadMain(void *query_server) {
|
||||
reinterpret_cast<ServerManagerBase *>(query_server)->LoopProcess();
|
||||
}
|
||||
|
||||
constexpr size_t QueryServerProcessThreadStackSize = 0x4000;
|
||||
constexpr int QueryServerProcessThreadPriority = 27;
|
||||
os::StaticThread<QueryServerProcessThreadStackSize> g_query_server_process_thread;
|
||||
|
||||
constexpr size_t MaxServers = 0;
|
||||
TYPED_STORAGE(sf::hipc::ServerManager<MaxServers>) g_query_server_storage;
|
||||
|
||||
}
|
||||
|
||||
void RegisterMitmQueryHandle(Handle query_handle, ServerManagerBase::MitmQueryFunction query_func) {
|
||||
std::scoped_lock lk(g_query_server_lock);
|
||||
|
||||
|
||||
if (!g_constructed_server) {
|
||||
new (GetPointer(g_query_server_storage)) sf::hipc::ServerManager<MaxServers>();
|
||||
g_constructed_server = true;
|
||||
}
|
||||
|
||||
R_ASSERT(GetPointer(g_query_server_storage)->RegisterSession(query_handle, cmif::ServiceObjectHolder(std::make_shared<MitmQueryService>(query_func))));
|
||||
|
||||
if (!g_registered_any) {
|
||||
R_ASSERT(g_query_server_process_thread.Initialize(&QueryServerProcessThreadMain, GetPointer(g_query_server_storage), QueryServerProcessThreadPriority));
|
||||
R_ASSERT(g_query_server_process_thread.Start());
|
||||
g_registered_any = true;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* Copyright (c) 2018-2019 Atmosphère-NX
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms and conditions of the GNU General Public License,
|
||||
* version 2, as published by the Free Software Foundation.
|
||||
*
|
||||
* This program is distributed in the hope it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#pragma once
|
||||
#include <stratosphere.hpp>
|
||||
|
||||
namespace ams::sf::hipc::impl {
|
||||
|
||||
void RegisterMitmQueryHandle(Handle query_handle, ServerManagerBase::MitmQueryFunction query_func);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
/*
|
||||
* Copyright (c) 2018-2019 Atmosphère-NX
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms and conditions of the GNU General Public License,
|
||||
* version 2, as published by the Free Software Foundation.
|
||||
*
|
||||
* This program is distributed in the hope it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include <stratosphere.hpp>
|
||||
|
||||
namespace ams::sf::hipc {
|
||||
|
||||
namespace impl {
|
||||
|
||||
class HipcManager : public IServiceObject {
|
||||
private:
|
||||
enum class CommandId {
|
||||
ConvertCurrentObjectToDomain = 0,
|
||||
CopyFromCurrentDomain = 1,
|
||||
CloneCurrentObject = 2,
|
||||
QueryPointerBufferSize = 3,
|
||||
CloneCurrentObjectEx = 4,
|
||||
};
|
||||
private:
|
||||
ServerDomainSessionManager *manager;
|
||||
ServerSession *session;
|
||||
bool is_mitm_session;
|
||||
private:
|
||||
Result CloneCurrentObjectImpl(Handle *out_client_handle, ServerSessionManager *tagged_manager) {
|
||||
/* Clone the object. */
|
||||
cmif::ServiceObjectHolder &&clone = this->session->srv_obj_holder.Clone();
|
||||
R_UNLESS(clone, sf::hipc::ResultDomainObjectNotFound());
|
||||
|
||||
/* Create new session handles. */
|
||||
Handle server_handle;
|
||||
R_ASSERT(hipc::CreateSession(&server_handle, out_client_handle));
|
||||
|
||||
/* Register with manager. */
|
||||
if (!is_mitm_session) {
|
||||
R_ASSERT(tagged_manager->RegisterSession(server_handle, std::move(clone)));
|
||||
} else {
|
||||
/* Clone the forward service. */
|
||||
std::shared_ptr<::Service> new_forward_service = std::move(ServerSession::CreateForwardService());
|
||||
R_ASSERT(serviceClone(this->session->forward_service.get(), new_forward_service.get()));
|
||||
R_ASSERT(tagged_manager->RegisterMitmSession(server_handle, std::move(clone), std::move(new_forward_service)));
|
||||
}
|
||||
|
||||
return ResultSuccess();
|
||||
}
|
||||
public:
|
||||
explicit HipcManager(ServerDomainSessionManager *m, ServerSession *s) : manager(m), session(s), is_mitm_session(s->forward_service != nullptr) {
|
||||
/* ... */
|
||||
}
|
||||
|
||||
Result ConvertCurrentObjectToDomain(sf::Out<cmif::DomainObjectId> out) {
|
||||
/* Allocate a domain. */
|
||||
auto domain = this->manager->AllocateDomainServiceObject();
|
||||
R_UNLESS(domain, sf::hipc::ResultOutOfDomains());
|
||||
auto domain_guard = SCOPE_GUARD { cmif::ServerDomainManager::DestroyDomainServiceObject(static_cast<cmif::DomainServiceObject *>(domain)); };
|
||||
|
||||
cmif::DomainObjectId object_id = cmif::InvalidDomainObjectId;
|
||||
|
||||
cmif::ServiceObjectHolder new_holder;
|
||||
|
||||
if (this->is_mitm_session) {
|
||||
/* If we're a mitm session, we need to convert the remote session to domain. */
|
||||
AMS_ASSERT(session->forward_service->own_handle);
|
||||
R_TRY(serviceConvertToDomain(session->forward_service.get()));
|
||||
|
||||
/* The object ID reservation cannot fail here, as that would cause desynchronization from target domain. */
|
||||
object_id = cmif::DomainObjectId{session->forward_service->object_id};
|
||||
domain->ReserveSpecificIds(&object_id, 1);
|
||||
|
||||
/* Create new object. */
|
||||
cmif::MitmDomainServiceObject *domain_ptr = static_cast<cmif::MitmDomainServiceObject *>(domain);
|
||||
new_holder = cmif::ServiceObjectHolder(std::move(std::shared_ptr<cmif::MitmDomainServiceObject>(domain_ptr, cmif::ServerDomainManager::DestroyDomainServiceObject)));
|
||||
} else {
|
||||
/* We're not a mitm session. Reserve a new object in the domain. */
|
||||
R_TRY(domain->ReserveIds(&object_id, 1));
|
||||
|
||||
/* Create new object. */
|
||||
cmif::DomainServiceObject *domain_ptr = static_cast<cmif::DomainServiceObject *>(domain);
|
||||
new_holder = cmif::ServiceObjectHolder(std::move(std::shared_ptr<cmif::DomainServiceObject>(domain_ptr, cmif::ServerDomainManager::DestroyDomainServiceObject)));
|
||||
}
|
||||
|
||||
AMS_ASSERT(object_id != cmif::InvalidDomainObjectId);
|
||||
AMS_ASSERT(static_cast<bool>(new_holder));
|
||||
|
||||
/* We succeeded! */
|
||||
domain_guard.Cancel();
|
||||
domain->RegisterObject(object_id, std::move(session->srv_obj_holder));
|
||||
session->srv_obj_holder = std::move(new_holder);
|
||||
out.SetValue(object_id);
|
||||
|
||||
return ResultSuccess();
|
||||
}
|
||||
|
||||
Result CopyFromCurrentDomain(sf::OutMoveHandle out, cmif::DomainObjectId object_id) {
|
||||
/* Get domain. */
|
||||
auto domain = this->session->srv_obj_holder.GetServiceObject<cmif::DomainServiceObject>();
|
||||
R_UNLESS(domain != nullptr, sf::hipc::ResultTargetNotDomain());
|
||||
|
||||
/* Get domain object. */
|
||||
auto &&object = domain->GetObject(object_id);
|
||||
if (!object) {
|
||||
R_UNLESS(this->is_mitm_session, sf::hipc::ResultDomainObjectNotFound());
|
||||
return cmifCopyFromCurrentDomain(this->session->forward_service->session, object_id.value, out.GetHandlePointer());
|
||||
}
|
||||
|
||||
if (!this->is_mitm_session || object_id.value != serviceGetObjectId(this->session->forward_service.get())) {
|
||||
/* Create new session handles. */
|
||||
Handle server_handle;
|
||||
R_ASSERT(hipc::CreateSession(&server_handle, out.GetHandlePointer()));
|
||||
|
||||
/* Register. */
|
||||
R_ASSERT(this->manager->RegisterSession(server_handle, std::move(object)));
|
||||
} else {
|
||||
/* Copy from the target domain. */
|
||||
Handle new_forward_target;
|
||||
R_TRY(cmifCopyFromCurrentDomain(this->session->forward_service->session, object_id.value, &new_forward_target));
|
||||
|
||||
/* Create new session handles. */
|
||||
Handle server_handle;
|
||||
R_ASSERT(hipc::CreateSession(&server_handle, out.GetHandlePointer()));
|
||||
|
||||
/* Register. */
|
||||
std::shared_ptr<::Service> new_forward_service = std::move(ServerSession::CreateForwardService());
|
||||
serviceCreate(new_forward_service.get(), new_forward_target);
|
||||
R_ASSERT(this->manager->RegisterMitmSession(server_handle, std::move(object), std::move(new_forward_service)));
|
||||
}
|
||||
|
||||
return ResultSuccess();
|
||||
}
|
||||
|
||||
Result CloneCurrentObject(sf::OutMoveHandle out) {
|
||||
return this->CloneCurrentObjectImpl(out.GetHandlePointer(), this->manager);
|
||||
}
|
||||
|
||||
void QueryPointerBufferSize(sf::Out<u16> out) {
|
||||
out.SetValue(this->session->pointer_buffer.GetSize());
|
||||
}
|
||||
|
||||
Result CloneCurrentObjectEx(sf::OutMoveHandle out, u32 tag) {
|
||||
return this->CloneCurrentObjectImpl(out.GetHandlePointer(), this->manager->GetSessionManagerByTag(tag));
|
||||
}
|
||||
|
||||
public:
|
||||
DEFINE_SERVICE_DISPATCH_TABLE {
|
||||
MAKE_SERVICE_COMMAND_META(ConvertCurrentObjectToDomain),
|
||||
MAKE_SERVICE_COMMAND_META(CopyFromCurrentDomain),
|
||||
MAKE_SERVICE_COMMAND_META(CloneCurrentObject),
|
||||
MAKE_SERVICE_COMMAND_META(QueryPointerBufferSize),
|
||||
MAKE_SERVICE_COMMAND_META(CloneCurrentObjectEx),
|
||||
};
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
Result ServerDomainSessionManager::DispatchManagerRequest(ServerSession *session, const cmif::PointerAndSize &in_message, const cmif::PointerAndSize &out_message) {
|
||||
/* Make a stack object, and pass a shared pointer to it to DispatchRequest. */
|
||||
/* Note: This is safe, as no additional references to the hipc manager can ever be stored. */
|
||||
/* The shared pointer to stack object is definitely gross, though. */
|
||||
impl::HipcManager hipc_manager(this, session);
|
||||
return this->DispatchRequest(cmif::ServiceObjectHolder(std::move(ServiceObjectTraits<impl::HipcManager>::SharedPointerHelper::GetEmptyDeleteSharedPointer(&hipc_manager))), session, in_message, out_message);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
/*
|
||||
* Copyright (c) 2018-2019 Atmosphère-NX
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms and conditions of the GNU General Public License,
|
||||
* version 2, as published by the Free Software Foundation.
|
||||
*
|
||||
* This program is distributed in the hope it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include <stratosphere.hpp>
|
||||
#include "sf_hipc_mitm_query_api.hpp"
|
||||
|
||||
namespace ams::sf::hipc {
|
||||
|
||||
ServerManagerBase::ServerBase::~ServerBase() { /* Pure virtual destructor, to prevent linker errors. */ }
|
||||
|
||||
Result ServerManagerBase::InstallMitmServerImpl(Handle *out_port_handle, sm::ServiceName service_name, ServerManagerBase::MitmQueryFunction query_func) {
|
||||
/* Install the Mitm. */
|
||||
Handle query_handle;
|
||||
R_TRY(sm::mitm::InstallMitm(out_port_handle, &query_handle, service_name));
|
||||
|
||||
/* Register the query handle. */
|
||||
impl::RegisterMitmQueryHandle(query_handle, query_func);
|
||||
return ResultSuccess();
|
||||
}
|
||||
|
||||
void ServerManagerBase::RegisterSessionToWaitList(ServerSession *session) {
|
||||
session->has_received = false;
|
||||
|
||||
/* Set user data tag. */
|
||||
session->SetUserData(static_cast<uintptr_t>(UserDataTag::Session));
|
||||
|
||||
this->RegisterToWaitList(session);
|
||||
}
|
||||
|
||||
void ServerManagerBase::RegisterToWaitList(os::WaitableHolder *holder) {
|
||||
std::scoped_lock lk(this->waitlist_mutex);
|
||||
this->waitlist.LinkWaitableHolder(holder);
|
||||
this->notify_event.Signal();
|
||||
}
|
||||
|
||||
void ServerManagerBase::ProcessWaitList() {
|
||||
std::scoped_lock lk(this->waitlist_mutex);
|
||||
this->waitable_manager.MoveAllFrom(&this->waitlist);
|
||||
}
|
||||
|
||||
os::WaitableHolder *ServerManagerBase::WaitSignaled() {
|
||||
std::scoped_lock lk(this->waitable_selection_mutex);
|
||||
while (true) {
|
||||
this->ProcessWaitList();
|
||||
auto selected = this->waitable_manager.WaitAny();
|
||||
if (selected == &this->request_stop_event_holder) {
|
||||
return nullptr;
|
||||
} else if (selected == &this->notify_event_holder) {
|
||||
this->notify_event.Reset();
|
||||
} else {
|
||||
selected->UnlinkFromWaitableManager();
|
||||
return selected;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ServerManagerBase::ResumeProcessing() {
|
||||
this->request_stop_event.Reset();
|
||||
}
|
||||
|
||||
void ServerManagerBase::RequestStopProcessing() {
|
||||
this->request_stop_event.Signal();
|
||||
}
|
||||
|
||||
void ServerManagerBase::AddUserWaitableHolder(os::WaitableHolder *waitable) {
|
||||
const auto user_data_tag = static_cast<UserDataTag>(waitable->GetUserData());
|
||||
AMS_ASSERT(user_data_tag != UserDataTag::Server);
|
||||
AMS_ASSERT(user_data_tag != UserDataTag::MitmServer);
|
||||
AMS_ASSERT(user_data_tag != UserDataTag::Session);
|
||||
this->RegisterToWaitList(waitable);
|
||||
}
|
||||
|
||||
Result ServerManagerBase::ProcessForServer(os::WaitableHolder *holder) {
|
||||
AMS_ASSERT(static_cast<UserDataTag>(holder->GetUserData()) == UserDataTag::Server);
|
||||
|
||||
ServerBase *server = static_cast<ServerBase *>(holder);
|
||||
ON_SCOPE_EXIT { this->RegisterToWaitList(server); };
|
||||
|
||||
/* Create resources for new session. */
|
||||
cmif::ServiceObjectHolder obj;
|
||||
std::shared_ptr<::Service> fsrv;
|
||||
server->CreateSessionObjectHolder(&obj, &fsrv);
|
||||
|
||||
/* Not a mitm server, so we must have no forward service. */
|
||||
AMS_ASSERT(fsrv == nullptr);
|
||||
|
||||
/* Try to accept. */
|
||||
return this->AcceptSession(server->port_handle, std::move(obj));
|
||||
}
|
||||
|
||||
Result ServerManagerBase::ProcessForMitmServer(os::WaitableHolder *holder) {
|
||||
AMS_ASSERT(static_cast<UserDataTag>(holder->GetUserData()) == UserDataTag::MitmServer);
|
||||
|
||||
ServerBase *server = static_cast<ServerBase *>(holder);
|
||||
ON_SCOPE_EXIT { this->RegisterToWaitList(server); };
|
||||
|
||||
/* Create resources for new session. */
|
||||
cmif::ServiceObjectHolder obj;
|
||||
std::shared_ptr<::Service> fsrv;
|
||||
server->CreateSessionObjectHolder(&obj, &fsrv);
|
||||
|
||||
/* Mitm server, so we must have forward service. */
|
||||
AMS_ASSERT(fsrv != nullptr);
|
||||
|
||||
/* Try to accept. */
|
||||
return this->AcceptMitmSession(server->port_handle, std::move(obj), std::move(fsrv));
|
||||
}
|
||||
|
||||
Result ServerManagerBase::ProcessForSession(os::WaitableHolder *holder) {
|
||||
AMS_ASSERT(static_cast<UserDataTag>(holder->GetUserData()) == UserDataTag::Session);
|
||||
|
||||
ServerSession *session = static_cast<ServerSession *>(holder);
|
||||
|
||||
cmif::PointerAndSize tls_message(armGetTls(), hipc::TlsMessageBufferSize);
|
||||
const cmif::PointerAndSize &saved_message = session->saved_message;
|
||||
AMS_ASSERT(tls_message.GetSize() == saved_message.GetSize());
|
||||
if (!session->has_received) {
|
||||
R_TRY(this->ReceiveRequest(session, tls_message));
|
||||
session->has_received = true;
|
||||
std::memcpy(saved_message.GetPointer(), tls_message.GetPointer(), tls_message.GetSize());
|
||||
} else {
|
||||
/* We were deferred and are re-receiving, so just memcpy. */
|
||||
std::memcpy(tls_message.GetPointer(), saved_message.GetPointer(), tls_message.GetSize());
|
||||
}
|
||||
|
||||
/* Treat a meta "Context Invalidated" message as a success. */
|
||||
R_TRY_CATCH(this->ProcessRequest(session, tls_message)) {
|
||||
R_CONVERT(sf::impl::ResultRequestInvalidated, ResultSuccess());
|
||||
} R_END_TRY_CATCH;
|
||||
|
||||
return ResultSuccess();
|
||||
}
|
||||
|
||||
void ServerManagerBase::ProcessDeferredSessions() {
|
||||
/* Iterate over the list of deferred sessions, and see if we can't do anything. */
|
||||
std::scoped_lock lk(this->deferred_session_mutex);
|
||||
|
||||
/* Undeferring a request may undefer another request. We'll continue looping until everything is stable. */
|
||||
bool needs_undefer_all = true;
|
||||
while (needs_undefer_all) {
|
||||
needs_undefer_all = false;
|
||||
|
||||
auto it = this->deferred_session_list.begin();
|
||||
while (it != this->deferred_session_list.end()) {
|
||||
ServerSession *session = static_cast<ServerSession *>(&*it);
|
||||
R_TRY_CATCH(this->ProcessForSession(session)) {
|
||||
R_CATCH(sf::ResultRequestDeferred) {
|
||||
/* Session is still deferred, so let's continue. */
|
||||
it++;
|
||||
continue;
|
||||
}
|
||||
R_CATCH(sf::impl::ResultRequestInvalidated) {
|
||||
/* Session is no longer deferred! */
|
||||
it = this->deferred_session_list.erase(it);
|
||||
needs_undefer_all = true;
|
||||
continue;
|
||||
}
|
||||
} R_END_TRY_CATCH_WITH_ASSERT;
|
||||
|
||||
/* We succeeded! Remove from deferred list. */
|
||||
it = this->deferred_session_list.erase(it);
|
||||
needs_undefer_all = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Result ServerManagerBase::Process(os::WaitableHolder *holder) {
|
||||
switch (static_cast<UserDataTag>(holder->GetUserData())) {
|
||||
case UserDataTag::Server:
|
||||
return this->ProcessForServer(holder);
|
||||
break;
|
||||
case UserDataTag::MitmServer:
|
||||
return this->ProcessForMitmServer(holder);
|
||||
break;
|
||||
case UserDataTag::Session:
|
||||
/* Try to process for session. */
|
||||
R_TRY_CATCH(this->ProcessForSession(holder)) {
|
||||
R_CATCH(sf::ResultRequestDeferred) {
|
||||
/* The session was deferred, so push it onto the deferred session list. */
|
||||
std::scoped_lock lk(this->deferred_session_mutex);
|
||||
this->deferred_session_list.push_back(*static_cast<ServerSession *>(holder));
|
||||
return ResultSuccess();
|
||||
}
|
||||
} R_END_TRY_CATCH;
|
||||
|
||||
/* We successfully invoked a command...so let's see if anything can be undeferred. */
|
||||
this->ProcessDeferredSessions();
|
||||
return ResultSuccess();
|
||||
break;
|
||||
AMS_UNREACHABLE_DEFAULT_CASE();
|
||||
}
|
||||
}
|
||||
|
||||
bool ServerManagerBase::WaitAndProcessImpl() {
|
||||
auto waitable = this->WaitSignaled();
|
||||
if (!waitable) {
|
||||
return false;
|
||||
}
|
||||
R_ASSERT(this->Process(waitable));
|
||||
return true;
|
||||
}
|
||||
|
||||
void ServerManagerBase::WaitAndProcess() {
|
||||
this->WaitAndProcessImpl();
|
||||
}
|
||||
|
||||
void ServerManagerBase::LoopProcess() {
|
||||
while (this->WaitAndProcessImpl()) {
|
||||
/* ... */
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
/*
|
||||
* Copyright (c) 2018-2019 Atmosphère-NX
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms and conditions of the GNU General Public License,
|
||||
* version 2, as published by the Free Software Foundation.
|
||||
*
|
||||
* This program is distributed in the hope it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include <stratosphere.hpp>
|
||||
|
||||
namespace ams::sf::hipc {
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr inline void PreProcessCommandBufferForMitm(const cmif::ServiceDispatchContext &ctx, const cmif::PointerAndSize &pointer_buffer, uintptr_t cmd_buffer) {
|
||||
/* TODO: Less gross method of editing command buffer? */
|
||||
if (ctx.request.meta.send_pid) {
|
||||
constexpr u64 MitmProcessIdTag = 0xFFFE000000000000ul;
|
||||
constexpr u64 OldProcessIdMask = 0x0000FFFFFFFFFFFFul;
|
||||
u64 *process_id = reinterpret_cast<u64 *>(cmd_buffer + sizeof(HipcHeader) + sizeof(HipcSpecialHeader));
|
||||
*process_id = (MitmProcessIdTag) | (*process_id & OldProcessIdMask);
|
||||
}
|
||||
|
||||
if (ctx.request.meta.num_recv_statics) {
|
||||
/* TODO: Can we do this without gross bit-hackery? */
|
||||
reinterpret_cast<HipcHeader *>(cmd_buffer)->recv_static_mode = 2;
|
||||
const uintptr_t old_recv_list_entry = reinterpret_cast<uintptr_t>(ctx.request.data.recv_list);
|
||||
const size_t old_recv_list_offset = old_recv_list_entry - util::AlignDown(old_recv_list_entry, TlsMessageBufferSize);
|
||||
*reinterpret_cast<HipcRecvListEntry *>(cmd_buffer + old_recv_list_offset) = hipcMakeRecvStatic(pointer_buffer.GetPointer(), pointer_buffer.GetSize());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Result ServerSession::ForwardRequest(const cmif::ServiceDispatchContext &ctx) const {
|
||||
AMS_ASSERT(this->IsMitmSession());
|
||||
/* TODO: Support non-TLS messages? */
|
||||
AMS_ASSERT(this->saved_message.GetPointer() != nullptr);
|
||||
AMS_ASSERT(this->saved_message.GetSize() == TlsMessageBufferSize);
|
||||
|
||||
/* Copy saved TLS in. */
|
||||
std::memcpy(armGetTls(), this->saved_message.GetPointer(), this->saved_message.GetSize());
|
||||
|
||||
/* Prepare buffer. */
|
||||
PreProcessCommandBufferForMitm(ctx, this->pointer_buffer, reinterpret_cast<uintptr_t>(armGetTls()));
|
||||
|
||||
/* Dispatch forwards. */
|
||||
R_TRY(svcSendSyncRequest(this->forward_service->session));
|
||||
|
||||
/* Parse, to ensure we catch any copy handles and close them. */
|
||||
{
|
||||
const auto response = hipcParseResponse(armGetTls());
|
||||
if (response.num_copy_handles) {
|
||||
ctx.handles_to_close->num_handles = response.num_copy_handles;
|
||||
for (size_t i = 0; i < response.num_copy_handles; i++) {
|
||||
ctx.handles_to_close->handles[i] = response.copy_handles[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ResultSuccess();
|
||||
}
|
||||
|
||||
void ServerSessionManager::DestroySession(ServerSession *session) {
|
||||
/* Destroy object. */
|
||||
session->~ServerSession();
|
||||
/* Free object memory. */
|
||||
this->FreeSession(session);
|
||||
}
|
||||
|
||||
void ServerSessionManager::CloseSessionImpl(ServerSession *session) {
|
||||
const Handle session_handle = session->session_handle;
|
||||
this->DestroySession(session);
|
||||
R_ASSERT(svcCloseHandle(session_handle));
|
||||
}
|
||||
|
||||
Result ServerSessionManager::RegisterSessionImpl(ServerSession *session_memory, Handle session_handle, cmif::ServiceObjectHolder &&obj) {
|
||||
/* Create session object. */
|
||||
new (session_memory) ServerSession(session_handle, std::forward<cmif::ServiceObjectHolder>(obj));
|
||||
/* Assign session resources. */
|
||||
session_memory->pointer_buffer = this->GetSessionPointerBuffer(session_memory);
|
||||
session_memory->saved_message = this->GetSessionSavedMessageBuffer(session_memory);
|
||||
/* Register to wait list. */
|
||||
this->RegisterSessionToWaitList(session_memory);
|
||||
return ResultSuccess();
|
||||
}
|
||||
|
||||
Result ServerSessionManager::AcceptSessionImpl(ServerSession *session_memory, Handle port_handle, cmif::ServiceObjectHolder &&obj) {
|
||||
/* Create session handle. */
|
||||
Handle session_handle;
|
||||
R_TRY(svcAcceptSession(&session_handle, port_handle));
|
||||
bool succeeded = false;
|
||||
ON_SCOPE_EXIT {
|
||||
if (!succeeded) {
|
||||
R_ASSERT(svcCloseHandle(session_handle));
|
||||
}
|
||||
};
|
||||
/* Register session. */
|
||||
R_TRY(this->RegisterSessionImpl(session_memory, session_handle, std::forward<cmif::ServiceObjectHolder>(obj)));
|
||||
succeeded = true;
|
||||
return ResultSuccess();
|
||||
}
|
||||
|
||||
Result ServerSessionManager::RegisterMitmSessionImpl(ServerSession *session_memory, Handle mitm_session_handle, cmif::ServiceObjectHolder &&obj, std::shared_ptr<::Service> &&fsrv) {
|
||||
/* Create session object. */
|
||||
new (session_memory) ServerSession(mitm_session_handle, std::forward<cmif::ServiceObjectHolder>(obj), std::forward<std::shared_ptr<::Service>>(fsrv));
|
||||
/* Assign session resources. */
|
||||
session_memory->pointer_buffer = this->GetSessionPointerBuffer(session_memory);
|
||||
session_memory->saved_message = this->GetSessionSavedMessageBuffer(session_memory);
|
||||
/* Validate session pointer buffer. */
|
||||
AMS_ASSERT(session_memory->pointer_buffer.GetSize() >= session_memory->forward_service->pointer_buffer_size);
|
||||
session_memory->pointer_buffer = cmif::PointerAndSize(session_memory->pointer_buffer.GetAddress(), session_memory->forward_service->pointer_buffer_size);
|
||||
/* Register to wait list. */
|
||||
this->RegisterSessionToWaitList(session_memory);
|
||||
return ResultSuccess();
|
||||
}
|
||||
|
||||
Result ServerSessionManager::AcceptMitmSessionImpl(ServerSession *session_memory, Handle mitm_port_handle, cmif::ServiceObjectHolder &&obj, std::shared_ptr<::Service> &&fsrv) {
|
||||
/* Create session handle. */
|
||||
Handle mitm_session_handle;
|
||||
R_TRY(svcAcceptSession(&mitm_session_handle, mitm_port_handle));
|
||||
bool succeeded = false;
|
||||
ON_SCOPE_EXIT {
|
||||
if (!succeeded) {
|
||||
R_ASSERT(svcCloseHandle(mitm_session_handle));
|
||||
}
|
||||
};
|
||||
/* Register session. */
|
||||
R_TRY(this->RegisterMitmSessionImpl(session_memory, mitm_session_handle, std::forward<cmif::ServiceObjectHolder>(obj), std::forward<std::shared_ptr<::Service>>(fsrv)));
|
||||
succeeded = true;
|
||||
return ResultSuccess();
|
||||
}
|
||||
|
||||
Result ServerSessionManager::RegisterSession(Handle session_handle, cmif::ServiceObjectHolder &&obj) {
|
||||
/* We don't actually care about what happens to the session. It'll get linked. */
|
||||
ServerSession *session_ptr = nullptr;
|
||||
return this->RegisterSession(&session_ptr, session_handle, std::forward<cmif::ServiceObjectHolder>(obj));
|
||||
}
|
||||
|
||||
Result ServerSessionManager::AcceptSession(Handle port_handle, cmif::ServiceObjectHolder &&obj) {
|
||||
/* We don't actually care about what happens to the session. It'll get linked. */
|
||||
ServerSession *session_ptr = nullptr;
|
||||
return this->AcceptSession(&session_ptr, port_handle, std::forward<cmif::ServiceObjectHolder>(obj));
|
||||
}
|
||||
|
||||
Result ServerSessionManager::RegisterMitmSession(Handle mitm_session_handle, cmif::ServiceObjectHolder &&obj, std::shared_ptr<::Service> &&fsrv) {
|
||||
/* We don't actually care about what happens to the session. It'll get linked. */
|
||||
ServerSession *session_ptr = nullptr;
|
||||
return this->RegisterMitmSession(&session_ptr, mitm_session_handle, std::forward<cmif::ServiceObjectHolder>(obj), std::forward<std::shared_ptr<::Service>>(fsrv));
|
||||
}
|
||||
|
||||
Result ServerSessionManager::AcceptMitmSession(Handle mitm_port_handle, cmif::ServiceObjectHolder &&obj, std::shared_ptr<::Service> &&fsrv) {
|
||||
/* We don't actually care about what happens to the session. It'll get linked. */
|
||||
ServerSession *session_ptr = nullptr;
|
||||
return this->AcceptMitmSession(&session_ptr, mitm_port_handle, std::forward<cmif::ServiceObjectHolder>(obj), std::forward<std::shared_ptr<::Service>>(fsrv));
|
||||
}
|
||||
|
||||
Result ServerSessionManager::ReceiveRequestImpl(ServerSession *session, const cmif::PointerAndSize &message) {
|
||||
const cmif::PointerAndSize &pointer_buffer = session->pointer_buffer;
|
||||
|
||||
/* If the receive list is odd, we may need to receive repeatedly. */
|
||||
while (true) {
|
||||
if (pointer_buffer.GetPointer()) {
|
||||
hipcMakeRequestInline(message.GetPointer(),
|
||||
.type = CmifCommandType_Invalid,
|
||||
.num_recv_statics = HIPC_AUTO_RECV_STATIC,
|
||||
).recv_list[0] = hipcMakeRecvStatic(pointer_buffer.GetPointer(), pointer_buffer.GetSize());
|
||||
} else {
|
||||
hipcMakeRequestInline(message.GetPointer(),
|
||||
.type = CmifCommandType_Invalid,
|
||||
);
|
||||
}
|
||||
hipc::ReceiveResult recv_result;
|
||||
R_TRY(hipc::Receive(&recv_result, session->session_handle, message));
|
||||
switch (recv_result) {
|
||||
case hipc::ReceiveResult::Success:
|
||||
session->is_closed = false;
|
||||
return ResultSuccess();
|
||||
case hipc::ReceiveResult::Closed:
|
||||
session->is_closed = true;
|
||||
return ResultSuccess();
|
||||
case hipc::ReceiveResult::NeedsRetry:
|
||||
continue;
|
||||
AMS_UNREACHABLE_DEFAULT_CASE();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
NX_CONSTEXPR u32 GetCmifCommandType(const cmif::PointerAndSize &message) {
|
||||
HipcHeader hdr = {};
|
||||
__builtin_memcpy(&hdr, message.GetPointer(), sizeof(hdr));
|
||||
return hdr.type;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Result ServerSessionManager::ProcessRequest(ServerSession *session, const cmif::PointerAndSize &message) {
|
||||
if (session->is_closed) {
|
||||
this->CloseSessionImpl(session);
|
||||
return ResultSuccess();
|
||||
}
|
||||
switch (GetCmifCommandType(message)) {
|
||||
case CmifCommandType_Close:
|
||||
{
|
||||
this->CloseSessionImpl(session);
|
||||
return ResultSuccess();
|
||||
}
|
||||
default:
|
||||
{
|
||||
R_TRY_CATCH(this->ProcessRequestImpl(session, message, message)) {
|
||||
R_CATCH(sf::impl::ResultRequestContextChanged) {
|
||||
/* A meta message changing the request context has been sent. */
|
||||
return R_CURRENT_RESULT;
|
||||
}
|
||||
R_CATCH_ALL() {
|
||||
/* All other results indicate something went very wrong. */
|
||||
this->CloseSessionImpl(session);
|
||||
return ResultSuccess();
|
||||
}
|
||||
} R_END_TRY_CATCH;
|
||||
|
||||
/* We succeeded, so we can process future messages on this session. */
|
||||
this->RegisterSessionToWaitList(session);
|
||||
return ResultSuccess();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Result ServerSessionManager::ProcessRequestImpl(ServerSession *session, const cmif::PointerAndSize &in_message, const cmif::PointerAndSize &out_message) {
|
||||
/* TODO: Inline context support, retrieve from raw data + 0xC. */
|
||||
const auto cmif_command_type = GetCmifCommandType(in_message);
|
||||
switch (cmif_command_type) {
|
||||
case CmifCommandType_Request:
|
||||
case CmifCommandType_RequestWithContext:
|
||||
return this->DispatchRequest(session->srv_obj_holder.Clone(), session, in_message, out_message);
|
||||
case CmifCommandType_Control:
|
||||
case CmifCommandType_ControlWithContext:
|
||||
return this->DispatchManagerRequest(session, in_message, out_message);
|
||||
default:
|
||||
return sf::hipc::ResultUnknownCommandType();
|
||||
}
|
||||
}
|
||||
|
||||
Result ServerSessionManager::DispatchManagerRequest(ServerSession *session, const cmif::PointerAndSize &in_message, const cmif::PointerAndSize &out_message) {
|
||||
/* This will get overridden by ... WithDomain class. */
|
||||
return sf::ResultNotSupported();
|
||||
}
|
||||
|
||||
Result ServerSessionManager::DispatchRequest(cmif::ServiceObjectHolder &&obj_holder, ServerSession *session, const cmif::PointerAndSize &in_message, const cmif::PointerAndSize &out_message) {
|
||||
/* Create request context. */
|
||||
cmif::HandlesToClose handles_to_close = {};
|
||||
cmif::ServiceDispatchContext dispatch_ctx = {
|
||||
.srv_obj = obj_holder.GetServiceObjectUnsafe(),
|
||||
.manager = this,
|
||||
.session = session,
|
||||
.processor = nullptr, /* Filled in by template implementations. */
|
||||
.handles_to_close = &handles_to_close,
|
||||
.pointer_buffer = session->pointer_buffer,
|
||||
.in_message_buffer = in_message,
|
||||
.out_message_buffer = out_message,
|
||||
.request = hipcParseRequest(in_message.GetPointer()),
|
||||
};
|
||||
|
||||
/* Validate message sizes. */
|
||||
const uintptr_t in_message_buffer_end = in_message.GetAddress() + in_message.GetSize();
|
||||
const uintptr_t in_raw_addr = reinterpret_cast<uintptr_t>(dispatch_ctx.request.data.data_words);
|
||||
const size_t in_raw_size = dispatch_ctx.request.meta.num_data_words * sizeof(u32);
|
||||
/* Note: Nintendo does not validate this size before subtracting 0x10 from it. This is not exploitable. */
|
||||
R_UNLESS(in_raw_size >= 0x10, sf::hipc::ResultInvalidRequestSize());
|
||||
R_UNLESS(in_raw_addr + in_raw_size <= in_message_buffer_end, sf::hipc::ResultInvalidRequestSize());
|
||||
const uintptr_t recv_list_end = reinterpret_cast<uintptr_t>(dispatch_ctx.request.data.recv_list + dispatch_ctx.request.meta.num_recv_statics);
|
||||
R_UNLESS(recv_list_end <= in_message_buffer_end, sf::hipc::ResultInvalidRequestSize());
|
||||
|
||||
/* CMIF has 0x10 of padding in raw data, and requires 0x10 alignment. */
|
||||
const cmif::PointerAndSize in_raw_data(util::AlignUp(in_raw_addr, 0x10), in_raw_size - 0x10);
|
||||
|
||||
/* Invoke command handler. */
|
||||
R_TRY(obj_holder.ProcessMessage(dispatch_ctx, in_raw_data));
|
||||
|
||||
/* Reply. */
|
||||
{
|
||||
ON_SCOPE_EXIT {
|
||||
for (size_t i = 0; i < handles_to_close.num_handles; i++) {
|
||||
R_ASSERT(svcCloseHandle(handles_to_close.handles[i]));
|
||||
}
|
||||
};
|
||||
R_TRY(hipc::Reply(session->session_handle, out_message));
|
||||
}
|
||||
|
||||
return ResultSuccess();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user