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/json.h18
-rw-r--r--src/web_service/telemetry_json.cpp94
-rw-r--r--src/web_service/telemetry_json.h59
-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.cpp147
-rw-r--r--src/web_service/web_backend.h91
8 files changed, 474 insertions, 0 deletions
diff --git a/src/web_service/CMakeLists.txt b/src/web_service/CMakeLists.txt
new file mode 100644
index 000000000..ef77728c0
--- /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)
15add_definitions(-DCPPHTTPLIB_OPENSSL_SUPPORT)
16target_link_libraries(web_service PUBLIC common json-headers ${OPENSSL_LIBS} httplib lurlparser)
diff --git a/src/web_service/json.h b/src/web_service/json.h
new file mode 100644
index 000000000..88b31501e
--- /dev/null
+++ b/src/web_service/json.h
@@ -0,0 +1,18 @@
1// Copyright 2018 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// This hack is needed to support json.hpp on platforms where the C++17 stdlib
8// lacks std::string_view. See https://github.com/nlohmann/json/issues/735.
9// clang-format off
10#if !__has_include(<string_view>) && __has_include(<experimental/string_view>)
11# include <experimental/string_view>
12# define string_view experimental::string_view
13# include <json.hpp>
14# undef string_view
15#else
16# include <json.hpp>
17#endif
18// clang-format on
diff --git a/src/web_service/telemetry_json.cpp b/src/web_service/telemetry_json.cpp
new file mode 100644
index 000000000..a0b7f9c4e
--- /dev/null
+++ b/src/web_service/telemetry_json.cpp
@@ -0,0 +1,94 @@
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
13template <class T>
14void TelemetryJson::Serialize(Telemetry::FieldType type, const std::string& name, T value) {
15 sections[static_cast<u8>(type)][name] = value;
16}
17
18void TelemetryJson::SerializeSection(Telemetry::FieldType type, const std::string& name) {
19 TopSection()[name] = sections[static_cast<unsigned>(type)];
20}
21
22void TelemetryJson::Visit(const Telemetry::Field<bool>& field) {
23 Serialize(field.GetType(), field.GetName(), field.GetValue());
24}
25
26void TelemetryJson::Visit(const Telemetry::Field<double>& field) {
27 Serialize(field.GetType(), field.GetName(), field.GetValue());
28}
29
30void TelemetryJson::Visit(const Telemetry::Field<float>& field) {
31 Serialize(field.GetType(), field.GetName(), field.GetValue());
32}
33
34void TelemetryJson::Visit(const Telemetry::Field<u8>& field) {
35 Serialize(field.GetType(), field.GetName(), field.GetValue());
36}
37
38void TelemetryJson::Visit(const Telemetry::Field<u16>& field) {
39 Serialize(field.GetType(), field.GetName(), field.GetValue());
40}
41
42void TelemetryJson::Visit(const Telemetry::Field<u32>& field) {
43 Serialize(field.GetType(), field.GetName(), field.GetValue());
44}
45
46void TelemetryJson::Visit(const Telemetry::Field<u64>& field) {
47 Serialize(field.GetType(), field.GetName(), field.GetValue());
48}
49
50void TelemetryJson::Visit(const Telemetry::Field<s8>& field) {
51 Serialize(field.GetType(), field.GetName(), field.GetValue());
52}
53
54void TelemetryJson::Visit(const Telemetry::Field<s16>& field) {
55 Serialize(field.GetType(), field.GetName(), field.GetValue());
56}
57
58void TelemetryJson::Visit(const Telemetry::Field<s32>& field) {
59 Serialize(field.GetType(), field.GetName(), field.GetValue());
60}
61
62void TelemetryJson::Visit(const Telemetry::Field<s64>& field) {
63 Serialize(field.GetType(), field.GetName(), field.GetValue());
64}
65
66void TelemetryJson::Visit(const Telemetry::Field<std::string>& field) {
67 Serialize(field.GetType(), field.GetName(), field.GetValue());
68}
69
70void TelemetryJson::Visit(const Telemetry::Field<const char*>& field) {
71 Serialize(field.GetType(), field.GetName(), std::string(field.GetValue()));
72}
73
74void TelemetryJson::Visit(const Telemetry::Field<std::chrono::microseconds>& field) {
75 Serialize(field.GetType(), field.GetName(), field.GetValue().count());
76}
77
78void TelemetryJson::Complete() {
79 SerializeSection(Telemetry::FieldType::App, "App");
80 SerializeSection(Telemetry::FieldType::Session, "Session");
81 SerializeSection(Telemetry::FieldType::Performance, "Performance");
82 SerializeSection(Telemetry::FieldType::UserFeedback, "UserFeedback");
83 SerializeSection(Telemetry::FieldType::UserConfig, "UserConfig");
84 SerializeSection(Telemetry::FieldType::UserSystem, "UserSystem");
85
86 auto content = TopSection().dump();
87 // Send the telemetry async but don't handle the errors since they were written to the log
88 Common::DetachedTasks::AddTask(
89 [host{this->host}, username{this->username}, token{this->token}, content]() {
90 Client{host, username, token}.PostJson("/telemetry", content, true);
91 });
92}
93
94} // namespace WebService
diff --git a/src/web_service/telemetry_json.h b/src/web_service/telemetry_json.h
new file mode 100644
index 000000000..9bc886538
--- /dev/null
+++ b/src/web_service/telemetry_json.h
@@ -0,0 +1,59 @@
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 "common/telemetry.h"
10#include "common/web_result.h"
11#include "web_service/json.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 : host(host), username(username), token(token) {}
23 ~TelemetryJson() = default;
24
25 void Visit(const Telemetry::Field<bool>& field) override;
26 void Visit(const Telemetry::Field<double>& field) override;
27 void Visit(const Telemetry::Field<float>& field) override;
28 void Visit(const Telemetry::Field<u8>& field) override;
29 void Visit(const Telemetry::Field<u16>& field) override;
30 void Visit(const Telemetry::Field<u32>& field) override;
31 void Visit(const Telemetry::Field<u64>& field) override;
32 void Visit(const Telemetry::Field<s8>& field) override;
33 void Visit(const Telemetry::Field<s16>& field) override;
34 void Visit(const Telemetry::Field<s32>& field) override;
35 void Visit(const Telemetry::Field<s64>& field) override;
36 void Visit(const Telemetry::Field<std::string>& field) override;
37 void Visit(const Telemetry::Field<const char*>& field) override;
38 void Visit(const Telemetry::Field<std::chrono::microseconds>& field) override;
39
40 void Complete() override;
41
42private:
43 nlohmann::json& TopSection() {
44 return sections[static_cast<u8>(Telemetry::FieldType::None)];
45 }
46
47 template <class T>
48 void Serialize(Telemetry::FieldType type, const std::string& name, T value);
49
50 void SerializeSection(Telemetry::FieldType type, const std::string& name);
51
52 nlohmann::json output;
53 std::array<nlohmann::json, 7> sections;
54 std::string host;
55 std::string username;
56 std::string token;
57};
58
59} // namespace WebService
diff --git a/src/web_service/verify_login.cpp b/src/web_service/verify_login.cpp
new file mode 100644
index 000000000..02e1b74f3
--- /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 "web_service/json.h"
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..a726fb8eb
--- /dev/null
+++ b/src/web_service/web_backend.cpp
@@ -0,0 +1,147 @@
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
16static constexpr char API_VERSION[]{"1"};
17
18constexpr int HTTP_PORT = 80;
19constexpr int HTTPS_PORT = 443;
20
21constexpr int 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 if (username == jwt_cache.username && token == jwt_cache.token) {
28 jwt = jwt_cache.jwt;
29 }
30}
31
32Common::WebResult Client::GenericJson(const std::string& method, const std::string& path,
33 const std::string& data, const std::string& jwt,
34 const std::string& username, const std::string& token) {
35 if (cli == nullptr) {
36 auto parsedUrl = LUrlParser::clParseURL::ParseURL(host);
37 int port;
38 if (parsedUrl.m_Scheme == "http") {
39 if (!parsedUrl.GetPort(&port)) {
40 port = HTTP_PORT;
41 }
42 cli =
43 std::make_unique<httplib::Client>(parsedUrl.m_Host.c_str(), port, TIMEOUT_SECONDS);
44 } else if (parsedUrl.m_Scheme == "https") {
45 if (!parsedUrl.GetPort(&port)) {
46 port = HTTPS_PORT;
47 }
48 cli = std::make_unique<httplib::SSLClient>(parsedUrl.m_Host.c_str(), port,
49 TIMEOUT_SECONDS);
50 } else {
51 LOG_ERROR(WebService, "Bad URL scheme {}", parsedUrl.m_Scheme);
52 return Common::WebResult{Common::WebResult::Code::InvalidURL, "Bad URL scheme"};
53 }
54 }
55 if (cli == nullptr) {
56 LOG_ERROR(WebService, "Invalid URL {}", host + path);
57 return Common::WebResult{Common::WebResult::Code::InvalidURL, "Invalid URL"};
58 }
59
60 httplib::Headers params;
61 if (!jwt.empty()) {
62 params = {
63 {std::string("Authorization"), fmt::format("Bearer {}", jwt)},
64 };
65 } else if (!username.empty()) {
66 params = {
67 {std::string("x-username"), username},
68 {std::string("x-token"), token},
69 };
70 }
71
72 params.emplace(std::string("api-version"), std::string(API_VERSION));
73 if (method != "GET") {
74 params.emplace(std::string("Content-Type"), std::string("application/json"));
75 };
76
77 httplib::Request request;
78 request.method = method;
79 request.path = path;
80 request.headers = params;
81 request.body = data;
82
83 httplib::Response response;
84
85 if (!cli->send(request, response)) {
86 LOG_ERROR(WebService, "{} to {} returned null", method, host + path);
87 return Common::WebResult{Common::WebResult::Code::LibError, "Null response"};
88 }
89
90 if (response.status >= 400) {
91 LOG_ERROR(WebService, "{} to {} returned error status code: {}", method, host + path,
92 response.status);
93 return Common::WebResult{Common::WebResult::Code::HttpError,
94 std::to_string(response.status)};
95 }
96
97 auto content_type = response.headers.find("content-type");
98
99 if (content_type == response.headers.end()) {
100 LOG_ERROR(WebService, "{} to {} returned no content", method, host + path);
101 return Common::WebResult{Common::WebResult::Code::WrongContent, ""};
102 }
103
104 if (content_type->second.find("application/json") == std::string::npos &&
105 content_type->second.find("text/html; charset=utf-8") == std::string::npos) {
106 LOG_ERROR(WebService, "{} to {} returned wrong content: {}", method, host + path,
107 content_type->second);
108 return Common::WebResult{Common::WebResult::Code::WrongContent, "Wrong content"};
109 }
110 return Common::WebResult{Common::WebResult::Code::Success, "", response.body};
111}
112
113void Client::UpdateJWT() {
114 if (!username.empty() && !token.empty()) {
115 auto result = GenericJson("POST", "/jwt/internal", "", "", username, token);
116 if (result.result_code != Common::WebResult::Code::Success) {
117 LOG_ERROR(WebService, "UpdateJWT failed");
118 } else {
119 jwt_cache.username = username;
120 jwt_cache.token = token;
121 jwt_cache.jwt = jwt = result.returned_data;
122 }
123 }
124}
125
126Common::WebResult Client::GenericJson(const std::string& method, const std::string& path,
127 const std::string& data, bool allow_anonymous) {
128 if (jwt.empty()) {
129 UpdateJWT();
130 }
131
132 if (jwt.empty() && !allow_anonymous) {
133 LOG_ERROR(WebService, "Credentials must be provided for authenticated requests");
134 return Common::WebResult{Common::WebResult::Code::CredentialsMissing, "Credentials needed"};
135 }
136
137 auto result = GenericJson(method, path, data, jwt);
138 if (result.result_string == "401") {
139 // Try again with new JWT
140 UpdateJWT();
141 result = GenericJson(method, path, data, jwt);
142 }
143
144 return result;
145}
146
147} // namespace WebService
diff --git a/src/web_service/web_backend.h b/src/web_service/web_backend.h
new file mode 100644
index 000000000..549bcce29
--- /dev/null
+++ b/src/web_service/web_backend.h
@@ -0,0 +1,91 @@
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#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::string username;
85 std::string token;
86 std::string jwt;
87 };
88 static JWTCache jwt_cache;
89};
90
91} // namespace WebService