web_service_runtime.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. #include "web_service_runtime.h"
  2. #include <algorithm>
  3. #include <array>
  4. #include <atomic>
  5. #include <chrono>
  6. #include <cstdio>
  7. #include "../../core/logging/log.h"
  8. #include "../../middleware/web_service/messages/opcode1801.h"
  9. #include "../../middleware/web_service/messages/opcode1821.h"
  10. #include "../../middleware/web_service/messages/opcode1901.h"
  11. #include "../../middleware/web_service/messages/opcode205.h"
  12. #include "../../middleware/web_service/messages/opcode206.h"
  13. #include "../../middleware/web_service/messages/opcode2400.h"
  14. #include "../../middleware/web_service/messages/opcode501_codec.h"
  15. #include "../../middleware/web_service/messages/opcode503.h"
  16. #include "../../middleware/web_service/messages/opcode504.h"
  17. #include "../../middleware/web_service/messages/opcode601/opcode601_codec.h"
  18. #include "../../middleware/web_service/messages/opcode701/opcode701_codec.h"
  19. #include "../../middleware/web_service/messages/opcode702.h"
  20. #include "../../middleware/web_service/messages/opcode801.h"
  21. #include "../../middleware/web_service/messages/opcode901/opcode901_codec.h"
  22. #include "../../middleware/web_service/messages/opcode903.h"
  23. #include "../../middleware/web_service/messages/opcode904/opcode904_codec.h"
  24. #include "../../middleware/web_service/web_service_envelope.h"
  25. #include "../../state/account/account_state.h"
  26. #include "../../state/activity/membership/activity_membership_query.h"
  27. #include "../../state/build_data/runtime.h"
  28. #include "../../state/runtime/runtime.h"
  29. #include "opcode_routes.h"
  30. #include "web_service_actions.h"
  31. namespace sunrise::server::web_service {
  32. /** Web Service opcode used by the Character screen's Equip action. */
  33. constexpr std::uint16_t kEquipOpcode = 403;
  34. /** Web Service opcode used by the Character screen's Unequip action. */
  35. constexpr std::uint16_t kUnequipOpcode = 404;
  36. /** Web Service opcode used by item-state actions such as finisher Favorite. */
  37. constexpr std::uint16_t kItemStateOpcode = 406;
  38. /** Web Service opcode used by the Character screen's Dismantle action. */
  39. constexpr std::uint16_t kItemDismantleOpcode = 402;
  40. /** Web Service opcode used by Collections to create one item instance. */
  41. constexpr std::uint16_t kItemAcquisitionOpcode = 1820;
  42. /**
  43. * Logical status of a refused action. The descriptor biases logical zero to the wire success the
  44. * Client expects, so any other logical value reports a refusal. Its five bits hold no error
  45. * taxonomy, so one code covers every reason and the log line names the actual one.
  46. */
  47. constexpr std::int32_t kRefusedStatus = 1;
  48. /**
  49. * Opcodes whose reply may name a resident the client no longer holds.
  50. * Kept sorted; the lookup below is a binary search.
  51. */
  52. constexpr auto kResidentDependentOpcodes =
  53. std::to_array<std::uint16_t>({402, 403, 404, 406, 504, 903, 1801, 1820, 1901, 2400});
  54. /** One refusal line carries both request indices, the clock presence, and the clock verdict. */
  55. constexpr std::size_t kPurchaseLineCapacity = 128;
  56. constexpr std::size_t kEchoLineCapacity = 64;
  57. /** Season of Arrivals artifact vendor row in the installed build's vendor index. */
  58. constexpr std::int16_t kArtifactVendorIndex = 430;
  59. /** Glimmer the artifact vendor charges to reset its mods, as retail charges. */
  60. constexpr std::int32_t kArtifactResetGlimmerCost = 20'000;
  61. /** The artifact vendor's reset row. Every lower row unlocks one mod tier. */
  62. constexpr std::uint16_t kArtifactResetSaleIndex = 5;
  63. /**
  64. * Reads the server's own clock for the purchase clock rule.
  65. * The system clock counts from the Unix epoch, which is the same base the request field uses.
  66. * @return Current time in Unix seconds.
  67. */
  68. [[nodiscard]] std::int64_t server_clock_seconds() noexcept {
  69. const auto sinceEpoch = std::chrono::system_clock::now().time_since_epoch();
  70. return std::chrono::duration_cast<std::chrono::seconds>(sinceEpoch).count();
  71. }
  72. /** Issues a strictly increasing family-5 clock, including multiple requests in one second. */
  73. std::uint64_t next_family5_clock() noexcept {
  74. static std::atomic<std::uint64_t> issued{0};
  75. const auto wall = static_cast<std::uint64_t>(server_clock_seconds());
  76. std::uint64_t previous = issued.load(std::memory_order_relaxed);
  77. std::uint64_t next = 0;
  78. do {
  79. next = wall > previous ? wall : previous + 1;
  80. } while (!issued.compare_exchange_weak(previous, next, std::memory_order_relaxed));
  81. return next;
  82. }
  83. /** Records the authoritative world state carried by the client's character write-back. */
  84. bool note_character_writeback(
  85. const middleware::web_service::Message& message,
  86. std::span<const state::account::inventory::PresentedItemRow> presentation) noexcept {
  87. namespace writeback = middleware::web_service::messages::opcode702;
  88. writeback::Request request{};
  89. const bool parsed = writeback::parse_request(message, request);
  90. std::array<char, core::log::kLineCapacity> line{};
  91. const int written = std::snprintf(line.data(),
  92. line.size(),
  93. "ev=activity stage=writeback result=%s world_state=%u",
  94. parsed ? "ok" : "unparsed",
  95. static_cast<unsigned>(request.worldState));
  96. if (written > 0) {
  97. core::log::write(core::log::Channel::server,
  98. core::log::Level::info,
  99. {line.data(), static_cast<std::size_t>(written)});
  100. }
  101. if (parsed && request.hasWorldState) {
  102. state::activity::membership::note_client_writeback(request.worldState
  103. == writeback::kInWorld);
  104. }
  105. return parsed
  106. && (!request.newItems
  107. || state::account::inventory::record_character_seen(*request.newItems,
  108. presentation));
  109. }
  110. /** @return True when a purchase names the seasonal artifact vendor, which is answered here. */
  111. [[nodiscard]] bool names_artifact_vendor(const middleware::web_service::Message& message) noexcept {
  112. namespace purchase_codec = middleware::web_service::messages::opcode901;
  113. purchase_codec::Request purchase{};
  114. return purchase_codec::parse_request(message, purchase)
  115. && purchase.vendorIndex == kArtifactVendorIndex;
  116. }
  117. /**
  118. * Refuses one vendor purchase and answers it.
  119. * No award, cost or stock rule exists yet, so no purchase can succeed. The refusal must still be
  120. * answered, because no answer holds the head of the client's pending queue.
  121. * @param message Parsed purchase request.
  122. * @param response Response-body storage owned by the caller.
  123. * @param written Receives the encoded response size.
  124. * @return True when the refusal was encoded.
  125. */
  126. [[nodiscard]] bool refuse_purchase(const middleware::web_service::Message& message,
  127. std::span<std::byte> response,
  128. std::size_t& written) noexcept {
  129. namespace purchase_codec = middleware::web_service::messages::opcode901;
  130. purchase_codec::Request purchase;
  131. const bool parsed = purchase_codec::parse_request(message, purchase);
  132. std::array<char, kPurchaseLineCapacity> line{};
  133. const int length =
  134. parsed ? std::snprintf(line.data(),
  135. line.size(),
  136. "ev=ws901 stage=purchase result=refuse vendor=%d sale=%d present=%u",
  137. static_cast<int>(purchase.vendorIndex),
  138. static_cast<int>(purchase.saleIndex),
  139. purchase.hasClock ? 1U : 0U)
  140. : std::snprintf(line.data(),
  141. line.size(),
  142. "ev=ws901 stage=purchase result=refuse reason=parse");
  143. if (length > 0) {
  144. core::log::write(core::log::Channel::server,
  145. core::log::Level::warn,
  146. {line.data(), static_cast<std::size_t>(length)});
  147. }
  148. middleware::web_service::StatusResponse status{};
  149. status.code = kRefusedStatus;
  150. // The trailing bool drives a local action effect on the client, so it stays clear.
  151. status.trailingBool = false;
  152. return middleware::web_service::encode_response(
  153. message,
  154. middleware::web_service::ResponseShape::statusPairWithBool,
  155. status,
  156. response,
  157. written);
  158. }
  159. /** Accepts one affordable, unlocked-tier artifact mod and reports the local purchase effect. */
  160. [[nodiscard]] bool purchase_artifact_mod(const middleware::web_service::Message& message,
  161. std::span<std::byte> response,
  162. std::size_t& written,
  163. Outcome& outcome) noexcept {
  164. namespace purchase_codec = middleware::web_service::messages::opcode901;
  165. purchase_codec::Request purchase{};
  166. if (!purchase_codec::parse_request(message, purchase)
  167. || purchase.vendorIndex != kArtifactVendorIndex || purchase.saleIndex < 0
  168. || purchase.saleIndex
  169. >= static_cast<std::int16_t>(state::build_data::kArtifactSaleRowCapacity)) {
  170. return false;
  171. }
  172. const auto saleIndex = static_cast<std::uint16_t>(purchase.saleIndex);
  173. if (saleIndex == kArtifactResetSaleIndex) {
  174. state::ArtifactResetResult reset{};
  175. if (!state::reset_artifact(kArtifactResetGlimmerCost, reset)) {
  176. return false;
  177. }
  178. middleware::web_service::StatusResponse status{};
  179. status.trailingBool = true;
  180. const bool encoded = middleware::web_service::encode_response(
  181. message,
  182. middleware::web_service::ResponseShape::statusPairWithBool,
  183. status,
  184. response,
  185. written);
  186. outcome.hasArtifactReset = encoded;
  187. if (encoded) {
  188. outcome.artifactReset = reset;
  189. }
  190. return encoded;
  191. }
  192. auto* mutation = emplace_mutation<state::PendingArtifactPurchase>(outcome);
  193. if (mutation == nullptr || !state::prepare_artifact_mod_unlock(saleIndex, *mutation)) {
  194. clear_mutation(outcome);
  195. return false;
  196. }
  197. std::array<char, kPurchaseLineCapacity> line{};
  198. const int length = std::snprintf(line.data(),
  199. line.size(),
  200. "ev=ws901 stage=artifact result=ok vendor=%d sale=%d",
  201. static_cast<int>(purchase.vendorIndex),
  202. static_cast<int>(purchase.saleIndex));
  203. if (length > 0) {
  204. core::log::write(core::log::Channel::server,
  205. core::log::Level::info,
  206. {line.data(), static_cast<std::size_t>(length)});
  207. }
  208. middleware::web_service::StatusResponse status{};
  209. status.trailingBool = true;
  210. const bool encoded = middleware::web_service::encode_response(
  211. message,
  212. middleware::web_service::ResponseShape::statusPairWithBool,
  213. status,
  214. response,
  215. written);
  216. if (!encoded) {
  217. // The purchase was written when it was prepared, so a refused reply undoes it.
  218. (void)state::replace_artifact_mod_mask(mutation->afterMask, mutation->beforeMask);
  219. clear_mutation(outcome);
  220. return false;
  221. }
  222. return true;
  223. }
  224. /**
  225. * Answers a request whose own codec refused with the bare correlated echo.
  226. * The Client matches on the echoed transaction id. A missing body is worse than a thin one. It
  227. * under-runs the decoder and takes the BAP connection down.
  228. * @param message Parsed request whose correlation fields are echoed.
  229. * @param response Svc-11 response-body storage owned by the caller.
  230. * @param written Gets the encoded response-body size in bytes.
  231. * @return True when the echo fits.
  232. */
  233. bool encode_echo(const middleware::web_service::Message& message,
  234. std::span<std::byte> response,
  235. std::size_t& written) noexcept {
  236. std::array<char, kEchoLineCapacity> line{};
  237. const int count = std::snprintf(
  238. line.data(), line.size(), "ev=ws stage=body result=echo opcode=%u", message.opcode);
  239. if (count > 0) {
  240. core::log::write(core::log::Channel::server,
  241. core::log::Level::warn,
  242. {line.data(), static_cast<std::size_t>(count)});
  243. }
  244. namespace ws = middleware::web_service;
  245. return ws::encode_response(
  246. message, ws::ResponseShape::generic, ws::StatusResponse{}, response, written);
  247. }
  248. /**
  249. * Encodes the refusal reply for a request whose answer may name a resident the client dropped.
  250. * @param request Whole decrypted svc-10 body.
  251. * @param response Svc-11 response-body storage owned by the caller.
  252. * @param written Gets the encoded response-body size; zero when the opcode is not refused here.
  253. * @param refused Gets true when the opcode is one of the resident-dependent set.
  254. * @return False when neither the refusal nor the bare echo could be encoded.
  255. */
  256. bool encode_resident_dependent_refusal(std::span<const std::byte> request,
  257. std::span<std::byte> response,
  258. std::size_t& written,
  259. bool& refused) noexcept {
  260. written = 0;
  261. refused = false;
  262. middleware::web_service::Message message;
  263. if (!middleware::web_service::parse_request(request, message)
  264. || !std::binary_search(
  265. kResidentDependentOpcodes.begin(), kResidentDependentOpcodes.end(), message.opcode)) {
  266. return true;
  267. }
  268. refused = true;
  269. middleware::web_service::ResponseShape shape{};
  270. resolve_response_shape(message.opcode, shape);
  271. middleware::web_service::StatusResponse status{};
  272. status.code = kRefusedStatus;
  273. return middleware::web_service::encode_response(message, shape, status, response, written)
  274. || encode_echo(message, response, written);
  275. }
  276. /**
  277. * Parses one request, prepares any action it names, and encodes the reply that reports it.
  278. * @param request Whole decrypted svc-10 body.
  279. * @param response Svc-11 response-body storage owned by the caller.
  280. * @param written Gets the encoded response-body size, or zero when the header does not parse.
  281. * @param outcome Gets the prepared action for the caller to publish, and is left empty when
  282. * the action was refused or the reply could not be encoded.
  283. * @return False only when the envelope header does not parse.
  284. */
  285. bool consume(std::span<const std::byte> request,
  286. std::span<std::byte> response,
  287. std::size_t& written,
  288. Outcome& outcome,
  289. std::span<const state::account::inventory::PresentedItemRow> presentation) noexcept {
  290. written = 0;
  291. outcome = {};
  292. middleware::web_service::Message message;
  293. if (!middleware::web_service::parse_request(request, message)) {
  294. core::log::write(
  295. core::log::Channel::server, core::log::Level::warn, "ev=ws stage=parse result=fail");
  296. return false;
  297. }
  298. if (message.opcode == middleware::web_service::messages::opcode702::kOpcode) {
  299. if (!note_character_writeback(message, presentation)) {
  300. return false;
  301. }
  302. }
  303. if (message.opcode == middleware::web_service::messages::opcode205::kOpcode) {
  304. state::InvestmentState investment{};
  305. return (state::investment_snapshot(investment)
  306. && middleware::web_service::messages::opcode205::encode_response(
  307. message, investment, next_family5_clock(), response, written))
  308. || encode_echo(message, response, written);
  309. }
  310. if (message.opcode == middleware::web_service::messages::opcode503::kOpcode) {
  311. middleware::web_service::messages::opcode503::Request bootstrap;
  312. const bool parsed =
  313. middleware::web_service::messages::opcode503::parse_request(message, bootstrap);
  314. // The request's own key is echoed and adopted. An authored id here costs the ship and the
  315. // banner.
  316. if (!bootstrap.hasPrimarySoid) {
  317. bootstrap.primarySoid = state::account_snapshot().primarySoid;
  318. }
  319. state::InvestmentState investment{};
  320. if (!parsed || !state::investment_snapshot(investment)
  321. || !middleware::web_service::messages::opcode503::encode_response(
  322. message, bootstrap, investment, next_family5_clock(), response, written)) {
  323. return encode_echo(message, response, written);
  324. }
  325. if (bootstrap.hasPrimarySoid && !state::set_primary_soid(bootstrap.primarySoid)) {
  326. core::log::write(core::log::Channel::server,
  327. core::log::Level::warn,
  328. "ev=ws503 stage=adopt result=fail");
  329. }
  330. return true;
  331. }
  332. if (message.opcode == middleware::web_service::messages::opcode501::kOpcode) {
  333. // Returns a SOID family three already publishes. The request body is not parsed.
  334. const std::uint64_t characterSoid =
  335. state::account::selected_character_soid(state::account_snapshot());
  336. return middleware::web_service::messages::opcode501::encode_response(
  337. message, characterSoid, response, written)
  338. || encode_echo(message, response, written);
  339. }
  340. // The artifact vendor is answered here. Every other vendor purchase falls through to the
  341. // shared response-shape path, which runs the action and answers its status: an action that
  342. // prepared no mutation is answered with the refused code.
  343. if (message.opcode == middleware::web_service::messages::opcode901::kOpcode
  344. && names_artifact_vendor(message)) {
  345. return purchase_artifact_mod(message, response, written, outcome)
  346. || refuse_purchase(message, response, written)
  347. || encode_echo(message, response, written);
  348. }
  349. if (message.opcode == middleware::web_service::messages::opcode601::kOpcode) {
  350. return middleware::web_service::messages::opcode601::encode_response(
  351. message, response, written)
  352. || encode_echo(message, response, written);
  353. }
  354. // A subscribe whose body does not parse is still answered; only the subscription is dropped.
  355. middleware::queuez::Subscription subscription;
  356. const bool subscribes =
  357. message.opcode == middleware::web_service::messages::opcode206::kOpcode
  358. && middleware::web_service::messages::opcode206::parse_request(message, subscription);
  359. // The action runs before its reply is encoded, because the reply reports whether it worked.
  360. // Most actions fill the outcome only after preparing a whole transition. WS-701 also accepts
  361. // a valid no-op heartbeat, so that one success is tracked separately from mutation presence.
  362. bool dispatched = true;
  363. bool acceptedWithoutMutation = false;
  364. bool profileSetupRefused = false;
  365. if (message.opcode == middleware::web_service::messages::opcode1801::kOpcode) {
  366. claim_record(message, outcome);
  367. } else if (message.opcode == middleware::web_service::messages::opcode504::kOpcode) {
  368. select_character(message, outcome);
  369. } else if (message.opcode == kItemDismantleOpcode) {
  370. dismantle_item(message, outcome);
  371. } else if (message.opcode == kEquipOpcode) {
  372. mutate_equipment(message, false, outcome);
  373. } else if (message.opcode == kUnequipOpcode) {
  374. mutate_equipment(message, true, outcome);
  375. } else if (message.opcode == middleware::web_service::messages::opcode801::kOpcode) {
  376. mutate_subclass_selection(message, outcome);
  377. } else if (message.opcode == middleware::web_service::messages::opcode1821::kOpcode) {
  378. equip_title(message, outcome);
  379. } else if (message.opcode == middleware::web_service::messages::opcode903::kOpcode) {
  380. mutate_socket_plug(message, outcome);
  381. } else if (message.opcode == middleware::web_service::messages::opcode1901::kOpcode) {
  382. mutate_equipped_socket_plug(message, outcome);
  383. } else if (message.opcode == kItemStateOpcode) {
  384. mutate_item_state(message, outcome);
  385. } else if (message.opcode == middleware::web_service::messages::opcode701::kOpcode) {
  386. const state::SettingsUpdateDisposition disposition = mutate_settings(message, outcome);
  387. acceptedWithoutMutation = disposition == state::SettingsUpdateDisposition::acceptedNoChange;
  388. profileSetupRefused = outcome.profileSetupRefused;
  389. } else if (message.opcode == kItemAcquisitionOpcode) {
  390. acquire_item(message, outcome);
  391. } else if (message.opcode == middleware::web_service::messages::opcode2400::kOpcode) {
  392. claim_season_pass_reward(message, outcome);
  393. } else if (message.opcode == middleware::web_service::messages::opcode901::kOpcode) {
  394. purchase_item(message, outcome);
  395. } else if (message.opcode == middleware::web_service::messages::opcode904::kOpcode) {
  396. acquire_quest(message, outcome);
  397. } else {
  398. dispatched = false;
  399. }
  400. const bool prepared = outcome.hasSelectedCharacter || outcome.hasTitleEquip
  401. || outcome.hasRecordClaim || has_mutation(outcome);
  402. middleware::web_service::ResponseShape shape{};
  403. resolve_response_shape(message.opcode, shape);
  404. middleware::web_service::StatusResponse status{};
  405. if (awaits_family4_version(message.opcode)) {
  406. // Nothing is published from here. A staged mutation re-encodes this with its own revision.
  407. status.value = middleware::web_service::kNoFamily4Publication;
  408. }
  409. if ((dispatched && !prepared && !acceptedWithoutMutation) || profileSetupRefused) {
  410. status.code = kRefusedStatus;
  411. }
  412. if (!middleware::web_service::encode_response(message, shape, status, response, written)) {
  413. // The echo carries no status, so nothing may be published against it.
  414. outcome = {};
  415. return encode_echo(message, response, written);
  416. }
  417. if (subscribes) {
  418. // Publish the subscription only after its correlated response is complete.
  419. outcome.hasSubscription = true;
  420. outcome.subscription = subscription;
  421. }
  422. return true;
  423. }
  424. } // namespace sunrise::server::web_service