summaryrefslogtreecommitdiffstats
path: root/src/Protocol
diff options
context:
space:
mode:
authorMattes D <github@xoft.cz>2014-08-01 22:35:12 +0200
committerMattes D <github@xoft.cz>2014-08-01 22:35:12 +0200
commit941a182d8a8a210bb6400cc6b2750a06b5f6c038 (patch)
tree82dfee0f38536020345a820c84ff2c4f01c3213b /src/Protocol
parentMerge pull request #1273 from Howaner/GlobalFixes (diff)
parentMerged branch 'master' into NameToUUID. (diff)
downloadcuberite-941a182d8a8a210bb6400cc6b2750a06b5f6c038.tar
cuberite-941a182d8a8a210bb6400cc6b2750a06b5f6c038.tar.gz
cuberite-941a182d8a8a210bb6400cc6b2750a06b5f6c038.tar.bz2
cuberite-941a182d8a8a210bb6400cc6b2750a06b5f6c038.tar.lz
cuberite-941a182d8a8a210bb6400cc6b2750a06b5f6c038.tar.xz
cuberite-941a182d8a8a210bb6400cc6b2750a06b5f6c038.tar.zst
cuberite-941a182d8a8a210bb6400cc6b2750a06b5f6c038.zip
Diffstat (limited to 'src/Protocol')
-rw-r--r--src/Protocol/Authenticator.cpp138
-rw-r--r--src/Protocol/Authenticator.h23
-rw-r--r--src/Protocol/CMakeLists.txt2
-rw-r--r--src/Protocol/MojangAPI.cpp480
-rw-r--r--src/Protocol/MojangAPI.h117
-rw-r--r--src/Protocol/Protocol17x.cpp6
6 files changed, 619 insertions, 147 deletions
diff --git a/src/Protocol/Authenticator.cpp b/src/Protocol/Authenticator.cpp
index 2a7cbc7bc..160564d51 100644
--- a/src/Protocol/Authenticator.cpp
+++ b/src/Protocol/Authenticator.cpp
@@ -2,6 +2,7 @@
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "Authenticator.h"
+#include "MojangAPI.h"
#include "../Root.h"
#include "../Server.h"
#include "../ClientHandle.h"
@@ -18,67 +19,6 @@
#define DEFAULT_AUTH_SERVER "sessionserver.mojang.com"
#define DEFAULT_AUTH_ADDRESS "/session/minecraft/hasJoined?username=%USERNAME%&serverId=%SERVERID%"
-/** This is the data of the root certs for Starfield Technologies, the CA that signed sessionserver.mojang.com's cert:
-Downloaded from http://certs.starfieldtech.com/repository/ */
-static const AString StarfieldCACert()
-{
- return AString(
- // G2 cert
- "-----BEGIN CERTIFICATE-----\n"
- "MIID3TCCAsWgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBjzELMAkGA1UEBhMCVVMx\n"
- "EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT\n"
- "HFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAMTKVN0YXJmaWVs\n"
- "ZCBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAw\n"
- "MFoXDTM3MTIzMTIzNTk1OVowgY8xCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6\n"
- "b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFyZmllbGQgVGVj\n"
- "aG5vbG9naWVzLCBJbmMuMTIwMAYDVQQDEylTdGFyZmllbGQgUm9vdCBDZXJ0aWZp\n"
- "Y2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n"
- "ggEBAL3twQP89o/8ArFvW59I2Z154qK3A2FWGMNHttfKPTUuiUP3oWmb3ooa/RMg\n"
- "nLRJdzIpVv257IzdIvpy3Cdhl+72WoTsbhm5iSzchFvVdPtrX8WJpRBSiUZV9Lh1\n"
- "HOZ/5FSuS/hVclcCGfgXcVnrHigHdMWdSL5stPSksPNkN3mSwOxGXn/hbVNMYq/N\n"
- "Hwtjuzqd+/x5AJhhdM8mgkBj87JyahkNmcrUDnXMN/uLicFZ8WJ/X7NfZTD4p7dN\n"
- "dloedl40wOiWVpmKs/B/pM293DIxfJHP4F8R+GuqSVzRmZTRouNjWwl2tVZi4Ut0\n"
- "HZbUJtQIBFnQmA4O5t78w+wfkPECAwEAAa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8J7oX+zlJ0T1KKY/e97gKvDIr1MvnsoFAZMej2YcOadN\n"
- "+lq2cwQlZut3f+dZxkqZJRRU6ybH838Z1TBwj6+wRir/resp7defqgSHo9T5iaU0\n"
- "X9tDkYI22WY8sbi5gv2cOj4QyDvvBmVmepsZGD3/cVE8MC5fvj13c7JdBmzDI1aa\n"
- "K4UmkhynArPkPw2vCHmCuDY96pzTNbO8acr1zJ3o/WSNF4Azbl5KXZnJHoe0nRrA\n"
- "1W4TNSNe35tfPe/W93bC6j67eA0cQmdrBNj41tpvi/JEoAGrAgEDo4HFMIHCMB0G\n"
- "A1UdDgQWBBS/X7fRzt0fhvRbVazc1xDCDqmI5zCBkgYDVR0jBIGKMIGHgBS/X7fR\n"
- "zt0fhvRbVazc1xDCDqmI56FspGowaDELMAkGA1UEBhMCVVMxJTAjBgNVBAoTHFN0\n"
- "YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAsTKVN0YXJmaWVsZCBD\n"
- "bGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8w\n"
- "DQYJKoZIhvcNAQEFBQADggEBAAWdP4id0ckaVaGsafPzWdqbAYcaT1epoXkJKtv3\n"
- "L7IezMdeatiDh6GX70k1PncGQVhiv45YuApnP+yz3SFmH8lU+nLMPUxA2IGvd56D\n"
- "eruix/U0F47ZEUD0/CwqTRV/p2JdLiXTAAsgGh1o+Re49L2L7ShZ3U0WixeDyLJl\n"
- "xy16paq8U4Zt3VekyvggQQto8PT7dL5WXXp59fkdheMtlb71cZBDzI0fmgAKhynp\n"
- "VSJYACPq4xJDKVtHCN2MQWplBqjlIapBtJUhlbl90TSrE9atvNziPTnNvT51cKEY\n"
- "WQPJIrSPnNVeKtelttQKbfi3QBFGmh95DmK/D5fs4C8fF5Q=\n"
- "-----END CERTIFICATE-----\n"
- );
-}
-
-
-
-
-
cAuthenticator::cAuthenticator(void) :
super("cAuthenticator"),
m_Server(DEFAULT_AUTH_SERVER),
@@ -102,8 +42,8 @@ cAuthenticator::~cAuthenticator()
void cAuthenticator::ReadINI(cIniFile & IniFile)
{
- m_Server = IniFile.GetValueSet("Authentication", "Server", DEFAULT_AUTH_SERVER);
- m_Address = IniFile.GetValueSet("Authentication", "Address", DEFAULT_AUTH_ADDRESS);
+ m_Server = IniFile.GetValueSet ("Authentication", "Server", DEFAULT_AUTH_SERVER);
+ m_Address = IniFile.GetValueSet ("Authentication", "Address", DEFAULT_AUTH_ADDRESS);
m_ShouldAuthenticate = IniFile.GetValueSetB("Authentication", "Authenticate", true);
}
@@ -193,62 +133,6 @@ void cAuthenticator::Execute(void)
-bool cAuthenticator::SecureGetFromAddress(const AString & a_CACerts, const AString & a_ExpectedPeerName, const AString & a_Data, AString & a_Response)
-{
- // Connect the socket:
- cBlockingSslClientSocket Socket;
- Socket.SetTrustedRootCertsFromString(a_CACerts, a_ExpectedPeerName);
- if (!Socket.Connect(a_ExpectedPeerName, 443))
- {
- LOGWARNING("cAuthenticator: Can't connect to %s: %s", a_ExpectedPeerName.c_str(), Socket.GetLastErrorText().c_str());
- return false;
- }
-
- if (!Socket.Send(a_Data.c_str(), a_Data.size()))
- {
- LOGWARNING("cAuthenticator: Writing SSL data failed: %s", Socket.GetLastErrorText().c_str());
- return false;
- }
-
- // Read the HTTP response:
- int ret;
- unsigned char buf[1024];
-
- for (;;)
- {
- ret = Socket.Receive(buf, sizeof(buf));
-
- if ((ret == POLARSSL_ERR_NET_WANT_READ) || (ret == POLARSSL_ERR_NET_WANT_WRITE))
- {
- // This value should never be returned, it is handled internally by cBlockingSslClientSocket
- LOGWARNING("cAuthenticator: SSL reading failed internally");
- return false;
- }
- if (ret == POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY)
- {
- break;
- }
- if (ret < 0)
- {
- LOGWARNING("cAuthenticator: SSL reading failed: -0x%x", -ret);
- return false;
- }
- if (ret == 0)
- {
- break;
- }
-
- a_Response.append((const char *)buf, (size_t)ret);
- }
-
- Socket.Disconnect();
- return true;
-}
-
-
-
-
-
bool cAuthenticator::AuthWithYggdrasil(AString & a_UserName, const AString & a_ServerId, AString & a_UUID, Json::Value & a_Properties)
{
LOGD("Trying to authenticate user %s", a_UserName.c_str());
@@ -266,7 +150,7 @@ bool cAuthenticator::AuthWithYggdrasil(AString & a_UserName, const AString & a_S
Request += "\r\n";
AString Response;
- if (!SecureGetFromAddress(StarfieldCACert(), m_Server, Request, Response))
+ if (!cMojangAPI::SecureRequest(m_Server, Request, Response))
{
return false;
}
@@ -304,17 +188,11 @@ bool cAuthenticator::AuthWithYggdrasil(AString & a_UserName, const AString & a_S
return false;
}
a_UserName = root.get("name", "Unknown").asString();
- a_UUID = root.get("id", "").asString();
+ a_UUID = cMojangAPI::MakeUUIDShort(root.get("id", "").asString());
a_Properties = root["properties"];
-
- // If the UUID doesn't contain the hashes, insert them at the proper places:
- if (a_UUID.size() == 32)
- {
- a_UUID.insert(8, "-");
- a_UUID.insert(13, "-");
- a_UUID.insert(18, "-");
- a_UUID.insert(23, "-");
- }
+
+ // Store the player's UUID in the NameToUUID map in MojangAPI:
+ cRoot::Get()->GetMojangAPI().AddPlayerNameToUUIDMapping(a_UserName, a_UUID);
return true;
}
diff --git a/src/Protocol/Authenticator.h b/src/Protocol/Authenticator.h
index 244d94c0b..853eff535 100644
--- a/src/Protocol/Authenticator.h
+++ b/src/Protocol/Authenticator.h
@@ -11,8 +11,6 @@
#pragma once
-#ifndef CAUTHENTICATOR_H_INCLUDED
-#define CAUTHENTICATOR_H_INCLUDED
#include "../OSSupport/IsThread.h"
@@ -52,7 +50,7 @@ public:
/** Stops the authenticator thread. The thread may be started and stopped repeatedly */
void Stop(void);
-
+
private:
class cUser
@@ -76,29 +74,26 @@ private:
cUserList m_Queue;
cEvent m_QueueNonempty;
+ /** The server that is to be contacted for auth / UUID conversions */
AString m_Server;
+
+ /** The URL to use for auth, without server part.
+ %USERNAME% will be replaced with actual user name.
+ %SERVERID% will be replaced with server's ID.
+ For example "/session/minecraft/hasJoined?username=%USERNAME%&serverId=%SERVERID%". */
AString m_Address;
+
AString m_PropertiesAddress;
bool m_ShouldAuthenticate;
/** cIsThread override: */
virtual void Execute(void) override;
- /** Connects to a hostname using SSL, sends given data, and sets the response, returning whether all was successful or not */
- bool SecureGetFromAddress(const AString & a_CACerts, const AString & a_ExpectedPeerName, const AString & a_Request, AString & a_Response);
-
/** Returns true if the user authenticated okay, false on error
- Sets the username, UUID, and properties (i.e. skin) fields
- */
+ Returns the case-corrected username, UUID, and properties (eg. skin). */
bool AuthWithYggdrasil(AString & a_UserName, const AString & a_ServerId, AString & a_UUID, Json::Value & a_Properties);
};
-
-#endif // CAUTHENTICATOR_H_INCLUDED
-
-
-
-
diff --git a/src/Protocol/CMakeLists.txt b/src/Protocol/CMakeLists.txt
index ae447ce54..1ba66ff1f 100644
--- a/src/Protocol/CMakeLists.txt
+++ b/src/Protocol/CMakeLists.txt
@@ -7,6 +7,7 @@ include_directories ("${PROJECT_SOURCE_DIR}/../")
SET (SRCS
Authenticator.cpp
ChunkDataSerializer.cpp
+ MojangAPI.cpp
Protocol125.cpp
Protocol132.cpp
Protocol14x.cpp
@@ -18,6 +19,7 @@ SET (SRCS
SET (HDRS
Authenticator.h
ChunkDataSerializer.h
+ MojangAPI.h
Protocol.h
Protocol125.h
Protocol132.h
diff --git a/src/Protocol/MojangAPI.cpp b/src/Protocol/MojangAPI.cpp
new file mode 100644
index 000000000..45baa5a4f
--- /dev/null
+++ b/src/Protocol/MojangAPI.cpp
@@ -0,0 +1,480 @@
+
+// MojangAPI.cpp
+
+// Implements the cMojangAPI class representing the various API points provided by Mojang's webservices, and a cache for their results
+
+#include "Globals.h"
+#include "MojangAPI.h"
+#include "SQLiteCpp/Database.h"
+#include "SQLiteCpp/Statement.h"
+#include "inifile/iniFile.h"
+#include "json/json.h"
+#include "PolarSSL++/BlockingSslClientSocket.h"
+
+
+
+
+
+/** The maximum age for items to be kept in the cache. Any item older than this will be removed. */
+const Int64 MAX_AGE = 7 * 24 * 60 * 60; // 7 days ago
+
+/** The maximum number of names to send in a single query */
+const int MAX_PER_QUERY = 100;
+
+
+
+
+
+#define DEFAULT_NAME_TO_UUID_SERVER "api.mojang.com"
+#define DEFAULT_NAME_TO_UUID_ADDRESS "/profiles/minecraft"
+
+
+
+
+
+
+/** This is the data of the root certs for Starfield Technologies, the CA that signed sessionserver.mojang.com's cert:
+Downloaded from http://certs.starfieldtech.com/repository/ */
+static const AString & StarfieldCACert(void)
+{
+ static const AString Cert(
+ // G2 cert
+ "-----BEGIN CERTIFICATE-----\n"
+ "MIID3TCCAsWgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBjzELMAkGA1UEBhMCVVMx\n"
+ "EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT\n"
+ "HFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAMTKVN0YXJmaWVs\n"
+ "ZCBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAw\n"
+ "MFoXDTM3MTIzMTIzNTk1OVowgY8xCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6\n"
+ "b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFyZmllbGQgVGVj\n"
+ "aG5vbG9naWVzLCBJbmMuMTIwMAYDVQQDEylTdGFyZmllbGQgUm9vdCBDZXJ0aWZp\n"
+ "Y2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n"
+ "ggEBAL3twQP89o/8ArFvW59I2Z154qK3A2FWGMNHttfKPTUuiUP3oWmb3ooa/RMg\n"
+ "nLRJdzIpVv257IzdIvpy3Cdhl+72WoTsbhm5iSzchFvVdPtrX8WJpRBSiUZV9Lh1\n"
+ "HOZ/5FSuS/hVclcCGfgXcVnrHigHdMWdSL5stPSksP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PT7dL5WXXp59fkdheMtlb71cZBDzI0fmgAKhynp\n"
+ "VSJYACPq4xJDKVtHCN2MQWplBqjlIapBtJUhlbl90TSrE9atvNziPTnNvT51cKEY\n"
+ "WQPJIrSPnNVeKtelttQKbfi3QBFGmh95DmK/D5fs4C8fF5Q=\n"
+ "-----END CERTIFICATE-----\n"
+ );
+
+ return Cert;
+}
+
+
+
+
+
+////////////////////////////////////////////////////////////////////////////////
+// cMojangAPI:
+
+cMojangAPI::cMojangAPI(void) :
+ m_NameToUUIDServer(DEFAULT_NAME_TO_UUID_SERVER),
+ m_NameToUUIDAddress(DEFAULT_NAME_TO_UUID_ADDRESS)
+{
+}
+
+
+
+
+
+cMojangAPI::~cMojangAPI()
+{
+ SaveCachesToDisk();
+}
+
+
+
+
+
+void cMojangAPI::Start(cIniFile & a_SettingsIni)
+{
+ m_NameToUUIDServer = a_SettingsIni.GetValueSet("MojangAPI", "NameToUUIDServer", DEFAULT_NAME_TO_UUID_SERVER);
+ m_NameToUUIDAddress = a_SettingsIni.GetValueSet("MojangAPI", "NameToUUIDAddress", DEFAULT_NAME_TO_UUID_ADDRESS);
+ LoadCachesFromDisk();
+}
+
+
+
+
+
+AStringVector cMojangAPI::GetUUIDsFromPlayerNames(const AStringVector & a_PlayerNames, bool a_UseOnlyCached)
+{
+ // Convert all playernames to lowercase:
+ AStringVector PlayerNames;
+ for (AStringVector::const_iterator itr = a_PlayerNames.begin(), end = a_PlayerNames.end(); itr != end; ++itr)
+ {
+ AString Lower(*itr);
+ PlayerNames.push_back(StrToLower(Lower));
+ } // for itr - a_PlayerNames[]
+
+ // Request the cache to populate any names not yet contained:
+ if (!a_UseOnlyCached)
+ {
+ CacheNamesToUUIDs(PlayerNames);
+ }
+
+ // Retrieve from cache:
+ size_t idx = 0;
+ AStringVector res;
+ res.resize(PlayerNames.size());
+ cCSLock Lock(m_CSNameToUUID);
+ for (AStringVector::const_iterator itr = PlayerNames.begin(), end = PlayerNames.end(); itr != end; ++itr, ++idx)
+ {
+ cNameToUUIDMap::const_iterator itrN = m_NameToUUID.find(*itr);
+ if (itrN != m_NameToUUID.end())
+ {
+ res[idx] = itrN->second.m_UUID;
+ }
+ } // for itr - PlayerNames[]
+ return res;
+}
+
+
+
+
+
+void cMojangAPI::AddPlayerNameToUUIDMapping(const AString & a_PlayerName, const AString & a_UUID)
+{
+ AString lcName(a_PlayerName);
+ AString UUID = MakeUUIDShort(a_UUID);
+ Int64 Now = time(NULL);
+ cCSLock Lock(m_CSNameToUUID);
+ m_NameToUUID[StrToLower(lcName)] = sUUIDRecord(a_PlayerName, UUID, Now);
+}
+
+
+
+
+
+bool cMojangAPI::SecureRequest(const AString & a_ServerName, const AString & a_Request, AString & a_Response)
+{
+ // Connect the socket:
+ cBlockingSslClientSocket Socket;
+ Socket.SetTrustedRootCertsFromString(StarfieldCACert(), a_ServerName);
+ if (!Socket.Connect(a_ServerName, 443))
+ {
+ LOGWARNING("%s: Can't connect to %s: %s", __FUNCTION__, a_ServerName.c_str(), Socket.GetLastErrorText().c_str());
+ return false;
+ }
+
+ if (!Socket.Send(a_Request.c_str(), a_Request.size()))
+ {
+ LOGWARNING("%s: Writing SSL data failed: %s", __FUNCTION__, Socket.GetLastErrorText().c_str());
+ return false;
+ }
+
+ // Read the HTTP response:
+ int ret;
+ unsigned char buf[1024];
+
+ for (;;)
+ {
+ ret = Socket.Receive(buf, sizeof(buf));
+
+ if ((ret == POLARSSL_ERR_NET_WANT_READ) || (ret == POLARSSL_ERR_NET_WANT_WRITE))
+ {
+ // This value should never be returned, it is handled internally by cBlockingSslClientSocket
+ LOGWARNING("%s: SSL reading failed internally", __FUNCTION__);
+ return false;
+ }
+ if (ret == POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY)
+ {
+ break;
+ }
+ if (ret < 0)
+ {
+ LOGWARNING("%s: SSL reading failed: -0x%x", __FUNCTION__, -ret);
+ return false;
+ }
+ if (ret == 0)
+ {
+ break;
+ }
+
+ a_Response.append((const char *)buf, (size_t)ret);
+ }
+
+ Socket.Disconnect();
+ return true;
+}
+
+
+
+
+
+AString cMojangAPI::MakeUUIDShort(const AString & a_UUID)
+{
+ // Note: we only check the string's length, not the actual content
+ switch (a_UUID.size())
+ {
+ case 32:
+ {
+ // Already is a short UUID
+ return a_UUID;
+ }
+
+ case 36:
+ {
+ // Remove the dashes from the string:
+ AString res;
+ res.reserve(32);
+ res.append(a_UUID, 0, 8);
+ res.append(a_UUID, 9, 4);
+ res.append(a_UUID, 14, 4);
+ res.append(a_UUID, 19, 4);
+ res.append(a_UUID, 24, 12);
+ return res;
+ }
+ }
+ LOGWARNING("%s: Not an UUID: \"%s\".", __FUNCTION__, a_UUID.c_str());
+ return "";
+}
+
+
+
+
+
+AString cMojangAPI::MakeUUIDDashed(const AString & a_UUID)
+{
+ // Note: we only check the string's length, not the actual content
+ switch (a_UUID.size())
+ {
+ case 36:
+ {
+ // Already is a dashed UUID
+ return a_UUID;
+ }
+
+ case 32:
+ {
+ // Insert dashes at the proper positions:
+ AString res;
+ res.reserve(36);
+ res.append(a_UUID, 0, 8);
+ res.push_back('-');
+ res.append(a_UUID, 8, 4);
+ res.push_back('-');
+ res.append(a_UUID, 12, 4);
+ res.push_back('-');
+ res.append(a_UUID, 16, 4);
+ res.push_back('-');
+ res.append(a_UUID, 20, 12);
+ return res;
+ }
+ }
+ LOGWARNING("%s: Not an UUID: \"%s\".", __FUNCTION__, a_UUID.c_str());
+ return "";
+}
+
+
+
+
+
+void cMojangAPI::LoadCachesFromDisk(void)
+{
+ try
+ {
+ // Open up the SQLite DB:
+ SQLite::Database db("MojangAPI.sqlite", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);
+ db.exec("CREATE TABLE IF NOT EXISTS PlayerNameToUUID (PlayerName, UUID, DateTime)");
+
+ // Clean up old entries:
+ {
+ SQLite::Statement stmt(db, "DELETE FROM PlayerNameToUUID WHERE DateTime < ?");
+ Int64 LimitDateTime = time(NULL) - MAX_AGE;
+ stmt.bind(1, LimitDateTime);
+ stmt.exec();
+ }
+
+ // Retrieve all remaining entries::
+ SQLite::Statement stmt(db, "SELECT PlayerName, UUID, DateTime FROM PlayerNameToUUID");
+ while (stmt.executeStep())
+ {
+ AString PlayerName = stmt.getColumn(0);
+ AString UUID = stmt.getColumn(1);
+ Int64 DateTime = stmt.getColumn(2);
+ AString lcPlayerName = PlayerName;
+ m_NameToUUID[StrToLower(lcPlayerName)] = sUUIDRecord(PlayerName, UUID, DateTime);
+ }
+ }
+ catch (const SQLite::Exception & ex)
+ {
+ LOGINFO("Loading MojangAPI cache failed: %s", ex.what());
+ }
+}
+
+
+
+
+
+void cMojangAPI::SaveCachesToDisk(void)
+{
+ try
+ {
+ // Open up the SQLite DB:
+ SQLite::Database db("MojangAPI.sqlite", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);
+ db.exec("CREATE TABLE IF NOT EXISTS PlayerNameToUUID (PlayerName, UUID, DateTime)");
+
+ // Remove all entries:
+ db.exec("DELETE FROM PlayerNameToUUID");
+
+ // Save all cache entries:
+ SQLite::Statement stmt(db, "INSERT INTO PlayerNameToUUID(PlayerName, UUID, DateTime) VALUES (?, ?, ?)");
+ Int64 LimitDateTime = time(NULL) - MAX_AGE;
+ cCSLock Lock(m_CSNameToUUID);
+ for (cNameToUUIDMap::const_iterator itr = m_NameToUUID.begin(), end = m_NameToUUID.end(); itr != end; ++itr)
+ {
+ if (itr->second.m_DateTime < LimitDateTime)
+ {
+ // This item is too old, do not save
+ continue;
+ }
+ stmt.bind(1, itr->second.m_PlayerName);
+ stmt.bind(2, itr->second.m_UUID);
+ stmt.bind(3, itr->second.m_DateTime);
+ stmt.exec();
+ stmt.reset();
+ }
+ }
+ catch (const SQLite::Exception & ex)
+ {
+ LOGINFO("Saving MojangAPI cache failed: %s", ex.what());
+ }
+}
+
+
+
+
+
+void cMojangAPI::CacheNamesToUUIDs(const AStringVector & a_PlayerNames)
+{
+ // Create a list of names to query, by removing those that are already cached:
+ AStringVector NamesToQuery;
+ NamesToQuery.reserve(a_PlayerNames.size());
+ {
+ cCSLock Lock(m_CSNameToUUID);
+ for (AStringVector::const_iterator itr = a_PlayerNames.begin(), end = a_PlayerNames.end(); itr != end; ++itr)
+ {
+ if (m_NameToUUID.find(*itr) == m_NameToUUID.end())
+ {
+ NamesToQuery.push_back(*itr);
+ }
+ } // for itr - a_PlayerNames[]
+ } // Lock(m_CSNameToUUID)
+
+ while (!NamesToQuery.empty())
+ {
+ // Create the request body - a JSON containing up to MAX_PER_QUERY playernames:
+ Json::Value root;
+ int Count = 0;
+ AStringVector::iterator itr = NamesToQuery.begin(), end = NamesToQuery.end();
+ for (; (itr != end) && (Count < MAX_PER_QUERY); ++itr, ++Count)
+ {
+ Json::Value req(*itr);
+ root.append(req);
+ } // for itr - a_PlayerNames[]
+ NamesToQuery.erase(NamesToQuery.begin(), itr);
+ Json::FastWriter Writer;
+ AString RequestBody = Writer.write(root);
+
+ // Create the HTTP request:
+ AString Request;
+ Request += "POST " + m_NameToUUIDAddress + " HTTP/1.0\r\n"; // We need to use HTTP 1.0 because we don't handle Chunked transfer encoding
+ Request += "Host: " + m_NameToUUIDServer + "\r\n";
+ Request += "User-Agent: MCServer\r\n";
+ Request += "Connection: close\r\n";
+ Request += "Content-Type: application/json\r\n";
+ Request += Printf("Content-Length: %u\r\n", (unsigned)RequestBody.length());
+ Request += "\r\n";
+ Request += RequestBody;
+
+ // Get the response from the server:
+ AString Response;
+ if (!SecureRequest(m_NameToUUIDServer, Request, Response))
+ {
+ continue;
+ }
+
+ // Check the HTTP status line:
+ const AString Prefix("HTTP/1.1 200 OK");
+ AString HexDump;
+ if (Response.compare(0, Prefix.size(), Prefix))
+ {
+ LOGINFO("%s failed: bad HTTP status line received", __FUNCTION__);
+ LOGD("Response: \n%s", CreateHexDump(HexDump, Response.data(), Response.size(), 16).c_str());
+ continue;
+ }
+
+ // Erase the HTTP headers from the response:
+ size_t idxHeadersEnd = Response.find("\r\n\r\n");
+ if (idxHeadersEnd == AString::npos)
+ {
+ LOGINFO("%s failed: bad HTTP response header received", __FUNCTION__);
+ LOGD("Response: \n%s", CreateHexDump(HexDump, Response.data(), Response.size(), 16).c_str());
+ continue;
+ }
+ Response.erase(0, idxHeadersEnd + 4);
+
+ // Parse the returned string into Json:
+ Json::Reader reader;
+ if (!reader.parse(Response, root, false) || !root.isArray())
+ {
+ LOGWARNING("%s failed: Cannot parse received data (NameToUUID) to JSON!", __FUNCTION__);
+ LOGD("Response body:\n%s", CreateHexDump(HexDump, Response.data(), Response.size(), 16).c_str());
+ continue;
+ }
+
+ // Store the returned results into cache:
+ size_t JsonCount = root.size();
+ Int64 Now = time(NULL);
+ cCSLock Lock(m_CSNameToUUID);
+ for (size_t idx = 0; idx < JsonCount; ++idx)
+ {
+ Json::Value & Val = root[idx];
+ AString JsonName = Val.get("name", "").asString();
+ AString JsonUUID = MakeUUIDShort(Val.get("id", "").asString());
+ if (JsonUUID.empty())
+ {
+ continue;
+ }
+ AString lcName = JsonName;
+ m_NameToUUID[StrToLower(lcName)] = sUUIDRecord(JsonName, JsonUUID, Now);
+ } // for idx - root[]
+ } // while (!NamesToQuery.empty())
+}
+
+
+
+
diff --git a/src/Protocol/MojangAPI.h b/src/Protocol/MojangAPI.h
new file mode 100644
index 000000000..ac8995bb5
--- /dev/null
+++ b/src/Protocol/MojangAPI.h
@@ -0,0 +1,117 @@
+
+// MojangAPI.h
+
+// Declares the cMojangAPI class representing the various API points provided by Mojang's webservices, and a cache for their results
+
+
+
+
+
+#pragma once
+
+#include <time.h>
+
+
+
+
+
+// tolua_begin
+class cMojangAPI
+{
+public:
+ // tolua_end
+
+ cMojangAPI(void);
+ ~cMojangAPI();
+
+ /** Initializes the API; reads the settings from the specified ini file.
+ Loads cached results from disk. */
+ void Start(cIniFile & a_SettingsIni);
+
+ /** Connects to the specified server using SSL, sends the given request and receives the response.
+ Checks Mojang certificates using the hard-coded Starfield root CA certificate.
+ Returns true if all was successful, false on failure. */
+ static bool SecureRequest(const AString & a_ServerName, const AString & a_Request, AString & a_Response);
+
+ // tolua_begin
+
+ /** Converts the given UUID to its short form (32 bytes, no dashes).
+ Logs a warning and returns empty string if not a UUID.
+ Note: only checks the string's length, not the actual content. */
+ static AString MakeUUIDShort(const AString & a_UUID);
+
+ /** Converts the given UUID to its dashed form (36 bytes, 4 dashes).
+ Logs a warning and returns empty string if not a UUID.
+ Note: only checks the string's length, not the actual content. */
+ static AString MakeUUIDDashed(const AString & a_UUID);
+
+ // tolua_end
+
+ /** Converts the player names into UUIDs.
+ a_PlayerName[idx] will be converted to UUID and returned as idx-th value
+ The UUID will be empty on error.
+ If a_UseOnlyCached is true, only the cached values are returned.
+ If a_UseOnlyCached is false, the names not found in the cache are looked up online, which is a blocking
+ operation, do not use this in world-tick thread! */
+ AStringVector GetUUIDsFromPlayerNames(const AStringVector & a_PlayerName, bool a_UseOnlyCached = false);
+
+ // tolua_begin
+
+ /** Called by the Authenticator to add a PlayerName -> UUID mapping that it has received from
+ authenticating a user. This adds the cache item and "refreshes" it if existing, adjusting its datetime
+ stamp to now. */
+ void AddPlayerNameToUUIDMapping(const AString & a_PlayerName, const AString & a_UUID);
+
+ // tolua_end
+
+protected:
+ struct sUUIDRecord
+ {
+ AString m_PlayerName; // Case-correct playername
+ AString m_UUID;
+ Int64 m_DateTime; // UNIXtime of the UUID lookup
+
+ sUUIDRecord(void) :
+ m_UUID(),
+ m_DateTime(time(NULL))
+ {
+ }
+
+ sUUIDRecord(const AString & a_PlayerName, const AString & a_UUID, Int64 a_DateTime) :
+ m_PlayerName(a_PlayerName),
+ m_UUID(a_UUID),
+ m_DateTime(a_DateTime)
+ {
+ }
+ };
+ typedef std::map<AString, sUUIDRecord> cNameToUUIDMap; // maps Lowercased PlayerName to sUUIDRecord
+
+ /** The server to connect to when converting player names to UUIDs. For example "api.mojang.com". */
+ AString m_NameToUUIDServer;
+
+ /** The URL to use for converting player names to UUIDs, without server part.
+ For example "/profiles/page/1". */
+ AString m_NameToUUIDAddress;
+
+ /** Cache for the Name-to-UUID lookups. The map key is expected lowercased. Protected by m_CSNameToUUID. */
+ cNameToUUIDMap m_NameToUUID;
+
+ /** Protects m_NameToUUID against simultaneous multi-threaded access. */
+ cCriticalSection m_CSNameToUUID;
+
+
+ /** Loads the caches from a disk storage. */
+ void LoadCachesFromDisk(void);
+
+ /** Saves the caches to a disk storage. */
+ void SaveCachesToDisk(void);
+
+ /** Makes sure all specified names are in the cache. Downloads any missing ones from Mojang API servers.
+ Names that are not valid are not added into the cache.
+ ASSUMEs that a_PlayerNames contains lowercased player names. */
+ void CacheNamesToUUIDs(const AStringVector & a_PlayerNames);
+} ; // tolua_export
+
+
+
+
diff --git a/src/Protocol/Protocol17x.cpp b/src/Protocol/Protocol17x.cpp
index 8e31e211c..f419c01a7 100644
--- a/src/Protocol/Protocol17x.cpp
+++ b/src/Protocol/Protocol17x.cpp
@@ -681,7 +681,7 @@ void cProtocol172::SendLoginSuccess(void)
{
cPacketizer Pkt(*this, 0x02); // Login success packet
- Pkt.WriteString(m_Client->GetUUID());
+ Pkt.WriteString(cMojangAPI::MakeUUIDDashed(m_Client->GetUUID()));
Pkt.WriteString(m_Client->GetUsername());
}
@@ -942,7 +942,7 @@ void cProtocol172::SendPlayerSpawn(const cPlayer & a_Player)
// Called to spawn another player for the client
cPacketizer Pkt(*this, 0x0c); // Spawn Player packet
Pkt.WriteVarInt(a_Player.GetUniqueID());
- Pkt.WriteString(a_Player.GetClientHandle()->GetUUID());
+ Pkt.WriteString(cMojangAPI::MakeUUIDDashed(a_Player.GetClientHandle()->GetUUID()));
Pkt.WriteString(a_Player.GetName());
Pkt.WriteFPInt(a_Player.GetPosX());
Pkt.WriteFPInt(a_Player.GetPosY());
@@ -3029,7 +3029,7 @@ void cProtocol176::SendPlayerSpawn(const cPlayer & a_Player)
// Called to spawn another player for the client
cPacketizer Pkt(*this, 0x0c); // Spawn Player packet
Pkt.WriteVarInt(a_Player.GetUniqueID());
- Pkt.WriteString(a_Player.GetClientHandle()->GetUUID());
+ Pkt.WriteString(cMojangAPI::MakeUUIDDashed(a_Player.GetClientHandle()->GetUUID()));
Pkt.WriteString(a_Player.GetName());
const Json::Value & Properties = m_Client->GetProperties();