web_backend.cpp 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. // Copyright 2017 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <cstdlib>
  5. #include <mutex>
  6. #include <string>
  7. #include <LUrlParser.h>
  8. #include <httplib.h>
  9. #include "common/common_types.h"
  10. #include "common/logging/log.h"
  11. #include "common/web_result.h"
  12. #include "web_service/web_backend.h"
  13. namespace WebService {
  14. constexpr std::array<const char, 1> API_VERSION{'1'};
  15. constexpr u32 HTTP_PORT = 80;
  16. constexpr u32 HTTPS_PORT = 443;
  17. constexpr u32 TIMEOUT_SECONDS = 30;
  18. struct Client::Impl {
  19. Impl(std::string host, std::string username, std::string token)
  20. : host{std::move(host)}, username{std::move(username)}, token{std::move(token)} {
  21. std::lock_guard lock{jwt_cache.mutex};
  22. if (this->username == jwt_cache.username && this->token == jwt_cache.token) {
  23. jwt = jwt_cache.jwt;
  24. }
  25. }
  26. /// A generic function handles POST, GET and DELETE request together
  27. Common::WebResult GenericJson(const std::string& method, const std::string& path,
  28. const std::string& data, bool allow_anonymous) {
  29. if (jwt.empty()) {
  30. UpdateJWT();
  31. }
  32. if (jwt.empty() && !allow_anonymous) {
  33. LOG_ERROR(WebService, "Credentials must be provided for authenticated requests");
  34. return Common::WebResult{Common::WebResult::Code::CredentialsMissing,
  35. "Credentials needed"};
  36. }
  37. auto result = GenericJson(method, path, data, jwt);
  38. if (result.result_string == "401") {
  39. // Try again with new JWT
  40. UpdateJWT();
  41. result = GenericJson(method, path, data, jwt);
  42. }
  43. return result;
  44. }
  45. /**
  46. * A generic function with explicit authentication method specified
  47. * JWT is used if the jwt parameter is not empty
  48. * username + token is used if jwt is empty but username and token are not empty
  49. * anonymous if all of jwt, username and token are empty
  50. */
  51. Common::WebResult GenericJson(const std::string& method, const std::string& path,
  52. const std::string& data, const std::string& jwt = "",
  53. const std::string& username = "", const std::string& token = "") {
  54. if (cli == nullptr) {
  55. auto parsedUrl = LUrlParser::clParseURL::ParseURL(host);
  56. int port;
  57. if (parsedUrl.m_Scheme == "http") {
  58. if (!parsedUrl.GetPort(&port)) {
  59. port = HTTP_PORT;
  60. }
  61. cli = std::make_unique<httplib::Client>(parsedUrl.m_Host.c_str(), port,
  62. TIMEOUT_SECONDS);
  63. } else if (parsedUrl.m_Scheme == "https") {
  64. if (!parsedUrl.GetPort(&port)) {
  65. port = HTTPS_PORT;
  66. }
  67. cli = std::make_unique<httplib::SSLClient>(parsedUrl.m_Host.c_str(), port,
  68. TIMEOUT_SECONDS);
  69. } else {
  70. LOG_ERROR(WebService, "Bad URL scheme {}", parsedUrl.m_Scheme);
  71. return Common::WebResult{Common::WebResult::Code::InvalidURL, "Bad URL scheme"};
  72. }
  73. }
  74. if (cli == nullptr) {
  75. LOG_ERROR(WebService, "Invalid URL {}", host + path);
  76. return Common::WebResult{Common::WebResult::Code::InvalidURL, "Invalid URL"};
  77. }
  78. httplib::Headers params;
  79. if (!jwt.empty()) {
  80. params = {
  81. {std::string("Authorization"), fmt::format("Bearer {}", jwt)},
  82. };
  83. } else if (!username.empty()) {
  84. params = {
  85. {std::string("x-username"), username},
  86. {std::string("x-token"), token},
  87. };
  88. }
  89. params.emplace(std::string("api-version"),
  90. std::string(API_VERSION.begin(), API_VERSION.end()));
  91. if (method != "GET") {
  92. params.emplace(std::string("Content-Type"), std::string("application/json"));
  93. };
  94. httplib::Request request;
  95. request.method = method;
  96. request.path = path;
  97. request.headers = params;
  98. request.body = data;
  99. httplib::Response response;
  100. if (!cli->send(request, response)) {
  101. LOG_ERROR(WebService, "{} to {} returned null", method, host + path);
  102. return Common::WebResult{Common::WebResult::Code::LibError, "Null response"};
  103. }
  104. if (response.status >= 400) {
  105. LOG_ERROR(WebService, "{} to {} returned error status code: {}", method, host + path,
  106. response.status);
  107. return Common::WebResult{Common::WebResult::Code::HttpError,
  108. std::to_string(response.status)};
  109. }
  110. auto content_type = response.headers.find("content-type");
  111. if (content_type == response.headers.end()) {
  112. LOG_ERROR(WebService, "{} to {} returned no content", method, host + path);
  113. return Common::WebResult{Common::WebResult::Code::WrongContent, ""};
  114. }
  115. if (content_type->second.find("application/json") == std::string::npos &&
  116. content_type->second.find("text/html; charset=utf-8") == std::string::npos) {
  117. LOG_ERROR(WebService, "{} to {} returned wrong content: {}", method, host + path,
  118. content_type->second);
  119. return Common::WebResult{Common::WebResult::Code::WrongContent, "Wrong content"};
  120. }
  121. return Common::WebResult{Common::WebResult::Code::Success, "", response.body};
  122. }
  123. // Retrieve a new JWT from given username and token
  124. void UpdateJWT() {
  125. if (username.empty() || token.empty()) {
  126. return;
  127. }
  128. auto result = GenericJson("POST", "/jwt/internal", "", "", username, token);
  129. if (result.result_code != Common::WebResult::Code::Success) {
  130. LOG_ERROR(WebService, "UpdateJWT failed");
  131. } else {
  132. std::lock_guard lock{jwt_cache.mutex};
  133. jwt_cache.username = username;
  134. jwt_cache.token = token;
  135. jwt_cache.jwt = jwt = result.returned_data;
  136. }
  137. }
  138. std::string host;
  139. std::string username;
  140. std::string token;
  141. std::string jwt;
  142. std::unique_ptr<httplib::Client> cli;
  143. struct JWTCache {
  144. std::mutex mutex;
  145. std::string username;
  146. std::string token;
  147. std::string jwt;
  148. };
  149. static inline JWTCache jwt_cache;
  150. };
  151. Client::Client(std::string host, std::string username, std::string token)
  152. : impl{std::make_unique<Impl>(std::move(host), std::move(username), std::move(token))} {}
  153. Client::~Client() = default;
  154. Common::WebResult Client::PostJson(const std::string& path, const std::string& data,
  155. bool allow_anonymous) {
  156. return impl->GenericJson("POST", path, data, allow_anonymous);
  157. }
  158. Common::WebResult Client::GetJson(const std::string& path, bool allow_anonymous) {
  159. return impl->GenericJson("GET", path, "", allow_anonymous);
  160. }
  161. Common::WebResult Client::DeleteJson(const std::string& path, const std::string& data,
  162. bool allow_anonymous) {
  163. return impl->GenericJson("DELETE", path, data, allow_anonymous);
  164. }
  165. } // namespace WebService