nanoMMO 0.97.8
Building an MMO: The Engineering Series
Loading...
Searching...
No Matches
login_server.cc
Go to the documentation of this file.
2
3#include <chrono>
4#include <iostream>
5#include <memory>
6#include <optional>
7#include <string>
8#include <string_view>
9#include <utility>
10#include <vector>
11
12#include "absl/memory/memory.h"
13#include "absl/strings/str_cat.h"
14#include "protocol/framing.h"
15#include "protocol/messages.h"
16#include "protocol/version.h"
17#include "server/characters.h"
18#include "server/listen.h"
19#include "server/password.h"
20#include "server/session.h"
21#include "server/tracing.h"
22
23namespace nanommo {
24
25namespace {
26
27// Says why the reply refuses: in English, as a client before 0.96.0 shows it,
28// and as a sentence, for the client to say in its player's language.
29void Refuse(protocol::LoginReply& reply, const Sentence& why) {
30 reply.set_error(why.english);
31 *reply.mutable_why() = why.message;
32}
33
34// The account the name and password are for, or a reply that says why not:
35// a wrong password, or a name that's taken or no good for a new account.
36absl::StatusOr<uint32_t> Authenticate(const protocol::LoginRequest& request,
37 Accounts& accounts,
38 protocol::LoginReply& reply) {
39 if (request.new_account()) {
40 absl::Status problem = CheckUsername(request.username());
41 if (problem.ok()) {
42 problem = CheckPassword(request.password());
43 }
44 if (!problem.ok()) {
45 Refuse(reply, SentenceOf(problem));
46 return 0;
47 }
48 const absl::StatusOr<std::string> hash = HashPassword(request.password());
49 if (!hash.ok()) {
50 return hash.status();
51 }
52 const absl::StatusOr<uint32_t> created =
53 accounts.Create(request.username(), *hash);
54 if (absl::IsAlreadyExists(created.status())) {
55 Refuse(reply, Msg("That name is taken."));
56 return 0;
57 }
58 return created;
59 }
60 const absl::StatusOr<Account> account = accounts.Find(request.username());
61 if (!account.ok() && !absl::IsNotFound(account.status())) {
62 return account.status();
63 }
64 if (!account.ok() ||
65 !VerifyPassword(account->password_hash, request.password())) {
66 Refuse(reply, Msg("Wrong name or password."));
67 return 0;
68 }
69 return account->id;
70}
71
72// What the request asks for, as its span's name.
73std::string_view Asked(const protocol::LoginRequest& request) {
74 if (request.list_worlds()) {
75 return "list worlds";
76 }
77 if (request.session().empty()) {
78 return request.new_account() ? "create account" : "log in";
79 }
80 if (request.enter()) {
81 return "enter world";
82 }
83 if (request.create_character()) {
84 return "create character";
85 }
86 if (request.delete_character()) {
87 return "delete character";
88 }
89 return "list characters";
90}
91
92// An error the player can read, from a status a character's request got,
93// or the status itself, when it's the servers' and not theirs.
94absl::Status Readable(const absl::Status& status, protocol::LoginReply& reply) {
95 if (absl::IsInvalidArgument(status) || absl::IsAlreadyExists(status) ||
96 absl::IsResourceExhausted(status) || absl::IsNotFound(status)) {
97 Refuse(reply, SentenceOf(status));
98 return absl::OkStatus();
99 }
100 return status;
101}
102
103} // namespace
104
105const char* Outcome(const absl::StatusOr<protocol::LoginReply>& handled) {
106 if (!handled.ok()) {
107 return "failed";
108 }
109 return handled->ok() ? "ok" : "refused";
110}
111
112absl::StatusOr<protocol::LoginReply> HandleLogin(
113 const protocol::LoginRequest& request, Accounts& accounts, Tokens& tokens,
114 Characters& characters) {
115 protocol::LoginReply reply;
116 uint32_t account = 0;
117 if (request.session().empty()) {
118 // A client of another version would log in, then fail to make sense of
119 // what the world sends it: it's told which version to get instead.
120 if (!Compatible(request.version(), kVersion)) {
121 // Translators: $0 is the servers' version, such as 0.96.0.
122 Refuse(reply, request.version().empty()
123 ? Msg("This client is too old for the servers, which "
124 "are $0. Get the new one to play.",
125 Name(kVersion))
126 // Translators: $0 is this client's version, and $1
127 // the servers', such as 0.96.0.
128 : Msg("This client is $0, and the servers are $1. Get "
129 "the $1 client to play.",
130 Name(request.version()), Name(kVersion)));
131 return reply;
132 }
133 // Logging in, or making an account: a session for what comes next.
134 const absl::StatusOr<uint32_t> id = Authenticate(request, accounts, reply);
135 if (!id.ok()) {
136 return id.status();
137 }
138 if (!reply.error().empty()) {
139 return reply;
140 }
141 account = *id;
142 const absl::StatusOr<std::string> session = tokens.Open(account);
143 if (!session.ok()) {
144 return session.status();
145 }
146 reply.set_session(*session);
147 } else {
148 const absl::StatusOr<uint32_t> id = tokens.AccountOf(request.session());
149 if (absl::IsNotFound(id.status())) {
150 Refuse(reply, Msg("You've been away a while. Log in again."));
151 return reply;
152 }
153 if (!id.ok()) {
154 return id.status();
155 }
156 account = *id;
157 reply.set_session(request.session());
158 }
159
160 if (request.enter()) {
161 // A token to enter the character's world as it, which the world checks
162 // the character's in, once we know it's the account's.
163 const absl::StatusOr<std::string> world =
164 characters.WorldOf(account, request.character());
165 if (world.ok()) {
166 const absl::StatusOr<std::string> token =
167 tokens.Issue(request.character());
168 if (!token.ok()) {
169 return token.status();
170 }
171 reply.set_token(*token);
172 } else if (absl::Status unreadable = Readable(world.status(), reply);
173 !unreadable.ok()) {
174 return unreadable;
175 }
176 } else if (request.create_character()) {
177 const absl::StatusOr<uint32_t> created = characters.Create(
178 account, request.world(), request.name(),
179 request.has_looks() ? std::optional(request.looks()) : std::nullopt);
180 if (!created.ok()) {
181 if (absl::Status unreadable = Readable(created.status(), reply);
182 !unreadable.ok()) {
183 return unreadable;
184 }
185 }
186 } else if (request.delete_character()) {
187 if (absl::Status unreadable =
188 Readable(characters.Delete(account, request.character()), reply);
189 !unreadable.ok()) {
190 return unreadable;
191 }
192 }
193 // Whatever it asked, the characters as they are now come back, so the
194 // client's list is the server's.
195 absl::StatusOr<std::vector<protocol::CharacterListing>> listed =
196 characters.List(account);
197 if (!listed.ok()) {
198 return listed.status();
199 }
200 reply.mutable_characters()->Assign(listed->begin(), listed->end());
201 reply.set_ok(reply.error().empty());
202 return reply;
203}
204
205absl::StatusOr<std::unique_ptr<LoginServer>> LoginServer::Create(
206 asio::io_context& io, uint16_t port, asio::ssl::context& tls,
207 Accounts& accounts, Tokens& tokens, Characters& characters, Consul& consul,
208 LoginMetrics& metrics) {
209 std::unique_ptr<LoginServer> server = absl::WrapUnique(
210 new LoginServer(io, tls, accounts, tokens, characters, consul, metrics));
211 const absl::Status started = server->Start(port);
212 if (!started.ok()) {
213 return started;
214 }
215 return server;
216}
217
218LoginServer::LoginServer(asio::io_context& io, asio::ssl::context& tls,
219 Accounts& accounts, Tokens& tokens,
220 Characters& characters, Consul& consul,
221 LoginMetrics& metrics)
222 : acceptor_(io),
223 tls_(tls),
224 accounts_(accounts),
225 tokens_(tokens),
226 characters_(characters),
227 consul_(consul),
228 metrics_(metrics) {}
229
230absl::Status LoginServer::Start(uint16_t port) {
231 const absl::Status listening = Listen(acceptor_, port);
232 if (!listening.ok()) {
233 return listening;
234 }
235 Accept();
236 return absl::OkStatus();
237}
238
239void LoginServer::Accept() {
240 acceptor_.async_accept([this](std::error_code error,
241 asio::ip::tcp::socket socket) {
242 if (!error) {
243 const auto on_message = [this](Session& session,
244 const std::string& bytes) {
245 protocol::LoginRequest request;
246 if (!request.ParseFromString(bytes)) {
247 session.Close();
248 return;
249 }
250 // Each request is a trace of its own, from here to its answer.
251 const auto start = std::chrono::steady_clock::now();
252 Span span = StartSpan(Asked(request), SpanKind::kServer);
253 if (request.enter()) {
254 span.SetAttribute("nanommo.character", request.character());
255 }
256 if (request.list_worlds()) {
257 const protocol::LoginReply worlds = ListWorlds();
258 session.Send(Frame(worlds));
259 metrics_.ObserveRequest(worlds.ok() ? "ok" : "failed",
260 std::chrono::steady_clock::now() - start);
261 return;
262 }
263 absl::StatusOr<protocol::LoginReply> handled =
264 HandleLogin(request, accounts_, tokens_, characters_);
265 const char* result = Outcome(handled);
266 protocol::LoginReply reply;
267 if (handled.ok()) {
268 reply = *std::move(handled);
269 // A wrong password, say, is the player's mistake, not the server's.
270 if (!reply.error().empty()) {
271 span.SetAttribute("nanommo.refused", reply.error());
272 }
273 } else {
274 std::cerr << "nanommo login: " << handled.status() << TraceField()
275 << "\n";
276 span.SetError(handled.status().ToString());
277 Refuse(reply, Msg("The server couldn't do that. Try again later."));
278 }
279 // A login, as it happens: the requests that follow it go with its
280 // session, without a name.
281 if (request.session().empty()) {
282 if (reply.ok()) {
283 std::cout << "nanommo login: " << request.username()
284 << (request.new_account() ? " created an account"
285 : " logged in")
286 << TraceField() << std::endl;
287 } else {
288 std::cout << "nanommo login: refused " << request.username() << ": "
289 << reply.error() << TraceField() << std::endl;
290 }
291 }
292 // The worlds come with each answer, for the list the client shows.
293 if (reply.ok()) {
294 reply.mutable_worlds()->CopyFrom(ListWorlds().worlds());
295 }
296 session.Send(Frame(reply));
297 metrics_.ObserveRequest(result,
298 std::chrono::steady_clock::now() - start);
299 };
300 const auto on_close = [] {};
301 std::make_shared<Session>(std::move(socket), tls_, on_message, on_close)
302 ->Start();
303 }
304 Accept();
305 });
306}
307
308protocol::LoginReply LoginServer::ListWorlds() {
309 // A list from the last second is new enough, and a crowd of clients costs
310 // Consul a request a second, while this thread waits for its answer.
311 const auto now = std::chrono::steady_clock::now();
312 if (worlds_.ok() && now - worlds_at_ < std::chrono::seconds(1)) {
313 return worlds_;
314 }
315 protocol::LoginReply reply;
316 const absl::StatusOr<std::vector<protocol::WorldListing>> worlds =
317 consul_.Worlds();
318 if (!worlds.ok()) {
319 std::cerr << "nanommo login: " << worlds.status() << "\n";
320 // The worlds play on without Consul, so the list from the last half a
321 // minute is better than none, which would leave a player nowhere to go.
322 if (worlds_.ok() && now - worlds_at_ < std::chrono::seconds(30)) {
323 return worlds_;
324 }
325 Refuse(reply, Msg("The server couldn't list the worlds. Try again later."));
326 return reply;
327 }
328 reply.set_ok(true);
329 reply.mutable_worlds()->Assign(worlds->begin(), worlds->end());
330 worlds_ = reply;
331 worlds_at_ = now;
332 return reply;
333}
334
335} // namespace nanommo
absl::StatusOr< uint32_t > Create(uint32_t account, const std::string &world, const std::string &name, const std::optional< protocol::Looks > &looks=std::nullopt)
absl::Status Delete(uint32_t account, uint32_t id)
absl::StatusOr< std::vector< protocol::CharacterListing > > List(uint32_t account)
Definition characters.cc:19
absl::StatusOr< std::string > WorldOf(uint32_t account, uint32_t id)
static absl::StatusOr< std::unique_ptr< LoginServer > > Create(asio::io_context &io, uint16_t port, asio::ssl::context &tls, Accounts &accounts, Tokens &tokens, Characters &characters, Consul &consul, LoginMetrics &metrics)
absl::StatusOr< std::string > Issue(uint32_t player_id)
Definition tokens.cc:36
absl::StatusOr< uint32_t > AccountOf(const std::string &session)
Definition tokens.cc:87
absl::StatusOr< std::string > Open(uint32_t account_id)
Definition tokens.cc:76
Definition chat.cc:9
Span StartSpan(std::string_view name, SpanKind kind)
Definition tracing.cc:389
absl::Status CheckUsername(std::string_view username)
An InvalidArgument error says what's wrong, in words for the player.
Definition accounts.cc:13
absl::StatusOr< std::string > HashPassword(std::string_view password)
Definition password.cc:22
bool VerifyPassword(const std::string &hash, std::string_view password)
Definition password.cc:36
const char * Outcome(const absl::StatusOr< protocol::LoginReply > &handled)
Sentence SentenceOf(const absl::Status &status)
Definition messages.cc:224
std::string Refuse(int status, std::string_view why)
An HTTP answer that turns the connection down, with why in its body.
Definition websocket.cc:139
std::string Frame(const google::protobuf::MessageLite &message)
The size goes in front, as four bytes in network byte order.
Definition framing.cc:14
bool Compatible(std::string_view client, std::string_view server)
Definition version.cc:32
std::string TraceField()
Definition tracing.cc:398
Sentence Msg(std::string_view text, Parts... parts)
Definition messages.h:92
Part Name(std::string_view name)
Definition messages.cc:113
absl::Status CheckPassword(std::string_view password)
Definition accounts.cc:28
absl::StatusOr< protocol::LoginReply > HandleLogin(const protocol::LoginRequest &request, Accounts &accounts, Tokens &tokens, Characters &characters)
absl::Status Listen(asio::ip::tcp::acceptor &acceptor, uint16_t port)
Opens the acceptor on the port, on all addresses, and starts listening.
Definition listen.cc:11