summaryrefslogtreecommitdiff
path: root/src/web_service
diff options
context:
space:
mode:
Diffstat (limited to 'src/web_service')
-rw-r--r--src/web_service/CMakeLists.txt16
-rw-r--r--src/web_service/telemetry_json.cpp99
-rw-r--r--src/web_service/telemetry_json.h58
-rw-r--r--src/web_service/verify_login.cpp27
-rw-r--r--src/web_service/verify_login.h22
-rw-r--r--src/web_service/web_backend.cpp149
-rw-r--r--src/web_service/web_backend.h92
7 files changed, 463 insertions, 0 deletions
diff --git a/src/web_service/CMakeLists.txt b/src/web_service/CMakeLists.txt
new file mode 100644
index 000000000..1c83e9c34
--- /dev/null
+++ b/src/web_service/CMakeLists.txt
@@ -0,0 +1,16 @@
1add_library(web_service STATIC
2 telemetry_json.cpp
3 telemetry_json.h
4 verify_login.cpp
5 verify_login.h
6 web_backend.cpp
7 web_backend.h
8)
9
10create_target_directory_groups(web_service)
11
12get_directory_property(OPENSSL_LIBS
13 DIRECTORY ${CMAKE_SOURCE_DIR}/externals/libressl
14 DEFINITION OPENSSL_LIBS)
15target_compile_definitions(web_service PUBLIC -DCPPHTTPLIB_OPENSSL_SUPPORT)
16target_link_libraries(web_service PRIVATE common json-headers ${OPENSSL_LIBS} httplib lurlparser)
diff --git a/src/web_service/telemetry_json.cpp b/src/web_service/telemetry_json.cpp
new file mode 100644
index 000000000..033ea1ea4
--- /dev/null
+++ b/src/web_service/telemetry_json.cpp
@@ -0,0 +1,99 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <thread>
6#include "common/assert.h"
7#include "common/detached_tasks.h"
8#include "web_service/telemetry_json.h"
9#include "web_service/web_backend.h"
10
11namespace WebService {
12
13TelemetryJson::TelemetryJson(const std::string& host, const std::string& username,
14 const std::string& token)
15 : host(std::move(host)), username(std::move(username)), token(std::move(token)) {}
16TelemetryJson::~TelemetryJson() = default;
17
18template <class T>
19void TelemetryJson::Serialize(Telemetry::FieldType type, const std::string& name, T value) {
20 sections[static_cast<u8>(type)][name] = value;
21}
22
23void TelemetryJson::SerializeSection(Telemetry::FieldType type, const std::string& name) {
24 TopSection()[name] = sections[static_cast<unsigned>(type)];
25}
26
27void TelemetryJson::Visit(const Telemetry::Field<bool>& field) {
28 Serialize(field.GetType(), field.GetName(), field.GetValue());
29}
30
31void TelemetryJson::Visit(const Telemetry::Field<double>& field) {
32 Serialize(field.GetType(), field.GetName(), field.GetValue());
33}
34
35void TelemetryJson::Visit(const Telemetry::Field<float>& field) {
36 Serialize(field.GetType(), field.GetName(), field.GetValue());
37}
38
39void TelemetryJson::Visit(const Telemetry::Field<u8>& field) {
40 Serialize(field.GetType(), field.GetName(), field.GetValue());
41}
42
43void TelemetryJson::Visit(const Telemetry::Field<u16>& field) {
44 Serialize(field.GetType(), field.GetName(), field.GetValue());
45}
46
47void TelemetryJson::Visit(const Telemetry::Field<u32>& field) {
48 Serialize(field.GetType(), field.GetName(), field.GetValue());
49}
50
51void TelemetryJson::Visit(const Telemetry::Field<u64>& field) {
52 Serialize(field.GetType(), field.GetName(), field.GetValue());
53}
54
55void TelemetryJson::Visit(const Telemetry::Field<s8>& field) {
56 Serialize(field.GetType(), field.GetName(), field.GetValue());
57}
58
59void TelemetryJson::Visit(const Telemetry::Field<s16>& field) {
60 Serialize(field.GetType(), field.GetName(), field.GetValue());
61}
62
63void TelemetryJson::Visit(const Telemetry::Field<s32>& field) {
64 Serialize(field.GetType(), field.GetName(), field.GetValue());
65}
66
67void TelemetryJson::Visit(const Telemetry::Field<s64>& field) {
68 Serialize(field.GetType(), field.GetName(), field.GetValue());
69}
70
71void TelemetryJson::Visit(const Telemetry::Field<std::string>& field) {
72 Serialize(field.GetType(), field.GetName(), field.GetValue());
73}
74
75void TelemetryJson::Visit(const Telemetry::Field<const char*>& field) {
76 Serialize(field.GetType(), field.GetName(), std::string(field.GetValue()));
77}
78
79void TelemetryJson::Visit(const Telemetry::Field<std::chrono::microseconds>& field) {
80 Serialize(field.GetType(), field.GetName(), field.GetValue().count());
81}
82
83void TelemetryJson::Complete() {
84 SerializeSection(Telemetry::FieldType::App, "App");
85 SerializeSection(Telemetry::FieldType::Session, "Session");
86 SerializeSection(Telemetry::FieldType::Performance, "Performance");
87 SerializeSection(Telemetry::FieldType::UserFeedback, "UserFeedback");
88 SerializeSection(Telemetry::FieldType::UserConfig, "UserConfig");
89 SerializeSection(Telemetry::FieldType::UserSystem, "UserSystem");
90
91 auto content = TopSection().dump();
92 // Send the telemetry async but don't handle the errors since they were written to the log
93 Common::DetachedTasks::AddTask(
94 [host{this->host}, username{this->username}, token{this->token}, content]() {
95 Client{host, username, token}.PostJson("/telemetry", content, true);
96 });
97}
98
99} // namespace WebService
diff --git a/src/web_service/telemetry_json.h b/src/web_service/telemetry_json.h
new file mode 100644
index 000000000..0fe6f9a3e
--- /dev/null
+++ b/src/web_service/telemetry_json.h
@@ -0,0 +1,58 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <array>
8#include <string>
9#include <json.hpp>
10#include "common/telemetry.h"
11#include "common/web_result.h"
12
13namespace WebService {
14
15/**
16 * Implementation of VisitorInterface that serialized telemetry into JSON, and submits it to the
17 * yuzu web service
18 */
19class TelemetryJson : public Telemetry::VisitorInterface {
20public:
21 TelemetryJson(const std::string& host, const std::string& username, const std::string& token);
22 ~TelemetryJson();
23
24 void Visit(const Telemetry::Field<bool>& field) override;
25 void Visit(const Telemetry::Field<double>& field) override;
26 void Visit(const Telemetry::Field<float>& field) override;
27 void Visit(const Telemetry::Field<u8>& field) override;
28 void Visit(const Telemetry::Field<u16>& field) override;
29 void Visit(const Telemetry::Field<u32>& field) override;
30 void Visit(const Telemetry::Field<u64>& field) override;
31 void Visit(const Telemetry::Field<s8>& field) override;
32 void Visit(const Telemetry::Field<s16>& field) override;
33 void Visit(const Telemetry::Field<s32>& field) override;
34 void Visit(const Telemetry::Field<s64>& field) override;
35 void Visit(const Telemetry::Field<std::string>& field) override;
36 void Visit(const Telemetry::Field<const char*>& field) override;
37 void Visit(const Telemetry::Field<std::chrono::microseconds>& field) override;
38
39 void Complete() override;
40
41private:
42 nlohmann::json& TopSection() {
43 return sections[static_cast<u8>(Telemetry::FieldType::None)];
44 }
45
46 template <class T>
47 void Serialize(Telemetry::FieldType type, const std::string& name, T value);
48
49 void SerializeSection(Telemetry::FieldType type, const std::string& name);
50
51 nlohmann::json output;
52 std::array<nlohmann::json, 7> sections;
53 std::string host;
54 std::string username;
55 std::string token;
56};
57
58} // namespace WebService
diff --git a/src/web_service/verify_login.cpp b/src/web_service/verify_login.cpp
new file mode 100644
index 000000000..124aa3863
--- /dev/null
+++ b/src/web_service/verify_login.cpp
@@ -0,0 +1,27 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <json.hpp>
6#include "web_service/verify_login.h"
7#include "web_service/web_backend.h"
8
9namespace WebService {
10
11bool VerifyLogin(const std::string& host, const std::string& username, const std::string& token) {
12 Client client(host, username, token);
13 auto reply = client.GetJson("/profile", false).returned_data;
14 if (reply.empty()) {
15 return false;
16 }
17 nlohmann::json json = nlohmann::json::parse(reply);
18 const auto iter = json.find("username");
19
20 if (iter == json.end()) {
21 return username.empty();
22 }
23
24 return username == *iter;
25}
26
27} // namespace WebService
diff --git a/src/web_service/verify_login.h b/src/web_service/verify_login.h
new file mode 100644
index 000000000..39db32dbb
--- /dev/null
+++ b/src/web_service/verify_login.h
@@ -0,0 +1,22 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <functional>
8#include <future>
9#include <string>
10
11namespace WebService {
12
13/**
14 * Checks if username and token is valid
15 * @param host the web API URL
16 * @param username yuzu username to use for authentication.
17 * @param token yuzu token to use for authentication.
18 * @returns a bool indicating whether the verification succeeded
19 */
20bool VerifyLogin(const std::string& host, const std::string& username, const std::string& token);
21
22} // namespace WebService
diff --git a/src/web_service/web_backend.cpp b/src/web_service/web_backend.cpp
new file mode 100644
index 000000000..787b0fbcb
--- /dev/null
+++ b/src/web_service/web_backend.cpp
@@ -0,0 +1,149 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <cstdlib>
6#include <string>
7#include <thread>
8#include <LUrlParser.h>
9#include "common/logging/log.h"
10#include "common/web_result.h"
11#include "core/settings.h"
12#include "web_service/web_backend.h"
13
14namespace WebService {
15
16constexpr std::array<const char, 1> API_VERSION{'1'};
17
18constexpr u32 HTTP_PORT = 80;
19constexpr u32 HTTPS_PORT = 443;
20
21constexpr u32 TIMEOUT_SECONDS = 30;
22
23Client::JWTCache Client::jwt_cache{};
24
25Client::Client(const std::string& host, const std::string& username, const std::string& token)
26 : host(host), username(username), token(token) {
27 std::lock_guard<std::mutex> lock(jwt_cache.mutex);
28 if (username == jwt_cache.username && token == jwt_cache.token) {
29 jwt = jwt_cache.jwt;
30 }
31}
32
33Common::WebResult Client::GenericJson(const std::string& method, const std::string& path,
34 const std::string& data, const std::string& jwt,
35 const std::string& username, const std::string& token) {
36 if (cli == nullptr) {
37 auto parsedUrl = LUrlParser::clParseURL::ParseURL(host);
38 int port;
39 if (parsedUrl.m_Scheme == "http") {
40 if (!parsedUrl.GetPort(&port)) {
41 port = HTTP_PORT;
42 }
43 cli =
44 std::make_unique<httplib::Client>(parsedUrl.m_Host.c_str(), port, TIMEOUT_SECONDS);
45 } else if (parsedUrl.m_Scheme == "https") {
46 if (!parsedUrl.GetPort(&port)) {
47 port = HTTPS_PORT;
48 }
49 cli = std::make_unique<httplib::SSLClient>(parsedUrl.m_Host.c_str(), port,
50 TIMEOUT_SECONDS);
51 } else {
52 LOG_ERROR(WebService, "Bad URL scheme {}", parsedUrl.m_Scheme);
53 return Common::WebResult{Common::WebResult::Code::InvalidURL, "Bad URL scheme"};
54 }
55 }
56 if (cli == nullptr) {
57 LOG_ERROR(WebService, "Invalid URL {}", host + path);
58 return Common::WebResult{Common::WebResult::Code::InvalidURL, "Invalid URL"};
59 }
60
61 httplib::Headers params;
62 if (!jwt.empty()) {
63 params = {
64 {std::string("Authorization"), fmt::format("Bearer {}", jwt)},
65 };
66 } else if (!username.empty()) {
67 params = {
68 {std::string("x-username"), username},
69 {std::string("x-token"), token},
70 };
71 }
72
73 params.emplace(std::string("api-version"), std::string(API_VERSION.begin(), API_VERSION.end()));
74 if (method != "GET") {
75 params.emplace(std::string("Content-Type"), std::string("application/json"));
76 };
77
78 httplib::Request request;
79 request.method = method;
80 request.path = path;
81 request.headers = params;
82 request.body = data;
83
84 httplib::Response response;
85
86 if (!cli->send(request, response)) {
87 LOG_ERROR(WebService, "{} to {} returned null", method, host + path);
88 return Common::WebResult{Common::WebResult::Code::LibError, "Null response"};
89 }
90
91 if (response.status >= 400) {
92 LOG_ERROR(WebService, "{} to {} returned error status code: {}", method, host + path,
93 response.status);
94 return Common::WebResult{Common::WebResult::Code::HttpError,
95 std::to_string(response.status)};
96 }
97
98 auto content_type = response.headers.find("content-type");
99
100 if (content_type == response.headers.end()) {
101 LOG_ERROR(WebService, "{} to {} returned no content", method, host + path);
102 return Common::WebResult{Common::WebResult::Code::WrongContent, ""};
103 }
104
105 if (content_type->second.find("application/json") == std::string::npos &&
106 content_type->second.find("text/html; charset=utf-8") == std::string::npos) {
107 LOG_ERROR(WebService, "{} to {} returned wrong content: {}", method, host + path,
108 content_type->second);
109 return Common::WebResult{Common::WebResult::Code::WrongContent, "Wrong content"};
110 }
111 return Common::WebResult{Common::WebResult::Code::Success, "", response.body};
112}
113
114void Client::UpdateJWT() {
115 if (!username.empty() && !token.empty()) {
116 auto result = GenericJson("POST", "/jwt/internal", "", "", username, token);
117 if (result.result_code != Common::WebResult::Code::Success) {
118 LOG_ERROR(WebService, "UpdateJWT failed");
119 } else {
120 std::lock_guard<std::mutex> lock(jwt_cache.mutex);
121 jwt_cache.username = username;
122 jwt_cache.token = token;
123 jwt_cache.jwt = jwt = result.returned_data;
124 }
125 }
126}
127
128Common::WebResult Client::GenericJson(const std::string& method, const std::string& path,
129 const std::string& data, bool allow_anonymous) {
130 if (jwt.empty()) {
131 UpdateJWT();
132 }
133
134 if (jwt.empty() && !allow_anonymous) {
135 LOG_ERROR(WebService, "Credentials must be provided for authenticated requests");
136 return Common::WebResult{Common::WebResult::Code::CredentialsMissing, "Credentials needed"};
137 }
138
139 auto result = GenericJson(method, path, data, jwt);
140 if (result.result_string == "401") {
141 // Try again with new JWT
142 UpdateJWT();
143 result = GenericJson(method, path, data, jwt);
144 }
145
146 return result;
147}
148
149} // namespace WebService
diff --git a/src/web_service/web_backend.h b/src/web_service/web_backend.h
new file mode 100644
index 000000000..d75fbcc15
--- /dev/null
+++ b/src/web_service/web_backend.h
@@ -0,0 +1,92 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <functional>
8#include <mutex>
9#include <string>
10#include <tuple>
11#include <httplib.h>
12#include "common/common_types.h"
13#include "common/web_result.h"
14
15namespace httplib {
16class Client;
17}
18
19namespace WebService {
20
21class Client {
22public:
23 Client(const std::string& host, const std::string& username, const std::string& token);
24
25 /**
26 * Posts JSON to the specified path.
27 * @param path the URL segment after the host address.
28 * @param data String of JSON data to use for the body of the POST request.
29 * @param allow_anonymous If true, allow anonymous unauthenticated requests.
30 * @return the result of the request.
31 */
32 Common::WebResult PostJson(const std::string& path, const std::string& data,
33 bool allow_anonymous) {
34 return GenericJson("POST", path, data, allow_anonymous);
35 }
36
37 /**
38 * Gets JSON from the specified path.
39 * @param path the URL segment after the host address.
40 * @param allow_anonymous If true, allow anonymous unauthenticated requests.
41 * @return the result of the request.
42 */
43 Common::WebResult GetJson(const std::string& path, bool allow_anonymous) {
44 return GenericJson("GET", path, "", allow_anonymous);
45 }
46
47 /**
48 * Deletes JSON to the specified path.
49 * @param path the URL segment after the host address.
50 * @param data String of JSON data to use for the body of the DELETE request.
51 * @param allow_anonymous If true, allow anonymous unauthenticated requests.
52 * @return the result of the request.
53 */
54 Common::WebResult DeleteJson(const std::string& path, const std::string& data,
55 bool allow_anonymous) {
56 return GenericJson("DELETE", path, data, allow_anonymous);
57 }
58
59private:
60 /// A generic function handles POST, GET and DELETE request together
61 Common::WebResult GenericJson(const std::string& method, const std::string& path,
62 const std::string& data, bool allow_anonymous);
63
64 /**
65 * A generic function with explicit authentication method specified
66 * JWT is used if the jwt parameter is not empty
67 * username + token is used if jwt is empty but username and token are not empty
68 * anonymous if all of jwt, username and token are empty
69 */
70 Common::WebResult GenericJson(const std::string& method, const std::string& path,
71 const std::string& data, const std::string& jwt = "",
72 const std::string& username = "", const std::string& token = "");
73
74 // Retrieve a new JWT from given username and token
75 void UpdateJWT();
76
77 std::string host;
78 std::string username;
79 std::string token;
80 std::string jwt;
81 std::unique_ptr<httplib::Client> cli;
82
83 struct JWTCache {
84 std::mutex mutex;
85 std::string username;
86 std::string token;
87 std::string jwt;
88 };
89 static JWTCache jwt_cache;
90};
91
92} // namespace WebService