Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
191 changes: 130 additions & 61 deletions src/moonlight-server/api/endpoints.cpp
Original file line number Diff line number Diff line change
@@ -1,13 +1,57 @@
#include <api/api.hpp>
#include <control/input_handler.hpp>
#include <core/docker.hpp>
#include <mutex>
#include <rtp/udp-ping.hpp>
#include <state/config.hpp>
#include <state/sessions.hpp>
#include <state/utils.hpp>

namespace wolf::api {

namespace {

/**
* Persists the new profiles, returning the error message on failure.
* update_profiles only stores the new list in memory after the file was saved.
*/
template <typename Cfg, typename Fn> std::optional<std::string> try_update_profiles(Cfg &cfg, Fn &&fn) {
try {
state::update_profiles(cfg, std::forward<Fn>(fn));
return std::nullopt;
} catch (const std::exception &e) {
logs::log(logs::error, "[API] Unable to save the config: {}", e.what());
return e.what();
}
}

/**
* Returns a copy of the profiles where the Moonlight profile has a new apps atom.
* The current atom is never touched, so a failed save leaves memory unchanged.
*/
template <typename Fn> state::ProfilesList with_moonlight_apps(const state::ProfilesList &profiles, Fn &&fn) {
return profiles | //
ranges::views::transform([&](const immer::box<events::Profile> &profile) {
if (profile->id != events::MOONLIGHT_PROFILE_ID) {
return profile;
}
using AppList = immer::vector<immer::box<events::App>>;
return immer::box<events::Profile>(
events::Profile{.id = profile->id,
.name = profile->name,
.icon_png_path = profile->icon_png_path,
.pin = profile->pin,
.apps = std::make_shared<immer::atom<AppList>>(fn(profile->apps->load()))});
}) |
ranges::to<state::ProfilesList>();
}

// Serialises the load -> save -> store of the Moonlight apps list between
// concurrent AddApp/RemoveApp requests, so one cannot overwrite the other.
std::mutex moonlight_apps_mutex;

} // namespace

void UnixSocketServer::endpoint_Events(const HTTPRequest &req, std::shared_ptr<UnixSocket> socket) {
// curl -N --unix-socket /tmp/wolf.sock http://localhost/api/v1/events
state_->sockets.push_back(socket);
Expand Down Expand Up @@ -101,19 +145,21 @@ void UnixSocketServer::endpoint_Apps(const HTTPRequest &req, std::shared_ptr<Uni
void UnixSocketServer::endpoint_AddApp(const HTTPRequest &req, std::shared_ptr<UnixSocket> socket) {
auto app = rfl::json::read<rfl::Reflector<events::App>::ReflType>(req.body);
if (app) {
auto profiles = state_->app_state->config->profiles->load().get();
state::update_profiles(
state_->app_state->config,
profiles | //
ranges::views::transform([app = app.value(), this](const immer::box<events::Profile> &profile) {
if (profile->id == events::MOONLIGHT_PROFILE_ID) {
profile->apps->update([app, this](auto &apps) {
return apps.push_back(rfl::Reflector<events::App>::to(app, this->state_->app_state->event_bus));
});
}
return profile;
}) |
ranges::to<state::ProfilesList>());
std::lock_guard lock(moonlight_apps_mutex);
try {
auto new_app = rfl::Reflector<events::App>::to(app.value(), this->state_->app_state->event_bus);
auto error = try_update_profiles(state_->app_state->config, [&](const state::ProfilesList &profiles) {
return with_moonlight_apps(profiles, [&](const auto &apps) { return apps.push_back(new_app); });
});
if (error) {
send_http(socket, 500, rfl::json::write(GenericErrorResponse{.error = *error}));
return;
}
} catch (const std::exception &e) {
logs::log(logs::error, "[API] Unable to add the app: {}", e.what());
send_http(socket, 500, rfl::json::write(GenericErrorResponse{.error = e.what()}));
return;
}

send_http(socket, 200, rfl::json::write(GenericSuccessResponse{.success = true}));
} else {
Expand All @@ -126,22 +172,19 @@ void UnixSocketServer::endpoint_AddApp(const HTTPRequest &req, std::shared_ptr<U
void UnixSocketServer::endpoint_RemoveApp(const HTTPRequest &req, std::shared_ptr<UnixSocket> socket) {
auto app = rfl::json::read<AppDeleteRequest>(req.body);
if (app) {
auto profiles = state_->app_state->config->profiles->load().get();
state::update_profiles(
state_->app_state->config,
profiles | //
ranges::views::transform([app = app.value(), this](const immer::box<events::Profile> &profile) {
if (profile->id == events::MOONLIGHT_PROFILE_ID) {
profile->apps->update([app, this](auto &apps) {
return apps | //
ranges::views::filter(
[&app](const immer::box<events::App> &a) { return a->base.id != app.id; }) | //
ranges::to<immer::vector<immer::box<events::App>>>();
});
}
return profile;
}) |
ranges::to<state::ProfilesList>());
std::lock_guard lock(moonlight_apps_mutex);
auto error = try_update_profiles(state_->app_state->config, [&](const state::ProfilesList &profiles) {
return with_moonlight_apps(profiles, [&](const auto &apps) {
return apps | //
ranges::views::filter(
[&](const immer::box<events::App> &a) { return a->base.id != app.value().id; }) | //
ranges::to<immer::vector<immer::box<events::App>>>();
});
});
if (error) {
send_http(socket, 500, rfl::json::write(GenericErrorResponse{.error = *error}));
return;
}

send_http(socket, 200, rfl::json::write(GenericSuccessResponse{.success = true}));
} else {
Expand All @@ -168,10 +211,13 @@ void UnixSocketServer::endpoint_AddProfile(const HTTPRequest &req, std::shared_p
if (profile_req) {
auto p = profile_req.value();

auto profiles = state_->app_state->config->profiles->load().get();
state::update_profiles(
state_->app_state->config,
profiles.push_back(rfl::Reflector<events::Profile>::to(p, this->state_->app_state->event_bus)));
auto error = try_update_profiles(state_->app_state->config, [&](const state::ProfilesList &profiles) {
return profiles.push_back(rfl::Reflector<events::Profile>::to(p, this->state_->app_state->event_bus));
});
if (error) {
send_http(socket, 500, rfl::json::write(GenericErrorResponse{.error = *error}));
return;
}
send_http(socket, 200, rfl::json::write(GenericSuccessResponse{.success = true}));
} else {
logs::log(logs::warning, "[API] Invalid event: {} - {}", req.body, profile_req.error().what());
Expand All @@ -185,13 +231,16 @@ void UnixSocketServer::endpoint_RemoveProfile(const HTTPRequest &req, std::share
if (profile_req) {
auto p = profile_req.value();

auto profiles = state_->app_state->config->profiles->load().get();
state::update_profiles(state_->app_state->config,
profiles | //
ranges::views::remove_if([&p](const immer::box<events::Profile> &profile) {
return profile.get().id == p.id;
}) | //
ranges::to<state::ProfilesList>());
auto error = try_update_profiles(state_->app_state->config, [&](const state::ProfilesList &profiles) {
return profiles | //
ranges::views::remove_if(
[&p](const immer::box<events::Profile> &profile) { return profile.get().id == p.id; }) | //
ranges::to<state::ProfilesList>();
});
if (error) {
send_http(socket, 500, rfl::json::write(GenericErrorResponse{.error = *error}));
return;
}
send_http(socket, 200, rfl::json::write(GenericSuccessResponse{.success = true}));
} else {
logs::log(logs::warning, "[API] Invalid event: {} - {}", req.body, profile_req.error().what());
Expand Down Expand Up @@ -556,32 +605,52 @@ void UnixSocketServer::endpoint_UpdateClientSettings(const HTTPRequest &req, std
}

const auto &payload = payload_result.value();
auto current_client = state::get_client_by_id(this->state_->app_state->config, payload.client_id.value());
if (!current_client) {
std::size_t client_id = 0;
try {
client_id = std::stoull(payload.client_id.value());
} catch (const std::exception &) {
send_http(socket, 400, rfl::json::write(GenericErrorResponse{.error = "Invalid client_id"}));
return;
}

bool updated = false;
try {
updated = update_client_settings(
this->state_->app_state->config,
client_id,
[&payload](const config::PairedClient &current_client) {
// Edit only the settings that are being passed in the payload
auto current_settings = current_client.settings;
auto new_settings = payload.settings.get().value_or(PartialClientSettings{});
return config::PairedClient{
.client_cert = current_client.client_cert, // Immutable, changing this would mean a new client
.app_state_folder = payload.app_state_folder.get().value_or(current_client.app_state_folder),
.settings = config::ClientSettings{
.run_uid = new_settings.run_uid.value_or(current_settings.run_uid),
.run_gid = new_settings.run_gid.value_or(current_settings.run_gid),
.controllers_override =
new_settings.controllers_override.value_or(current_settings.controllers_override),
.mouse_acceleration = new_settings.mouse_acceleration.value_or(current_settings.mouse_acceleration),
.v_scroll_acceleration =
new_settings.v_scroll_acceleration.value_or(current_settings.v_scroll_acceleration),
.h_scroll_acceleration =
new_settings.h_scroll_acceleration.value_or(current_settings.h_scroll_acceleration),
.motion_controller_override =
new_settings.motion_controller_override.value_or(current_settings.motion_controller_override),
}};
});
} catch (const std::exception &e) {
logs::log(logs::error, "[API] Unable to save the config: {}", e.what());
send_http(socket, 500, rfl::json::write(GenericErrorResponse{.error = e.what()}));
return;
}

if (!updated) {
auto res = GenericErrorResponse{.error = "Client not found"};
send_http(socket, 404, rfl::json::write(res));
return;
}

// Edit only the settings that are being passed in the payload
auto current_settings = current_client->settings;
auto new_settings = payload.settings.get().value_or(PartialClientSettings{});
auto merged_client = config::PairedClient{
.client_cert = current_client->client_cert, // Immutable, changing this would mean a new client
.app_state_folder = payload.app_state_folder.get().value_or(current_client->app_state_folder),
.settings = config::ClientSettings{
.run_uid = new_settings.run_uid.value_or(current_settings.run_uid),
.run_gid = new_settings.run_gid.value_or(current_settings.run_gid),
.controllers_override = new_settings.controllers_override.value_or(current_settings.controllers_override),
.mouse_acceleration = new_settings.mouse_acceleration.value_or(current_settings.mouse_acceleration),
.v_scroll_acceleration = new_settings.v_scroll_acceleration.value_or(current_settings.v_scroll_acceleration),
.h_scroll_acceleration = new_settings.h_scroll_acceleration.value_or(current_settings.h_scroll_acceleration),
.motion_controller_override =
new_settings.motion_controller_override.value_or(current_settings.motion_controller_override),
}};

update_client_settings(this->state_->app_state->config, std::stoull(payload.client_id.value()), merged_client);

auto res = GenericSuccessResponse{.success = true};
send_http(socket, 200, rfl::json::write(res));
}
Expand Down
28 changes: 27 additions & 1 deletion src/moonlight-server/api/http_server.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include <boost/asio/post.hpp>
#include <boost/asio/thread_pool.hpp>
#include <functional>
#include <helpers/logger.hpp>
#include <immer/box.hpp>
#include <optional>
#include <rfl.hpp>
Expand Down Expand Up @@ -42,6 +43,10 @@ template <typename Socket> struct RequestHandler {

template <typename T> class HTTPServer {
public:
// Called with the request socket when a handler throws, so the client gets
// an error response instead of hanging until timeout. May be empty.
std::function<void(const T &socket, const std::string &error)> on_unhandled_error;

HTTPServer() : pool_(std::max(std::thread::hardware_concurrency(), 2u)) {};

~HTTPServer() {
Expand All @@ -57,7 +62,28 @@ template <typename T> class HTTPServer {
if (it != endpoints_.end()) {
auto boxed_request = immer::box<HTTPRequest>(request);
auto handler = it->second.handler;
boost::asio::post(pool_, [handler, boxed_request, socket]() { handler(*boxed_request, socket); });
auto error_handler = on_unhandled_error;
boost::asio::post(pool_, [handler, boxed_request, socket, error_handler]() {
// An exception escaping a pool task would terminate Wolf
auto notify = [&](const std::string &error) {
if (error_handler) {
try {
error_handler(socket, error);
} catch (...) {
logs::log(logs::error, "[API] Failed to report the unhandled error in {}", boxed_request->path);
}
}
};
try {
handler(*boxed_request, socket);
} catch (const std::exception &e) {
logs::log(logs::error, "[API] Unhandled error in {}: {}", boxed_request->path, e.what());
notify(e.what());
} catch (...) {
logs::log(logs::error, "[API] Unhandled unknown error in {}", boxed_request->path);
notify("Unknown error");
}
});
return true;
}
return false;
Expand Down
4 changes: 4 additions & 0 deletions src/moonlight-server/api/unix_socket_server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ UnixSocketServer::UnixSocketServer(boost::asio::io_context &io_context,

state_ = std::make_shared<UnixSocketState>(io_context, app_state, socket_path);

state_->http.on_unhandled_error = [this](const std::shared_ptr<UnixSocket> &socket, const std::string &error) {
send_http(socket, 500, rfl::json::write(GenericErrorResponse{.error = error}));
};

state_->http.add(HTTPMethod::GET,
"/api/v1/events",
{.summary = "Subscribe to events",
Expand Down
50 changes: 50 additions & 0 deletions src/moonlight-server/state/config.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,15 @@
#include <boost/uuid/uuid_io.hpp> // streaming operators etc.
#include <crypto/crypto.hpp>
#include <events/events.hpp>
#include <functional>
#include <helpers/logger.hpp>
#include <optional>
#include <runners/docker.hpp>
#include <runners/process.hpp>
#include <state/data-structures.hpp>
#include <string>
#include <string_view>
#include <system_error>

namespace state {

Expand Down Expand Up @@ -174,9 +179,54 @@ std::optional<PairedClient> get_client_by_id(const Config &cfg, const std::strin
*/
void update_client_settings(const Config &cfg, std::size_t client_id, const PairedClient &updated_client);

/**
* Atomically replaces the client client_id with update_fn(current client).
* update_fn runs while holding config_file_mutex, so concurrent updates are never lost.
* Returns false (and changes nothing) when the client is not found.
* Side effects: will save back the configuration to disk
*/
bool update_client_settings(const Config &cfg,
std::size_t client_id,
const std::function<PairedClient(const PairedClient &)> &update_fn);

/**
* Replaces the currently loaded profiles
* Side effects: will save back the configuration to disk
*/
void update_profiles(const Config &cfg, const ProfilesList &profiles);

/**
* Atomically replaces the profiles with update_fn(current profiles).
* update_fn runs while holding config_file_mutex, so concurrent updates are never lost.
* Side effects: will save back the configuration to disk
*/
void update_profiles(const Config &cfg, const std::function<ProfilesList(const ProfilesList &)> &update_fn);

/**
* Filesystem operations used when saving the config file, injectable so tests can
* simulate bind-mount rename failures and faulty writes without privileges.
*/
namespace detail {

struct AtomicSaveOps {
/** Renames `from` over `to`, returning an empty error_code on success. */
std::function<std::error_code(const std::string &, const std::string &)> rename_file;
/** Truncates `file` and writes the whole content, returning false on failure (possibly after a partial write). */
std::function<bool(const std::string &, std::string_view)> write_in_place;
/** Returns the full content of the file, or std::nullopt when it cannot be opened or read. */
std::function<std::optional<std::string>(const std::string &)> read_file;
};

/** The operations above backed by the real filesystem. */
AtomicSaveOps real_atomic_save_ops();

/**
* Writes the content to `source` via a temporary file renamed over it, falling back to an
* in-place write (restoring the previous content on failure) when the rename reports
* EBUSY/EXDEV, as happens for a single bind-mounted file.
*/
void save_file_atomically(const std::string &source, std::string_view content, const AtomicSaveOps &ops);
void save_file_atomically(const std::string &source, std::string_view content);

} // namespace detail
} // namespace state
Loading