serverpackethandler.cpp 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063
  1. /*
  2. Minetest
  3. Copyright (C) 2015 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "chatmessage.h"
  17. #include "server.h"
  18. #include "log.h"
  19. #include "content_sao.h"
  20. #include "emerge.h"
  21. #include "mapblock.h"
  22. #include "nodedef.h"
  23. #include "remoteplayer.h"
  24. #include "rollback_interface.h"
  25. #include "scripting_server.h"
  26. #include "settings.h"
  27. #include "tool.h"
  28. #include "version.h"
  29. #include "network/connection.h"
  30. #include "network/networkprotocol.h"
  31. #include "network/serveropcodes.h"
  32. #include "util/auth.h"
  33. #include "util/base64.h"
  34. #include "util/pointedthing.h"
  35. #include "util/serialize.h"
  36. #include "util/srp.h"
  37. void Server::handleCommand_Deprecated(NetworkPacket* pkt)
  38. {
  39. infostream << "Server: " << toServerCommandTable[pkt->getCommand()].name
  40. << " not supported anymore" << std::endl;
  41. }
  42. void Server::handleCommand_Init(NetworkPacket* pkt)
  43. {
  44. if(pkt->getSize() < 1)
  45. return;
  46. RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);
  47. std::string addr_s;
  48. try {
  49. Address address = getPeerAddress(pkt->getPeerId());
  50. addr_s = address.serializeString();
  51. }
  52. catch (con::PeerNotFoundException &e) {
  53. /*
  54. * no peer for this packet found
  55. * most common reason is peer timeout, e.g. peer didn't
  56. * respond for some time, your server was overloaded or
  57. * things like that.
  58. */
  59. infostream << "Server::ProcessData(): Canceling: peer "
  60. << pkt->getPeerId() << " not found" << std::endl;
  61. return;
  62. }
  63. // If net_proto_version is set, this client has already been handled
  64. if (client->getState() > CS_Created) {
  65. verbosestream << "Server: Ignoring multiple TOSERVER_INITs from "
  66. << addr_s << " (peer_id=" << pkt->getPeerId() << ")" << std::endl;
  67. return;
  68. }
  69. verbosestream << "Server: Got TOSERVER_INIT from " << addr_s << " (peer_id="
  70. << pkt->getPeerId() << ")" << std::endl;
  71. // Do not allow multiple players in simple singleplayer mode.
  72. // This isn't a perfect way to do it, but will suffice for now
  73. if (m_simple_singleplayer_mode && m_clients.getClientIDs().size() > 1) {
  74. infostream << "Server: Not allowing another client (" << addr_s
  75. << ") to connect in simple singleplayer mode" << std::endl;
  76. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SINGLEPLAYER);
  77. return;
  78. }
  79. // First byte after command is maximum supported
  80. // serialization version
  81. u8 client_max;
  82. u16 supp_compr_modes;
  83. u16 min_net_proto_version = 0;
  84. u16 max_net_proto_version;
  85. std::string playerName;
  86. *pkt >> client_max >> supp_compr_modes >> min_net_proto_version
  87. >> max_net_proto_version >> playerName;
  88. u8 our_max = SER_FMT_VER_HIGHEST_READ;
  89. // Use the highest version supported by both
  90. u8 depl_serial_v = std::min(client_max, our_max);
  91. // If it's lower than the lowest supported, give up.
  92. if (depl_serial_v < SER_FMT_VER_LOWEST_READ)
  93. depl_serial_v = SER_FMT_VER_INVALID;
  94. if (depl_serial_v == SER_FMT_VER_INVALID) {
  95. actionstream << "Server: A mismatched client tried to connect from "
  96. << addr_s << std::endl;
  97. infostream<<"Server: Cannot negotiate serialization version with "
  98. << addr_s << std::endl;
  99. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_VERSION);
  100. return;
  101. }
  102. client->setPendingSerializationVersion(depl_serial_v);
  103. /*
  104. Read and check network protocol version
  105. */
  106. u16 net_proto_version = 0;
  107. // Figure out a working version if it is possible at all
  108. if (max_net_proto_version >= SERVER_PROTOCOL_VERSION_MIN ||
  109. min_net_proto_version <= SERVER_PROTOCOL_VERSION_MAX) {
  110. // If maximum is larger than our maximum, go with our maximum
  111. if (max_net_proto_version > SERVER_PROTOCOL_VERSION_MAX)
  112. net_proto_version = SERVER_PROTOCOL_VERSION_MAX;
  113. // Else go with client's maximum
  114. else
  115. net_proto_version = max_net_proto_version;
  116. }
  117. verbosestream << "Server: " << addr_s << ": Protocol version: min: "
  118. << min_net_proto_version << ", max: " << max_net_proto_version
  119. << ", chosen: " << net_proto_version << std::endl;
  120. client->net_proto_version = net_proto_version;
  121. // On this handler at least protocol version 25 is required
  122. if (net_proto_version < 25 ||
  123. net_proto_version < SERVER_PROTOCOL_VERSION_MIN ||
  124. net_proto_version > SERVER_PROTOCOL_VERSION_MAX) {
  125. actionstream << "Server: A mismatched client tried to connect from "
  126. << addr_s << std::endl;
  127. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_VERSION);
  128. return;
  129. }
  130. if (g_settings->getBool("strict_protocol_version_checking")) {
  131. if (net_proto_version != LATEST_PROTOCOL_VERSION) {
  132. actionstream << "Server: A mismatched (strict) client tried to "
  133. << "connect from " << addr_s << std::endl;
  134. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_VERSION);
  135. return;
  136. }
  137. }
  138. /*
  139. Validate player name
  140. */
  141. const char* playername = playerName.c_str();
  142. size_t pns = playerName.size();
  143. if (pns == 0 || pns > PLAYERNAME_SIZE) {
  144. actionstream << "Server: Player with "
  145. << ((pns > PLAYERNAME_SIZE) ? "a too long" : "an empty")
  146. << " name tried to connect from " << addr_s << std::endl;
  147. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_NAME);
  148. return;
  149. }
  150. if (!string_allowed(playerName, PLAYERNAME_ALLOWED_CHARS)) {
  151. actionstream << "Server: Player with an invalid name "
  152. << "tried to connect from " << addr_s << std::endl;
  153. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_CHARS_IN_NAME);
  154. return;
  155. }
  156. m_clients.setPlayerName(pkt->getPeerId(), playername);
  157. //TODO (later) case insensitivity
  158. std::string legacyPlayerNameCasing = playerName;
  159. if (!isSingleplayer() && strcasecmp(playername, "singleplayer") == 0) {
  160. actionstream << "Server: Player with the name \"singleplayer\" "
  161. << "tried to connect from " << addr_s << std::endl;
  162. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_NAME);
  163. return;
  164. }
  165. {
  166. std::string reason;
  167. if (m_script->on_prejoinplayer(playername, addr_s, &reason)) {
  168. actionstream << "Server: Player with the name \"" << playerName << "\" "
  169. << "tried to connect from " << addr_s << " "
  170. << "but it was disallowed for the following reason: "
  171. << reason << std::endl;
  172. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_CUSTOM_STRING, reason);
  173. return;
  174. }
  175. }
  176. infostream << "Server: New connection: \"" << playerName << "\" from "
  177. << addr_s << " (peer_id=" << pkt->getPeerId() << ")" << std::endl;
  178. // Enforce user limit.
  179. // Don't enforce for users that have some admin right
  180. if (m_clients.isUserLimitReached() &&
  181. !checkPriv(playername, "server") &&
  182. !checkPriv(playername, "ban") &&
  183. !checkPriv(playername, "privs") &&
  184. !checkPriv(playername, "password") &&
  185. playername != g_settings->get("name")) {
  186. actionstream << "Server: " << playername << " tried to join from "
  187. << addr_s << ", but there" << " are already max_users="
  188. << g_settings->getU16("max_users") << " players." << std::endl;
  189. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_TOO_MANY_USERS);
  190. return;
  191. }
  192. /*
  193. Compose auth methods for answer
  194. */
  195. std::string encpwd; // encrypted Password field for the user
  196. bool has_auth = m_script->getAuth(playername, &encpwd, NULL);
  197. u32 auth_mechs = 0;
  198. client->chosen_mech = AUTH_MECHANISM_NONE;
  199. if (has_auth) {
  200. std::vector<std::string> pwd_components = str_split(encpwd, '#');
  201. if (pwd_components.size() == 4) {
  202. if (pwd_components[1] == "1") { // 1 means srp
  203. auth_mechs |= AUTH_MECHANISM_SRP;
  204. client->enc_pwd = encpwd;
  205. } else {
  206. actionstream << "User " << playername
  207. << " tried to log in, but password field"
  208. << " was invalid (unknown mechcode)." << std::endl;
  209. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
  210. return;
  211. }
  212. } else if (base64_is_valid(encpwd)) {
  213. auth_mechs |= AUTH_MECHANISM_LEGACY_PASSWORD;
  214. client->enc_pwd = encpwd;
  215. } else {
  216. actionstream << "User " << playername
  217. << " tried to log in, but password field"
  218. << " was invalid (invalid base64)." << std::endl;
  219. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
  220. return;
  221. }
  222. } else {
  223. std::string default_password = g_settings->get("default_password");
  224. if (default_password.length() == 0) {
  225. auth_mechs |= AUTH_MECHANISM_FIRST_SRP;
  226. } else {
  227. // Take care of default passwords.
  228. client->enc_pwd = get_encoded_srp_verifier(playerName, default_password);
  229. auth_mechs |= AUTH_MECHANISM_SRP;
  230. // Allocate player in db, but only on successful login.
  231. client->create_player_on_auth_success = true;
  232. }
  233. }
  234. /*
  235. Answer with a TOCLIENT_HELLO
  236. */
  237. verbosestream << "Sending TOCLIENT_HELLO with auth method field: "
  238. << auth_mechs << std::endl;
  239. NetworkPacket resp_pkt(TOCLIENT_HELLO, 1 + 4
  240. + legacyPlayerNameCasing.size(), pkt->getPeerId());
  241. u16 depl_compress_mode = NETPROTO_COMPRESSION_NONE;
  242. resp_pkt << depl_serial_v << depl_compress_mode << net_proto_version
  243. << auth_mechs << legacyPlayerNameCasing;
  244. Send(&resp_pkt);
  245. client->allowed_auth_mechs = auth_mechs;
  246. client->setDeployedCompressionMode(depl_compress_mode);
  247. m_clients.event(pkt->getPeerId(), CSE_Hello);
  248. }
  249. void Server::handleCommand_Init_Legacy(NetworkPacket* pkt)
  250. {
  251. // [0] u8 SER_FMT_VER_HIGHEST_READ
  252. // [1] u8[20] player_name
  253. // [21] u8[28] password <--- can be sent without this, from old versions
  254. if (pkt->getSize() < 1+PLAYERNAME_SIZE)
  255. return;
  256. RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);
  257. std::string addr_s;
  258. try {
  259. Address address = getPeerAddress(pkt->getPeerId());
  260. addr_s = address.serializeString();
  261. }
  262. catch (con::PeerNotFoundException &e) {
  263. /*
  264. * no peer for this packet found
  265. * most common reason is peer timeout, e.g. peer didn't
  266. * respond for some time, your server was overloaded or
  267. * things like that.
  268. */
  269. infostream << "Server::ProcessData(): Canceling: peer "
  270. << pkt->getPeerId() << " not found" << std::endl;
  271. return;
  272. }
  273. // If net_proto_version is set, this client has already been handled
  274. if (client->getState() > CS_Created) {
  275. verbosestream << "Server: Ignoring multiple TOSERVER_INITs from "
  276. << addr_s << " (peer_id=" << pkt->getPeerId() << ")" << std::endl;
  277. return;
  278. }
  279. verbosestream << "Server: Got TOSERVER_INIT_LEGACY from " << addr_s << " (peer_id="
  280. << pkt->getPeerId() << ")" << std::endl;
  281. // Do not allow multiple players in simple singleplayer mode.
  282. // This isn't a perfect way to do it, but will suffice for now
  283. if (m_simple_singleplayer_mode && m_clients.getClientIDs().size() > 1) {
  284. infostream << "Server: Not allowing another client (" << addr_s
  285. << ") to connect in simple singleplayer mode" << std::endl;
  286. DenyAccess_Legacy(pkt->getPeerId(), L"Running in simple singleplayer mode.");
  287. return;
  288. }
  289. // First byte after command is maximum supported
  290. // serialization version
  291. u8 client_max;
  292. *pkt >> client_max;
  293. u8 our_max = SER_FMT_VER_HIGHEST_READ;
  294. // Use the highest version supported by both
  295. int deployed = std::min(client_max, our_max);
  296. // If it's lower than the lowest supported, give up.
  297. if (deployed < SER_FMT_VER_LOWEST_READ)
  298. deployed = SER_FMT_VER_INVALID;
  299. if (deployed == SER_FMT_VER_INVALID) {
  300. actionstream << "Server: A mismatched client tried to connect from "
  301. << addr_s << std::endl;
  302. infostream<<"Server: Cannot negotiate serialization version with "
  303. << addr_s << std::endl;
  304. DenyAccess_Legacy(pkt->getPeerId(), std::wstring(
  305. L"Your client's version is not supported.\n"
  306. L"Server version is ")
  307. + utf8_to_wide(g_version_string) + L"."
  308. );
  309. return;
  310. }
  311. client->setPendingSerializationVersion(deployed);
  312. /*
  313. Read and check network protocol version
  314. */
  315. u16 min_net_proto_version = 0;
  316. if (pkt->getSize() >= 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2)
  317. min_net_proto_version = pkt->getU16(1 + PLAYERNAME_SIZE + PASSWORD_SIZE);
  318. // Use same version as minimum and maximum if maximum version field
  319. // doesn't exist (backwards compatibility)
  320. u16 max_net_proto_version = min_net_proto_version;
  321. if (pkt->getSize() >= 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2)
  322. max_net_proto_version = pkt->getU16(1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2);
  323. // Start with client's maximum version
  324. u16 net_proto_version = max_net_proto_version;
  325. // Figure out a working version if it is possible at all
  326. if (max_net_proto_version >= SERVER_PROTOCOL_VERSION_MIN ||
  327. min_net_proto_version <= SERVER_PROTOCOL_VERSION_MAX) {
  328. // If maximum is larger than our maximum, go with our maximum
  329. if (max_net_proto_version > SERVER_PROTOCOL_VERSION_MAX)
  330. net_proto_version = SERVER_PROTOCOL_VERSION_MAX;
  331. // Else go with client's maximum
  332. else
  333. net_proto_version = max_net_proto_version;
  334. }
  335. // The client will send up to date init packet, ignore this one
  336. if (net_proto_version >= 25)
  337. return;
  338. verbosestream << "Server: " << addr_s << ": Protocol version: min: "
  339. << min_net_proto_version << ", max: " << max_net_proto_version
  340. << ", chosen: " << net_proto_version << std::endl;
  341. client->net_proto_version = net_proto_version;
  342. if (net_proto_version < SERVER_PROTOCOL_VERSION_MIN ||
  343. net_proto_version > SERVER_PROTOCOL_VERSION_MAX) {
  344. actionstream << "Server: A mismatched client tried to connect from "
  345. << addr_s << std::endl;
  346. DenyAccess_Legacy(pkt->getPeerId(), std::wstring(
  347. L"Your client's version is not supported.\n"
  348. L"Server version is ")
  349. + utf8_to_wide(g_version_string) + L",\n"
  350. + L"server's PROTOCOL_VERSION is "
  351. + utf8_to_wide(itos(SERVER_PROTOCOL_VERSION_MIN))
  352. + L"..."
  353. + utf8_to_wide(itos(SERVER_PROTOCOL_VERSION_MAX))
  354. + L", client's PROTOCOL_VERSION is "
  355. + utf8_to_wide(itos(min_net_proto_version))
  356. + L"..."
  357. + utf8_to_wide(itos(max_net_proto_version))
  358. );
  359. return;
  360. }
  361. if (g_settings->getBool("strict_protocol_version_checking")) {
  362. if (net_proto_version != LATEST_PROTOCOL_VERSION) {
  363. actionstream << "Server: A mismatched (strict) client tried to "
  364. << "connect from " << addr_s << std::endl;
  365. DenyAccess_Legacy(pkt->getPeerId(), std::wstring(
  366. L"Your client's version is not supported.\n"
  367. L"Server version is ")
  368. + utf8_to_wide(g_version_string) + L",\n"
  369. + L"server's PROTOCOL_VERSION (strict) is "
  370. + utf8_to_wide(itos(LATEST_PROTOCOL_VERSION))
  371. + L", client's PROTOCOL_VERSION is "
  372. + utf8_to_wide(itos(min_net_proto_version))
  373. + L"..."
  374. + utf8_to_wide(itos(max_net_proto_version))
  375. );
  376. return;
  377. }
  378. }
  379. /*
  380. Set up player
  381. */
  382. char playername[PLAYERNAME_SIZE];
  383. unsigned int playername_length = 0;
  384. for (; playername_length < PLAYERNAME_SIZE; playername_length++ ) {
  385. playername[playername_length] = pkt->getChar(1+playername_length);
  386. if (pkt->getChar(1+playername_length) == 0)
  387. break;
  388. }
  389. if (playername_length == PLAYERNAME_SIZE) {
  390. actionstream << "Server: Player with name exceeding max length "
  391. << "tried to connect from " << addr_s << std::endl;
  392. DenyAccess_Legacy(pkt->getPeerId(), L"Name too long");
  393. return;
  394. }
  395. if (playername[0]=='\0') {
  396. actionstream << "Server: Player with an empty name "
  397. << "tried to connect from " << addr_s << std::endl;
  398. DenyAccess_Legacy(pkt->getPeerId(), L"Empty name");
  399. return;
  400. }
  401. if (!string_allowed(playername, PLAYERNAME_ALLOWED_CHARS)) {
  402. actionstream << "Server: Player with an invalid name "
  403. << "tried to connect from " << addr_s << std::endl;
  404. DenyAccess_Legacy(pkt->getPeerId(), L"Name contains unallowed characters");
  405. return;
  406. }
  407. if (!isSingleplayer() && strcasecmp(playername, "singleplayer") == 0) {
  408. actionstream << "Server: Player with the name \"singleplayer\" "
  409. << "tried to connect from " << addr_s << std::endl;
  410. DenyAccess_Legacy(pkt->getPeerId(), L"Name is not allowed");
  411. return;
  412. }
  413. {
  414. std::string reason;
  415. if (m_script->on_prejoinplayer(playername, addr_s, &reason)) {
  416. actionstream << "Server: Player with the name \"" << playername << "\" "
  417. << "tried to connect from " << addr_s << " "
  418. << "but it was disallowed for the following reason: "
  419. << reason << std::endl;
  420. DenyAccess_Legacy(pkt->getPeerId(), utf8_to_wide(reason));
  421. return;
  422. }
  423. }
  424. infostream<<"Server: New connection: \""<<playername<<"\" from "
  425. <<addr_s<<" (peer_id="<<pkt->getPeerId()<<")"<<std::endl;
  426. // Get password
  427. char given_password[PASSWORD_SIZE];
  428. if (pkt->getSize() < 1 + PLAYERNAME_SIZE + PASSWORD_SIZE) {
  429. // old version - assume blank password
  430. given_password[0] = 0;
  431. }
  432. else {
  433. for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
  434. given_password[i] = pkt->getChar(21 + i);
  435. }
  436. given_password[PASSWORD_SIZE - 1] = 0;
  437. }
  438. if (!base64_is_valid(given_password)) {
  439. actionstream << "Server: " << playername
  440. << " supplied invalid password hash" << std::endl;
  441. DenyAccess_Legacy(pkt->getPeerId(), L"Invalid password hash");
  442. return;
  443. }
  444. // Enforce user limit.
  445. // Don't enforce for users that have some admin right
  446. if (m_clients.isUserLimitReached() &&
  447. !checkPriv(playername, "server") &&
  448. !checkPriv(playername, "ban") &&
  449. !checkPriv(playername, "privs") &&
  450. !checkPriv(playername, "password") &&
  451. playername != g_settings->get("name")) {
  452. actionstream << "Server: " << playername << " tried to join, but there"
  453. << " are already max_users="
  454. << g_settings->getU16("max_users") << " players." << std::endl;
  455. DenyAccess_Legacy(pkt->getPeerId(), L"Too many users.");
  456. return;
  457. }
  458. std::string checkpwd; // Password hash to check against
  459. bool has_auth = m_script->getAuth(playername, &checkpwd, NULL);
  460. // If no authentication info exists for user, create it
  461. if (!has_auth) {
  462. if (!isSingleplayer() &&
  463. g_settings->getBool("disallow_empty_password") &&
  464. std::string(given_password).empty()) {
  465. actionstream << "Server: " << playername
  466. << " supplied empty password" << std::endl;
  467. DenyAccess_Legacy(pkt->getPeerId(), L"Empty passwords are "
  468. L"disallowed. Set a password and try again.");
  469. return;
  470. }
  471. std::string raw_default_password =
  472. g_settings->get("default_password");
  473. std::string initial_password =
  474. translate_password(playername, raw_default_password);
  475. // If default_password is empty, allow any initial password
  476. if (raw_default_password.length() == 0)
  477. initial_password = given_password;
  478. m_script->createAuth(playername, initial_password);
  479. }
  480. has_auth = m_script->getAuth(playername, &checkpwd, NULL);
  481. if (!has_auth) {
  482. actionstream << "Server: " << playername << " cannot be authenticated"
  483. << " (auth handler does not work?)" << std::endl;
  484. DenyAccess_Legacy(pkt->getPeerId(), L"Not allowed to login");
  485. return;
  486. }
  487. if (given_password != checkpwd) {
  488. actionstream << "Server: User " << playername
  489. << " at " << addr_s
  490. << " supplied wrong password (auth mechanism: legacy)."
  491. << std::endl;
  492. DenyAccess_Legacy(pkt->getPeerId(), L"Wrong password");
  493. return;
  494. }
  495. RemotePlayer *player =
  496. static_cast<RemotePlayer*>(m_env->getPlayer(playername));
  497. if (player && player->peer_id != 0) {
  498. actionstream << "Server: " << playername << ": Failed to emerge player"
  499. << " (player allocated to an another client)" << std::endl;
  500. DenyAccess_Legacy(pkt->getPeerId(), L"Another client is connected with this "
  501. L"name. If your client closed unexpectedly, try again in "
  502. L"a minute.");
  503. }
  504. m_clients.setPlayerName(pkt->getPeerId(), playername);
  505. /*
  506. Answer with a TOCLIENT_INIT
  507. */
  508. NetworkPacket resp_pkt(TOCLIENT_INIT_LEGACY, 1 + 6 + 8 + 4,
  509. pkt->getPeerId());
  510. resp_pkt << (u8) deployed << (v3s16) floatToInt(v3f(0,0,0), BS)
  511. << (u64) m_env->getServerMap().getSeed()
  512. << g_settings->getFloat("dedicated_server_step");
  513. Send(&resp_pkt);
  514. m_clients.event(pkt->getPeerId(), CSE_InitLegacy);
  515. }
  516. void Server::handleCommand_Init2(NetworkPacket* pkt)
  517. {
  518. verbosestream << "Server: Got TOSERVER_INIT2 from "
  519. << pkt->getPeerId() << std::endl;
  520. m_clients.event(pkt->getPeerId(), CSE_GotInit2);
  521. u16 protocol_version = m_clients.getProtocolVersion(pkt->getPeerId());
  522. /*
  523. Send some initialization data
  524. */
  525. infostream << "Server: Sending content to "
  526. << getPlayerName(pkt->getPeerId()) << std::endl;
  527. // Send player movement settings
  528. SendMovement(pkt->getPeerId());
  529. // Send item definitions
  530. SendItemDef(pkt->getPeerId(), m_itemdef, protocol_version);
  531. // Send node definitions
  532. SendNodeDef(pkt->getPeerId(), m_nodedef, protocol_version);
  533. m_clients.event(pkt->getPeerId(), CSE_SetDefinitionsSent);
  534. // Send media announcement
  535. sendMediaAnnouncement(pkt->getPeerId());
  536. // Send detached inventories
  537. sendDetachedInventories(pkt->getPeerId());
  538. // Send time of day
  539. u16 time = m_env->getTimeOfDay();
  540. float time_speed = g_settings->getFloat("time_speed");
  541. SendTimeOfDay(pkt->getPeerId(), time, time_speed);
  542. SendCSMFlavourLimits(pkt->getPeerId());
  543. // Warnings about protocol version can be issued here
  544. if (getClient(pkt->getPeerId())->net_proto_version < LATEST_PROTOCOL_VERSION) {
  545. SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
  546. L"# Server: WARNING: YOUR CLIENT'S VERSION MAY NOT BE FULLY COMPATIBLE "
  547. L"WITH THIS SERVER!"));
  548. }
  549. }
  550. void Server::handleCommand_RequestMedia(NetworkPacket* pkt)
  551. {
  552. std::vector<std::string> tosend;
  553. u16 numfiles;
  554. *pkt >> numfiles;
  555. infostream << "Sending " << numfiles << " files to "
  556. << getPlayerName(pkt->getPeerId()) << std::endl;
  557. verbosestream << "TOSERVER_REQUEST_MEDIA: " << std::endl;
  558. for (u16 i = 0; i < numfiles; i++) {
  559. std::string name;
  560. *pkt >> name;
  561. tosend.push_back(name);
  562. verbosestream << "TOSERVER_REQUEST_MEDIA: requested file "
  563. << name << std::endl;
  564. }
  565. sendRequestedMedia(pkt->getPeerId(), tosend);
  566. }
  567. void Server::handleCommand_ClientReady(NetworkPacket* pkt)
  568. {
  569. u16 peer_id = pkt->getPeerId();
  570. PlayerSAO* playersao = StageTwoClientInit(peer_id);
  571. if (playersao == NULL) {
  572. actionstream
  573. << "TOSERVER_CLIENT_READY stage 2 client init failed for peer_id: "
  574. << peer_id << std::endl;
  575. m_con->DisconnectPeer(peer_id);
  576. return;
  577. }
  578. if (pkt->getSize() < 8) {
  579. errorstream
  580. << "TOSERVER_CLIENT_READY client sent inconsistent data, disconnecting peer_id: "
  581. << peer_id << std::endl;
  582. m_con->DisconnectPeer(peer_id);
  583. return;
  584. }
  585. u8 major_ver, minor_ver, patch_ver, reserved;
  586. std::string full_ver;
  587. *pkt >> major_ver >> minor_ver >> patch_ver >> reserved >> full_ver;
  588. m_clients.setClientVersion(
  589. peer_id, major_ver, minor_ver, patch_ver,
  590. full_ver);
  591. const std::vector<std::string> &players = m_clients.getPlayerNames();
  592. NetworkPacket list_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, peer_id);
  593. list_pkt << (u8) PLAYER_LIST_INIT << (u16) players.size();
  594. for (const std::string &player: players) {
  595. list_pkt << player;
  596. }
  597. m_clients.send(peer_id, 0, &list_pkt, true);
  598. NetworkPacket notice_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, PEER_ID_INEXISTENT);
  599. // (u16) 1 + std::string represents a pseudo vector serialization representation
  600. notice_pkt << (u8) PLAYER_LIST_ADD << (u16) 1 << std::string(playersao->getPlayer()->getName());
  601. m_clients.sendToAll(&notice_pkt);
  602. m_clients.event(peer_id, CSE_SetClientReady);
  603. m_script->on_joinplayer(playersao);
  604. // Send shutdown timer if shutdown has been scheduled
  605. if (m_shutdown_timer > 0.0f) {
  606. std::wstringstream ws;
  607. ws << L"*** Server shutting down in "
  608. << duration_to_string(myround(m_shutdown_timer)).c_str() << ".";
  609. SendChatMessage(pkt->getPeerId(), ws.str());
  610. }
  611. }
  612. void Server::handleCommand_GotBlocks(NetworkPacket* pkt)
  613. {
  614. if (pkt->getSize() < 1)
  615. return;
  616. /*
  617. [0] u16 command
  618. [2] u8 count
  619. [3] v3s16 pos_0
  620. [3+6] v3s16 pos_1
  621. ...
  622. */
  623. u8 count;
  624. *pkt >> count;
  625. RemoteClient *client = getClient(pkt->getPeerId());
  626. if ((s16)pkt->getSize() < 1 + (int)count * 6) {
  627. throw con::InvalidIncomingDataException
  628. ("GOTBLOCKS length is too short");
  629. }
  630. for (u16 i = 0; i < count; i++) {
  631. v3s16 p;
  632. *pkt >> p;
  633. client->GotBlock(p);
  634. }
  635. }
  636. void Server::process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao,
  637. NetworkPacket *pkt)
  638. {
  639. if (pkt->getRemainingBytes() < 12 + 12 + 4 + 4)
  640. return;
  641. v3s32 ps, ss;
  642. s32 f32pitch, f32yaw;
  643. u8 f32fov;
  644. *pkt >> ps;
  645. *pkt >> ss;
  646. *pkt >> f32pitch;
  647. *pkt >> f32yaw;
  648. f32 pitch = (f32)f32pitch / 100.0;
  649. f32 yaw = (f32)f32yaw / 100.0;
  650. u32 keyPressed = 0;
  651. // default behavior (in case an old client doesn't send these)
  652. f32 fov = 0;
  653. u8 wanted_range = 0;
  654. if (pkt->getRemainingBytes() >= 4)
  655. *pkt >> keyPressed;
  656. if (pkt->getRemainingBytes() >= 1) {
  657. *pkt >> f32fov;
  658. fov = (f32)f32fov / 80.0;
  659. }
  660. if (pkt->getRemainingBytes() >= 1)
  661. *pkt >> wanted_range;
  662. v3f position((f32)ps.X / 100.0, (f32)ps.Y / 100.0, (f32)ps.Z / 100.0);
  663. v3f speed((f32)ss.X / 100.0, (f32)ss.Y / 100.0, (f32)ss.Z / 100.0);
  664. pitch = modulo360f(pitch);
  665. yaw = wrapDegrees_0_360(yaw);
  666. playersao->setBasePosition(position);
  667. player->setSpeed(speed);
  668. playersao->setPitch(pitch);
  669. playersao->setYaw(yaw);
  670. playersao->setFov(fov);
  671. playersao->setWantedRange(wanted_range);
  672. player->keyPressed = keyPressed;
  673. player->control.up = (keyPressed & 1);
  674. player->control.down = (keyPressed & 2);
  675. player->control.left = (keyPressed & 4);
  676. player->control.right = (keyPressed & 8);
  677. player->control.jump = (keyPressed & 16);
  678. player->control.aux1 = (keyPressed & 32);
  679. player->control.sneak = (keyPressed & 64);
  680. player->control.LMB = (keyPressed & 128);
  681. player->control.RMB = (keyPressed & 256);
  682. if (playersao->checkMovementCheat()) {
  683. // Call callbacks
  684. m_script->on_cheat(playersao, "moved_too_fast");
  685. SendMovePlayer(pkt->getPeerId());
  686. }
  687. }
  688. void Server::handleCommand_PlayerPos(NetworkPacket* pkt)
  689. {
  690. RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
  691. if (player == NULL) {
  692. errorstream << "Server::ProcessData(): Canceling: "
  693. "No player for peer_id=" << pkt->getPeerId()
  694. << " disconnecting peer!" << std::endl;
  695. m_con->DisconnectPeer(pkt->getPeerId());
  696. return;
  697. }
  698. PlayerSAO *playersao = player->getPlayerSAO();
  699. if (playersao == NULL) {
  700. errorstream << "Server::ProcessData(): Canceling: "
  701. "No player object for peer_id=" << pkt->getPeerId()
  702. << " disconnecting peer!" << std::endl;
  703. m_con->DisconnectPeer(pkt->getPeerId());
  704. return;
  705. }
  706. // If player is dead we don't care of this packet
  707. if (playersao->isDead()) {
  708. verbosestream << "TOSERVER_PLAYERPOS: " << player->getName()
  709. << " is dead. Ignoring packet";
  710. return;
  711. }
  712. process_PlayerPos(player, playersao, pkt);
  713. }
  714. void Server::handleCommand_DeletedBlocks(NetworkPacket* pkt)
  715. {
  716. if (pkt->getSize() < 1)
  717. return;
  718. /*
  719. [0] u16 command
  720. [2] u8 count
  721. [3] v3s16 pos_0
  722. [3+6] v3s16 pos_1
  723. ...
  724. */
  725. u8 count;
  726. *pkt >> count;
  727. RemoteClient *client = getClient(pkt->getPeerId());
  728. if ((s16)pkt->getSize() < 1 + (int)count * 6) {
  729. throw con::InvalidIncomingDataException
  730. ("DELETEDBLOCKS length is too short");
  731. }
  732. for (u16 i = 0; i < count; i++) {
  733. v3s16 p;
  734. *pkt >> p;
  735. client->SetBlockNotSent(p);
  736. }
  737. }
  738. void Server::handleCommand_InventoryAction(NetworkPacket* pkt)
  739. {
  740. RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
  741. if (player == NULL) {
  742. errorstream << "Server::ProcessData(): Canceling: "
  743. "No player for peer_id=" << pkt->getPeerId()
  744. << " disconnecting peer!" << std::endl;
  745. m_con->DisconnectPeer(pkt->getPeerId());
  746. return;
  747. }
  748. PlayerSAO *playersao = player->getPlayerSAO();
  749. if (playersao == NULL) {
  750. errorstream << "Server::ProcessData(): Canceling: "
  751. "No player object for peer_id=" << pkt->getPeerId()
  752. << " disconnecting peer!" << std::endl;
  753. m_con->DisconnectPeer(pkt->getPeerId());
  754. return;
  755. }
  756. // Strip command and create a stream
  757. std::string datastring(pkt->getString(0), pkt->getSize());
  758. verbosestream << "TOSERVER_INVENTORY_ACTION: data=" << datastring
  759. << std::endl;
  760. std::istringstream is(datastring, std::ios_base::binary);
  761. // Create an action
  762. InventoryAction *a = InventoryAction::deSerialize(is);
  763. if (!a) {
  764. infostream << "TOSERVER_INVENTORY_ACTION: "
  765. << "InventoryAction::deSerialize() returned NULL"
  766. << std::endl;
  767. return;
  768. }
  769. // If something goes wrong, this player is to blame
  770. RollbackScopeActor rollback_scope(m_rollback,
  771. std::string("player:")+player->getName());
  772. /*
  773. Note: Always set inventory not sent, to repair cases
  774. where the client made a bad prediction.
  775. */
  776. /*
  777. Handle restrictions and special cases of the move action
  778. */
  779. if (a->getType() == IAction::Move) {
  780. IMoveAction *ma = (IMoveAction*)a;
  781. ma->from_inv.applyCurrentPlayer(player->getName());
  782. ma->to_inv.applyCurrentPlayer(player->getName());
  783. setInventoryModified(ma->from_inv, false);
  784. setInventoryModified(ma->to_inv, false);
  785. bool from_inv_is_current_player =
  786. (ma->from_inv.type == InventoryLocation::PLAYER) &&
  787. (ma->from_inv.name == player->getName());
  788. bool to_inv_is_current_player =
  789. (ma->to_inv.type == InventoryLocation::PLAYER) &&
  790. (ma->to_inv.name == player->getName());
  791. /*
  792. Disable moving items out of craftpreview
  793. */
  794. if (ma->from_list == "craftpreview") {
  795. infostream << "Ignoring IMoveAction from "
  796. << (ma->from_inv.dump()) << ":" << ma->from_list
  797. << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
  798. << " because src is " << ma->from_list << std::endl;
  799. delete a;
  800. return;
  801. }
  802. /*
  803. Disable moving items into craftresult and craftpreview
  804. */
  805. if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") {
  806. infostream << "Ignoring IMoveAction from "
  807. << (ma->from_inv.dump()) << ":" << ma->from_list
  808. << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
  809. << " because dst is " << ma->to_list << std::endl;
  810. delete a;
  811. return;
  812. }
  813. // Disallow moving items in elsewhere than player's inventory
  814. // if not allowed to interact
  815. if (!checkPriv(player->getName(), "interact") &&
  816. (!from_inv_is_current_player ||
  817. !to_inv_is_current_player)) {
  818. infostream << "Cannot move outside of player's inventory: "
  819. << "No interact privilege" << std::endl;
  820. delete a;
  821. return;
  822. }
  823. }
  824. /*
  825. Handle restrictions and special cases of the drop action
  826. */
  827. else if (a->getType() == IAction::Drop) {
  828. IDropAction *da = (IDropAction*)a;
  829. da->from_inv.applyCurrentPlayer(player->getName());
  830. setInventoryModified(da->from_inv, false);
  831. /*
  832. Disable dropping items out of craftpreview
  833. */
  834. if (da->from_list == "craftpreview") {
  835. infostream << "Ignoring IDropAction from "
  836. << (da->from_inv.dump()) << ":" << da->from_list
  837. << " because src is " << da->from_list << std::endl;
  838. delete a;
  839. return;
  840. }
  841. // Disallow dropping items if not allowed to interact
  842. if (!checkPriv(player->getName(), "interact")) {
  843. delete a;
  844. return;
  845. }
  846. // Disallow dropping items if dead
  847. if (playersao->isDead()) {
  848. infostream << "Ignoring IDropAction from "
  849. << (da->from_inv.dump()) << ":" << da->from_list
  850. << " because player is dead." << std::endl;
  851. delete a;
  852. return;
  853. }
  854. }
  855. /*
  856. Handle restrictions and special cases of the craft action
  857. */
  858. else if (a->getType() == IAction::Craft) {
  859. ICraftAction *ca = (ICraftAction*)a;
  860. ca->craft_inv.applyCurrentPlayer(player->getName());
  861. setInventoryModified(ca->craft_inv, false);
  862. //bool craft_inv_is_current_player =
  863. // (ca->craft_inv.type == InventoryLocation::PLAYER) &&
  864. // (ca->craft_inv.name == player->getName());
  865. // Disallow crafting if not allowed to interact
  866. if (!checkPriv(player->getName(), "interact")) {
  867. infostream << "Cannot craft: "
  868. << "No interact privilege" << std::endl;
  869. delete a;
  870. return;
  871. }
  872. }
  873. // Do the action
  874. a->apply(this, playersao, this);
  875. // Eat the action
  876. delete a;
  877. SendInventory(playersao);
  878. }
  879. void Server::handleCommand_ChatMessage(NetworkPacket* pkt)
  880. {
  881. /*
  882. u16 command
  883. u16 length
  884. wstring message
  885. */
  886. u16 len;
  887. *pkt >> len;
  888. std::wstring message;
  889. for (u16 i = 0; i < len; i++) {
  890. u16 tmp_wchar;
  891. *pkt >> tmp_wchar;
  892. message += (wchar_t)tmp_wchar;
  893. }
  894. RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
  895. if (player == NULL) {
  896. errorstream << "Server::ProcessData(): Canceling: "
  897. "No player for peer_id=" << pkt->getPeerId()
  898. << " disconnecting peer!" << std::endl;
  899. m_con->DisconnectPeer(pkt->getPeerId());
  900. return;
  901. }
  902. // Get player name of this client
  903. std::string name = player->getName();
  904. std::wstring wname = narrow_to_wide(name);
  905. std::wstring answer_to_sender = handleChat(name, wname, message, true, player);
  906. if (!answer_to_sender.empty()) {
  907. // Send the answer to sender
  908. SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_NORMAL,
  909. answer_to_sender, wname));
  910. }
  911. }
  912. void Server::handleCommand_Damage(NetworkPacket* pkt)
  913. {
  914. u8 damage;
  915. *pkt >> damage;
  916. RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
  917. if (player == NULL) {
  918. errorstream << "Server::ProcessData(): Canceling: "
  919. "No player for peer_id=" << pkt->getPeerId()
  920. << " disconnecting peer!" << std::endl;
  921. m_con->DisconnectPeer(pkt->getPeerId());
  922. return;
  923. }
  924. PlayerSAO *playersao = player->getPlayerSAO();
  925. if (playersao == NULL) {
  926. errorstream << "Server::ProcessData(): Canceling: "
  927. "No player object for peer_id=" << pkt->getPeerId()
  928. << " disconnecting peer!" << std::endl;
  929. m_con->DisconnectPeer(pkt->getPeerId());
  930. return;
  931. }
  932. if (g_settings->getBool("enable_damage")) {
  933. if (playersao->isDead()) {
  934. verbosestream << "Server::ProcessData(): Info: "
  935. "Ignoring damage as player " << player->getName()
  936. << " is already dead." << std::endl;
  937. return;
  938. }
  939. actionstream << player->getName() << " damaged by "
  940. << (int)damage << " hp at " << PP(playersao->getBasePosition() / BS)
  941. << std::endl;
  942. playersao->setHP(playersao->getHP() - damage);
  943. SendPlayerHPOrDie(playersao);
  944. }
  945. }
  946. void Server::handleCommand_Password(NetworkPacket* pkt)
  947. {
  948. if (pkt->getSize() != PASSWORD_SIZE * 2)
  949. return;
  950. std::string oldpwd;
  951. std::string newpwd;
  952. // Deny for clients using the new protocol
  953. RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);
  954. if (client->net_proto_version >= 25) {
  955. infostream << "Server::handleCommand_Password(): Denying change: "
  956. << " Client protocol version for peer_id=" << pkt->getPeerId()
  957. << " too new!" << std::endl;
  958. return;
  959. }
  960. for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
  961. char c = pkt->getChar(i);
  962. if (c == 0)
  963. break;
  964. oldpwd += c;
  965. }
  966. for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
  967. char c = pkt->getChar(PASSWORD_SIZE + i);
  968. if (c == 0)
  969. break;
  970. newpwd += c;
  971. }
  972. RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
  973. if (player == NULL) {
  974. errorstream << "Server::ProcessData(): Canceling: "
  975. "No player for peer_id=" << pkt->getPeerId()
  976. << " disconnecting peer!" << std::endl;
  977. m_con->DisconnectPeer(pkt->getPeerId());
  978. return;
  979. }
  980. if (!base64_is_valid(newpwd)) {
  981. infostream<<"Server: " << player->getName() <<
  982. " supplied invalid password hash" << std::endl;
  983. // Wrong old password supplied!!
  984. SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
  985. L"Invalid new password hash supplied. Password NOT changed."));
  986. return;
  987. }
  988. infostream << "Server: Client requests a password change from "
  989. << "'" << oldpwd << "' to '" << newpwd << "'" << std::endl;
  990. std::string playername = player->getName();
  991. std::string checkpwd;
  992. m_script->getAuth(playername, &checkpwd, NULL);
  993. if (oldpwd != checkpwd) {
  994. infostream << "Server: invalid old password" << std::endl;
  995. // Wrong old password supplied!!
  996. SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
  997. L"Invalid old password supplied. Password NOT changed."));
  998. return;
  999. }
  1000. bool success = m_script->setPassword(playername, newpwd);
  1001. if (success) {
  1002. actionstream << player->getName() << " changes password" << std::endl;
  1003. SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
  1004. L"Password change successful."));
  1005. } else {
  1006. actionstream << player->getName() << " tries to change password but "
  1007. << "it fails" << std::endl;
  1008. SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
  1009. L"Password change failed or unavailable."));
  1010. }
  1011. }
  1012. void Server::handleCommand_PlayerItem(NetworkPacket* pkt)
  1013. {
  1014. if (pkt->getSize() < 2)
  1015. return;
  1016. RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
  1017. if (player == NULL) {
  1018. errorstream << "Server::ProcessData(): Canceling: "
  1019. "No player for peer_id=" << pkt->getPeerId()
  1020. << " disconnecting peer!" << std::endl;
  1021. m_con->DisconnectPeer(pkt->getPeerId());
  1022. return;
  1023. }
  1024. PlayerSAO *playersao = player->getPlayerSAO();
  1025. if (playersao == NULL) {
  1026. errorstream << "Server::ProcessData(): Canceling: "
  1027. "No player object for peer_id=" << pkt->getPeerId()
  1028. << " disconnecting peer!" << std::endl;
  1029. m_con->DisconnectPeer(pkt->getPeerId());
  1030. return;
  1031. }
  1032. u16 item;
  1033. *pkt >> item;
  1034. playersao->setWieldIndex(item);
  1035. }
  1036. void Server::handleCommand_Respawn(NetworkPacket* pkt)
  1037. {
  1038. RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
  1039. if (player == NULL) {
  1040. errorstream << "Server::ProcessData(): Canceling: "
  1041. "No player for peer_id=" << pkt->getPeerId()
  1042. << " disconnecting peer!" << std::endl;
  1043. m_con->DisconnectPeer(pkt->getPeerId());
  1044. return;
  1045. }
  1046. PlayerSAO *playersao = player->getPlayerSAO();
  1047. assert(playersao);
  1048. if (!playersao->isDead())
  1049. return;
  1050. RespawnPlayer(pkt->getPeerId());
  1051. actionstream << player->getName() << " respawns at "
  1052. << PP(playersao->getBasePosition() / BS) << std::endl;
  1053. // ActiveObject is added to environment in AsyncRunStep after
  1054. // the previous addition has been successfully removed
  1055. }
  1056. void Server::handleCommand_Interact(NetworkPacket* pkt)
  1057. {
  1058. /*
  1059. [0] u16 command
  1060. [2] u8 action
  1061. [3] u16 item
  1062. [5] u32 length of the next item (plen)
  1063. [9] serialized PointedThing
  1064. [9 + plen] player position information
  1065. actions:
  1066. 0: start digging (from undersurface) or use
  1067. 1: stop digging (all parameters ignored)
  1068. 2: digging completed
  1069. 3: place block or item (to abovesurface)
  1070. 4: use item
  1071. 5: rightclick air ("activate")
  1072. */
  1073. u8 action;
  1074. u16 item_i;
  1075. *pkt >> action;
  1076. *pkt >> item_i;
  1077. std::istringstream tmp_is(pkt->readLongString(), std::ios::binary);
  1078. PointedThing pointed;
  1079. pointed.deSerialize(tmp_is);
  1080. verbosestream << "TOSERVER_INTERACT: action=" << (int)action << ", item="
  1081. << item_i << ", pointed=" << pointed.dump() << std::endl;
  1082. RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
  1083. if (player == NULL) {
  1084. errorstream << "Server::ProcessData(): Canceling: "
  1085. "No player for peer_id=" << pkt->getPeerId()
  1086. << " disconnecting peer!" << std::endl;
  1087. m_con->DisconnectPeer(pkt->getPeerId());
  1088. return;
  1089. }
  1090. PlayerSAO *playersao = player->getPlayerSAO();
  1091. if (playersao == NULL) {
  1092. errorstream << "Server::ProcessData(): Canceling: "
  1093. "No player object for peer_id=" << pkt->getPeerId()
  1094. << " disconnecting peer!" << std::endl;
  1095. m_con->DisconnectPeer(pkt->getPeerId());
  1096. return;
  1097. }
  1098. if (playersao->isDead()) {
  1099. actionstream << "Server: NoCheat: " << player->getName()
  1100. << " tried to interact while dead; ignoring." << std::endl;
  1101. if (pointed.type == POINTEDTHING_NODE) {
  1102. // Re-send block to revert change on client-side
  1103. RemoteClient *client = getClient(pkt->getPeerId());
  1104. v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
  1105. client->SetBlockNotSent(blockpos);
  1106. }
  1107. // Call callbacks
  1108. m_script->on_cheat(playersao, "interacted_while_dead");
  1109. return;
  1110. }
  1111. process_PlayerPos(player, playersao, pkt);
  1112. v3f player_pos = playersao->getLastGoodPosition();
  1113. // Update wielded item
  1114. playersao->setWieldIndex(item_i);
  1115. // Get pointed to node (undefined if not POINTEDTYPE_NODE)
  1116. v3s16 p_under = pointed.node_undersurface;
  1117. v3s16 p_above = pointed.node_abovesurface;
  1118. // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
  1119. ServerActiveObject *pointed_object = NULL;
  1120. if (pointed.type == POINTEDTHING_OBJECT) {
  1121. pointed_object = m_env->getActiveObject(pointed.object_id);
  1122. if (pointed_object == NULL) {
  1123. verbosestream << "TOSERVER_INTERACT: "
  1124. "pointed object is NULL" << std::endl;
  1125. return;
  1126. }
  1127. }
  1128. v3f pointed_pos_under = player_pos;
  1129. v3f pointed_pos_above = player_pos;
  1130. if (pointed.type == POINTEDTHING_NODE) {
  1131. pointed_pos_under = intToFloat(p_under, BS);
  1132. pointed_pos_above = intToFloat(p_above, BS);
  1133. }
  1134. else if (pointed.type == POINTEDTHING_OBJECT) {
  1135. pointed_pos_under = pointed_object->getBasePosition();
  1136. pointed_pos_above = pointed_pos_under;
  1137. }
  1138. /*
  1139. Make sure the player is allowed to do it
  1140. */
  1141. if (!checkPriv(player->getName(), "interact")) {
  1142. actionstream<<player->getName()<<" attempted to interact with "
  1143. <<pointed.dump()<<" without 'interact' privilege"
  1144. <<std::endl;
  1145. // Re-send block to revert change on client-side
  1146. RemoteClient *client = getClient(pkt->getPeerId());
  1147. // Digging completed -> under
  1148. if (action == 2) {
  1149. v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
  1150. client->SetBlockNotSent(blockpos);
  1151. }
  1152. // Placement -> above
  1153. if (action == 3) {
  1154. v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
  1155. client->SetBlockNotSent(blockpos);
  1156. }
  1157. return;
  1158. }
  1159. /*
  1160. Check that target is reasonably close
  1161. (only when digging or placing things)
  1162. */
  1163. static thread_local const bool enable_anticheat =
  1164. !g_settings->getBool("disable_anticheat");
  1165. if ((action == 0 || action == 2 || action == 3 || action == 4) &&
  1166. (enable_anticheat && !isSingleplayer())) {
  1167. float d = player_pos.getDistanceFrom(pointed_pos_under);
  1168. const ItemDefinition &playeritem_def =
  1169. playersao->getWieldedItem().getDefinition(m_itemdef);
  1170. float max_d = BS * playeritem_def.range;
  1171. InventoryList *hlist = playersao->getInventory()->getList("hand");
  1172. const ItemDefinition &hand_def =
  1173. hlist ? (hlist->getItem(0).getDefinition(m_itemdef)) : (m_itemdef->get(""));
  1174. float max_d_hand = BS * hand_def.range;
  1175. if (max_d < 0 && max_d_hand >= 0)
  1176. max_d = max_d_hand;
  1177. else if (max_d < 0)
  1178. max_d = BS * 4.0;
  1179. // cube diagonal: sqrt(3) = 1.73
  1180. if (d > max_d * 1.73) {
  1181. actionstream << "Player " << player->getName()
  1182. << " tried to access " << pointed.dump()
  1183. << " from too far: "
  1184. << "d=" << d <<", max_d=" << max_d
  1185. << ". ignoring." << std::endl;
  1186. // Re-send block to revert change on client-side
  1187. RemoteClient *client = getClient(pkt->getPeerId());
  1188. v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
  1189. client->SetBlockNotSent(blockpos);
  1190. // Call callbacks
  1191. m_script->on_cheat(playersao, "interacted_too_far");
  1192. // Do nothing else
  1193. return;
  1194. }
  1195. }
  1196. /*
  1197. If something goes wrong, this player is to blame
  1198. */
  1199. RollbackScopeActor rollback_scope(m_rollback,
  1200. std::string("player:")+player->getName());
  1201. /*
  1202. 0: start digging or punch object
  1203. */
  1204. if (action == 0) {
  1205. if (pointed.type == POINTEDTHING_NODE) {
  1206. MapNode n(CONTENT_IGNORE);
  1207. bool pos_ok;
  1208. n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
  1209. if (!pos_ok) {
  1210. infostream << "Server: Not punching: Node not found."
  1211. << " Adding block to emerge queue."
  1212. << std::endl;
  1213. m_emerge->enqueueBlockEmerge(pkt->getPeerId(),
  1214. getNodeBlockPos(p_above), false);
  1215. }
  1216. if (n.getContent() != CONTENT_IGNORE)
  1217. m_script->node_on_punch(p_under, n, playersao, pointed);
  1218. // Cheat prevention
  1219. playersao->noCheatDigStart(p_under);
  1220. }
  1221. else if (pointed.type == POINTEDTHING_OBJECT) {
  1222. // Skip if object has been removed
  1223. if (pointed_object->m_removed)
  1224. return;
  1225. actionstream<<player->getName()<<" punches object "
  1226. <<pointed.object_id<<": "
  1227. <<pointed_object->getDescription()<<std::endl;
  1228. ItemStack punchitem = playersao->getWieldedItemOrHand();
  1229. ToolCapabilities toolcap =
  1230. punchitem.getToolCapabilities(m_itemdef);
  1231. v3f dir = (pointed_object->getBasePosition() -
  1232. (playersao->getBasePosition() + playersao->getEyeOffset())
  1233. ).normalize();
  1234. float time_from_last_punch =
  1235. playersao->resetTimeFromLastPunch();
  1236. s16 src_original_hp = pointed_object->getHP();
  1237. s16 dst_origin_hp = playersao->getHP();
  1238. pointed_object->punch(dir, &toolcap, playersao,
  1239. time_from_last_punch);
  1240. // If the object is a player and its HP changed
  1241. if (src_original_hp != pointed_object->getHP() &&
  1242. pointed_object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
  1243. SendPlayerHPOrDie((PlayerSAO *)pointed_object);
  1244. }
  1245. // If the puncher is a player and its HP changed
  1246. if (dst_origin_hp != playersao->getHP())
  1247. SendPlayerHPOrDie(playersao);
  1248. }
  1249. } // action == 0
  1250. /*
  1251. 1: stop digging
  1252. */
  1253. else if (action == 1) {
  1254. } // action == 1
  1255. /*
  1256. 2: Digging completed
  1257. */
  1258. else if (action == 2) {
  1259. // Only digging of nodes
  1260. if (pointed.type == POINTEDTHING_NODE) {
  1261. bool pos_ok;
  1262. MapNode n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
  1263. if (!pos_ok) {
  1264. infostream << "Server: Not finishing digging: Node not found."
  1265. << " Adding block to emerge queue."
  1266. << std::endl;
  1267. m_emerge->enqueueBlockEmerge(pkt->getPeerId(),
  1268. getNodeBlockPos(p_above), false);
  1269. }
  1270. /* Cheat prevention */
  1271. bool is_valid_dig = true;
  1272. if (enable_anticheat && !isSingleplayer()) {
  1273. v3s16 nocheat_p = playersao->getNoCheatDigPos();
  1274. float nocheat_t = playersao->getNoCheatDigTime();
  1275. playersao->noCheatDigEnd();
  1276. // If player didn't start digging this, ignore dig
  1277. if (nocheat_p != p_under) {
  1278. infostream << "Server: NoCheat: " << player->getName()
  1279. << " started digging "
  1280. << PP(nocheat_p) << " and completed digging "
  1281. << PP(p_under) << "; not digging." << std::endl;
  1282. is_valid_dig = false;
  1283. // Call callbacks
  1284. m_script->on_cheat(playersao, "finished_unknown_dig");
  1285. }
  1286. // Get player's wielded item
  1287. ItemStack playeritem = playersao->getWieldedItemOrHand();
  1288. ToolCapabilities playeritem_toolcap =
  1289. playeritem.getToolCapabilities(m_itemdef);
  1290. // Get diggability and expected digging time
  1291. DigParams params = getDigParams(m_nodedef->get(n).groups,
  1292. &playeritem_toolcap);
  1293. // If can't dig, try hand
  1294. if (!params.diggable) {
  1295. InventoryList *hlist = playersao->getInventory()->getList("hand");
  1296. const ItemDefinition &hand =
  1297. hlist ? hlist->getItem(0).getDefinition(m_itemdef) : m_itemdef->get("");
  1298. const ToolCapabilities *tp = hand.tool_capabilities;
  1299. if (tp)
  1300. params = getDigParams(m_nodedef->get(n).groups, tp);
  1301. }
  1302. // If can't dig, ignore dig
  1303. if (!params.diggable) {
  1304. infostream << "Server: NoCheat: " << player->getName()
  1305. << " completed digging " << PP(p_under)
  1306. << ", which is not diggable with tool. not digging."
  1307. << std::endl;
  1308. is_valid_dig = false;
  1309. // Call callbacks
  1310. m_script->on_cheat(playersao, "dug_unbreakable");
  1311. }
  1312. // Check digging time
  1313. // If already invalidated, we don't have to
  1314. if (!is_valid_dig) {
  1315. // Well not our problem then
  1316. }
  1317. // Clean and long dig
  1318. else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
  1319. // All is good, but grab time from pool; don't care if
  1320. // it's actually available
  1321. playersao->getDigPool().grab(params.time);
  1322. }
  1323. // Short or laggy dig
  1324. // Try getting the time from pool
  1325. else if (playersao->getDigPool().grab(params.time)) {
  1326. // All is good
  1327. }
  1328. // Dig not possible
  1329. else {
  1330. infostream << "Server: NoCheat: " << player->getName()
  1331. << " completed digging " << PP(p_under)
  1332. << "too fast; not digging." << std::endl;
  1333. is_valid_dig = false;
  1334. // Call callbacks
  1335. m_script->on_cheat(playersao, "dug_too_fast");
  1336. }
  1337. }
  1338. /* Actually dig node */
  1339. if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
  1340. m_script->node_on_dig(p_under, n, playersao);
  1341. v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
  1342. RemoteClient *client = getClient(pkt->getPeerId());
  1343. // Send unusual result (that is, node not being removed)
  1344. if (m_env->getMap().getNodeNoEx(p_under).getContent() != CONTENT_AIR) {
  1345. // Re-send block to revert change on client-side
  1346. client->SetBlockNotSent(blockpos);
  1347. }
  1348. else {
  1349. client->ResendBlockIfOnWire(blockpos);
  1350. }
  1351. }
  1352. } // action == 2
  1353. /*
  1354. 3: place block or right-click object
  1355. */
  1356. else if (action == 3) {
  1357. ItemStack item = playersao->getWieldedItem();
  1358. // Reset build time counter
  1359. if (pointed.type == POINTEDTHING_NODE &&
  1360. item.getDefinition(m_itemdef).type == ITEM_NODE)
  1361. getClient(pkt->getPeerId())->m_time_from_building = 0.0;
  1362. if (pointed.type == POINTEDTHING_OBJECT) {
  1363. // Right click object
  1364. // Skip if object has been removed
  1365. if (pointed_object->m_removed)
  1366. return;
  1367. actionstream << player->getName() << " right-clicks object "
  1368. << pointed.object_id << ": "
  1369. << pointed_object->getDescription() << std::endl;
  1370. // Do stuff
  1371. pointed_object->rightClick(playersao);
  1372. }
  1373. else if (m_script->item_OnPlace(
  1374. item, playersao, pointed)) {
  1375. // Placement was handled in lua
  1376. // Apply returned ItemStack
  1377. if (playersao->setWieldedItem(item)) {
  1378. SendInventory(playersao);
  1379. }
  1380. }
  1381. // If item has node placement prediction, always send the
  1382. // blocks to make sure the client knows what exactly happened
  1383. RemoteClient *client = getClient(pkt->getPeerId());
  1384. v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
  1385. v3s16 blockpos2 = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
  1386. if (!item.getDefinition(m_itemdef).node_placement_prediction.empty()) {
  1387. client->SetBlockNotSent(blockpos);
  1388. if (blockpos2 != blockpos) {
  1389. client->SetBlockNotSent(blockpos2);
  1390. }
  1391. }
  1392. else {
  1393. client->ResendBlockIfOnWire(blockpos);
  1394. if (blockpos2 != blockpos) {
  1395. client->ResendBlockIfOnWire(blockpos2);
  1396. }
  1397. }
  1398. } // action == 3
  1399. /*
  1400. 4: use
  1401. */
  1402. else if (action == 4) {
  1403. ItemStack item = playersao->getWieldedItem();
  1404. actionstream << player->getName() << " uses " << item.name
  1405. << ", pointing at " << pointed.dump() << std::endl;
  1406. if (m_script->item_OnUse(
  1407. item, playersao, pointed)) {
  1408. // Apply returned ItemStack
  1409. if (playersao->setWieldedItem(item)) {
  1410. SendInventory(playersao);
  1411. }
  1412. }
  1413. } // action == 4
  1414. /*
  1415. 5: rightclick air
  1416. */
  1417. else if (action == 5) {
  1418. ItemStack item = playersao->getWieldedItem();
  1419. actionstream << player->getName() << " activates "
  1420. << item.name << std::endl;
  1421. if (m_script->item_OnSecondaryUse(
  1422. item, playersao)) {
  1423. if( playersao->setWieldedItem(item)) {
  1424. SendInventory(playersao);
  1425. }
  1426. }
  1427. }
  1428. /*
  1429. Catch invalid actions
  1430. */
  1431. else {
  1432. warningstream << "Server: Invalid action "
  1433. << action << std::endl;
  1434. }
  1435. }
  1436. void Server::handleCommand_RemovedSounds(NetworkPacket* pkt)
  1437. {
  1438. u16 num;
  1439. *pkt >> num;
  1440. for (u16 k = 0; k < num; k++) {
  1441. s32 id;
  1442. *pkt >> id;
  1443. std::unordered_map<s32, ServerPlayingSound>::iterator i =
  1444. m_playing_sounds.find(id);
  1445. if (i == m_playing_sounds.end())
  1446. continue;
  1447. ServerPlayingSound &psound = i->second;
  1448. psound.clients.erase(pkt->getPeerId());
  1449. if (psound.clients.empty())
  1450. m_playing_sounds.erase(i++);
  1451. }
  1452. }
  1453. void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt)
  1454. {
  1455. v3s16 p;
  1456. std::string formname;
  1457. u16 num;
  1458. *pkt >> p >> formname >> num;
  1459. StringMap fields;
  1460. for (u16 k = 0; k < num; k++) {
  1461. std::string fieldname;
  1462. *pkt >> fieldname;
  1463. fields[fieldname] = pkt->readLongString();
  1464. }
  1465. RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
  1466. if (player == NULL) {
  1467. errorstream << "Server::ProcessData(): Canceling: "
  1468. "No player for peer_id=" << pkt->getPeerId()
  1469. << " disconnecting peer!" << std::endl;
  1470. m_con->DisconnectPeer(pkt->getPeerId());
  1471. return;
  1472. }
  1473. PlayerSAO *playersao = player->getPlayerSAO();
  1474. if (playersao == NULL) {
  1475. errorstream << "Server::ProcessData(): Canceling: "
  1476. "No player object for peer_id=" << pkt->getPeerId()
  1477. << " disconnecting peer!" << std::endl;
  1478. m_con->DisconnectPeer(pkt->getPeerId());
  1479. return;
  1480. }
  1481. // If something goes wrong, this player is to blame
  1482. RollbackScopeActor rollback_scope(m_rollback,
  1483. std::string("player:")+player->getName());
  1484. // Check the target node for rollback data; leave others unnoticed
  1485. RollbackNode rn_old(&m_env->getMap(), p, this);
  1486. m_script->node_on_receive_fields(p, formname, fields, playersao);
  1487. // Report rollback data
  1488. RollbackNode rn_new(&m_env->getMap(), p, this);
  1489. if (rollback() && rn_new != rn_old) {
  1490. RollbackAction action;
  1491. action.setSetNode(p, rn_old, rn_new);
  1492. rollback()->reportAction(action);
  1493. }
  1494. }
  1495. void Server::handleCommand_InventoryFields(NetworkPacket* pkt)
  1496. {
  1497. std::string formname;
  1498. u16 num;
  1499. *pkt >> formname >> num;
  1500. StringMap fields;
  1501. for (u16 k = 0; k < num; k++) {
  1502. std::string fieldname;
  1503. *pkt >> fieldname;
  1504. fields[fieldname] = pkt->readLongString();
  1505. }
  1506. RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
  1507. if (player == NULL) {
  1508. errorstream << "Server::ProcessData(): Canceling: "
  1509. "No player for peer_id=" << pkt->getPeerId()
  1510. << " disconnecting peer!" << std::endl;
  1511. m_con->DisconnectPeer(pkt->getPeerId());
  1512. return;
  1513. }
  1514. PlayerSAO *playersao = player->getPlayerSAO();
  1515. if (playersao == NULL) {
  1516. errorstream << "Server::ProcessData(): Canceling: "
  1517. "No player object for peer_id=" << pkt->getPeerId()
  1518. << " disconnecting peer!" << std::endl;
  1519. m_con->DisconnectPeer(pkt->getPeerId());
  1520. return;
  1521. }
  1522. m_script->on_playerReceiveFields(playersao, formname, fields);
  1523. }
  1524. void Server::handleCommand_FirstSrp(NetworkPacket* pkt)
  1525. {
  1526. RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
  1527. ClientState cstate = client->getState();
  1528. std::string playername = client->getName();
  1529. std::string salt;
  1530. std::string verification_key;
  1531. std::string addr_s = getPeerAddress(pkt->getPeerId()).serializeString();
  1532. u8 is_empty;
  1533. *pkt >> salt >> verification_key >> is_empty;
  1534. verbosestream << "Server: Got TOSERVER_FIRST_SRP from " << addr_s
  1535. << ", with is_empty=" << (is_empty == 1) << std::endl;
  1536. // Either this packet is sent because the user is new or to change the password
  1537. if (cstate == CS_HelloSent) {
  1538. if (!client->isMechAllowed(AUTH_MECHANISM_FIRST_SRP)) {
  1539. actionstream << "Server: Client from " << addr_s
  1540. << " tried to set password without being "
  1541. << "authenticated, or the username being new." << std::endl;
  1542. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
  1543. return;
  1544. }
  1545. if (!isSingleplayer() &&
  1546. g_settings->getBool("disallow_empty_password") &&
  1547. is_empty == 1) {
  1548. actionstream << "Server: " << playername
  1549. << " supplied empty password from " << addr_s << std::endl;
  1550. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_EMPTY_PASSWORD);
  1551. return;
  1552. }
  1553. std::string initial_ver_key;
  1554. initial_ver_key = encode_srp_verifier(verification_key, salt);
  1555. m_script->createAuth(playername, initial_ver_key);
  1556. acceptAuth(pkt->getPeerId(), false);
  1557. } else {
  1558. if (cstate < CS_SudoMode) {
  1559. infostream << "Server::ProcessData(): Ignoring TOSERVER_FIRST_SRP from "
  1560. << addr_s << ": " << "Client has wrong state " << cstate << "."
  1561. << std::endl;
  1562. return;
  1563. }
  1564. m_clients.event(pkt->getPeerId(), CSE_SudoLeave);
  1565. std::string pw_db_field = encode_srp_verifier(verification_key, salt);
  1566. bool success = m_script->setPassword(playername, pw_db_field);
  1567. if (success) {
  1568. actionstream << playername << " changes password" << std::endl;
  1569. SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
  1570. L"Password change successful."));
  1571. } else {
  1572. actionstream << playername << " tries to change password but "
  1573. << "it fails" << std::endl;
  1574. SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
  1575. L"Password change failed or unavailable."));
  1576. }
  1577. }
  1578. }
  1579. void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
  1580. {
  1581. RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
  1582. ClientState cstate = client->getState();
  1583. bool wantSudo = (cstate == CS_Active);
  1584. if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
  1585. actionstream << "Server: got SRP _A packet in wrong state "
  1586. << cstate << " from "
  1587. << getPeerAddress(pkt->getPeerId()).serializeString()
  1588. << ". Ignoring." << std::endl;
  1589. return;
  1590. }
  1591. if (client->chosen_mech != AUTH_MECHANISM_NONE) {
  1592. actionstream << "Server: got SRP _A packet, while auth"
  1593. << "is already going on with mech " << client->chosen_mech
  1594. << " from " << getPeerAddress(pkt->getPeerId()).serializeString()
  1595. << " (wantSudo=" << wantSudo << "). Ignoring." << std::endl;
  1596. if (wantSudo) {
  1597. DenySudoAccess(pkt->getPeerId());
  1598. return;
  1599. }
  1600. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
  1601. return;
  1602. }
  1603. std::string bytes_A;
  1604. u8 based_on;
  1605. *pkt >> bytes_A >> based_on;
  1606. infostream << "Server: TOSERVER_SRP_BYTES_A received with "
  1607. << "based_on=" << int(based_on) << " and len_A="
  1608. << bytes_A.length() << "." << std::endl;
  1609. AuthMechanism chosen = (based_on == 0) ?
  1610. AUTH_MECHANISM_LEGACY_PASSWORD : AUTH_MECHANISM_SRP;
  1611. if (wantSudo) {
  1612. if (!client->isSudoMechAllowed(chosen)) {
  1613. actionstream << "Server: Player \"" << client->getName()
  1614. << "\" at " << getPeerAddress(pkt->getPeerId()).serializeString()
  1615. << " tried to change password using unallowed mech "
  1616. << chosen << "." << std::endl;
  1617. DenySudoAccess(pkt->getPeerId());
  1618. return;
  1619. }
  1620. } else {
  1621. if (!client->isMechAllowed(chosen)) {
  1622. actionstream << "Server: Client tried to authenticate from "
  1623. << getPeerAddress(pkt->getPeerId()).serializeString()
  1624. << " using unallowed mech " << chosen << "." << std::endl;
  1625. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
  1626. return;
  1627. }
  1628. }
  1629. client->chosen_mech = chosen;
  1630. std::string salt;
  1631. std::string verifier;
  1632. if (based_on == 0) {
  1633. generate_srp_verifier_and_salt(client->getName(), client->enc_pwd,
  1634. &verifier, &salt);
  1635. } else if (!decode_srp_verifier_and_salt(client->enc_pwd, &verifier, &salt)) {
  1636. // Non-base64 errors should have been catched in the init handler
  1637. actionstream << "Server: User " << client->getName()
  1638. << " tried to log in, but srp verifier field"
  1639. << " was invalid (most likely invalid base64)." << std::endl;
  1640. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
  1641. return;
  1642. }
  1643. char *bytes_B = 0;
  1644. size_t len_B = 0;
  1645. client->auth_data = srp_verifier_new(SRP_SHA256, SRP_NG_2048,
  1646. client->getName().c_str(),
  1647. (const unsigned char *) salt.c_str(), salt.size(),
  1648. (const unsigned char *) verifier.c_str(), verifier.size(),
  1649. (const unsigned char *) bytes_A.c_str(), bytes_A.size(),
  1650. NULL, 0,
  1651. (unsigned char **) &bytes_B, &len_B, NULL, NULL);
  1652. if (!bytes_B) {
  1653. actionstream << "Server: User " << client->getName()
  1654. << " tried to log in, SRP-6a safety check violated in _A handler."
  1655. << std::endl;
  1656. if (wantSudo) {
  1657. DenySudoAccess(pkt->getPeerId());
  1658. return;
  1659. }
  1660. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
  1661. return;
  1662. }
  1663. NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, pkt->getPeerId());
  1664. resp_pkt << salt << std::string(bytes_B, len_B);
  1665. Send(&resp_pkt);
  1666. }
  1667. void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
  1668. {
  1669. RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
  1670. ClientState cstate = client->getState();
  1671. bool wantSudo = (cstate == CS_Active);
  1672. verbosestream << "Server: Recieved TOCLIENT_SRP_BYTES_M." << std::endl;
  1673. if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
  1674. actionstream << "Server: got SRP _M packet in wrong state "
  1675. << cstate << " from "
  1676. << getPeerAddress(pkt->getPeerId()).serializeString()
  1677. << ". Ignoring." << std::endl;
  1678. return;
  1679. }
  1680. if ((client->chosen_mech != AUTH_MECHANISM_SRP)
  1681. && (client->chosen_mech != AUTH_MECHANISM_LEGACY_PASSWORD)) {
  1682. actionstream << "Server: got SRP _M packet, while auth"
  1683. << "is going on with mech " << client->chosen_mech
  1684. << " from " << getPeerAddress(pkt->getPeerId()).serializeString()
  1685. << " (wantSudo=" << wantSudo << "). Denying." << std::endl;
  1686. if (wantSudo) {
  1687. DenySudoAccess(pkt->getPeerId());
  1688. return;
  1689. }
  1690. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
  1691. return;
  1692. }
  1693. std::string bytes_M;
  1694. *pkt >> bytes_M;
  1695. if (srp_verifier_get_session_key_length((SRPVerifier *) client->auth_data)
  1696. != bytes_M.size()) {
  1697. actionstream << "Server: User " << client->getName()
  1698. << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
  1699. << " sent bytes_M with invalid length " << bytes_M.size() << std::endl;
  1700. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
  1701. return;
  1702. }
  1703. unsigned char *bytes_HAMK = 0;
  1704. srp_verifier_verify_session((SRPVerifier *) client->auth_data,
  1705. (unsigned char *)bytes_M.c_str(), &bytes_HAMK);
  1706. if (!bytes_HAMK) {
  1707. if (wantSudo) {
  1708. actionstream << "Server: User " << client->getName()
  1709. << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
  1710. << " tried to change their password, but supplied wrong"
  1711. << " (SRP) password for authentication." << std::endl;
  1712. DenySudoAccess(pkt->getPeerId());
  1713. return;
  1714. }
  1715. actionstream << "Server: User " << client->getName()
  1716. << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
  1717. << " supplied wrong password (auth mechanism: SRP)."
  1718. << std::endl;
  1719. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_PASSWORD);
  1720. return;
  1721. }
  1722. if (client->create_player_on_auth_success) {
  1723. std::string playername = client->getName();
  1724. m_script->createAuth(playername, client->enc_pwd);
  1725. std::string checkpwd; // not used, but needed for passing something
  1726. if (!m_script->getAuth(playername, &checkpwd, NULL)) {
  1727. actionstream << "Server: " << playername << " cannot be authenticated"
  1728. << " (auth handler does not work?)" << std::endl;
  1729. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
  1730. return;
  1731. }
  1732. client->create_player_on_auth_success = false;
  1733. }
  1734. acceptAuth(pkt->getPeerId(), wantSudo);
  1735. }