serverpackethandler.cpp 60 KB

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