Datacenter.cpp 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568
  1. /*
  2. * This is the source code of tgnet library v. 1.1
  3. * It is licensed under GNU GPL v. 2 or later.
  4. * You should have received a copy of the license in this archive (see LICENSE).
  5. *
  6. * Copyright Nikolai Kudashov, 2015-2018.
  7. */
  8. #include <stdlib.h>
  9. #include <algorithm>
  10. #include <openssl/rand.h>
  11. #include <openssl/sha.h>
  12. #include <openssl/bn.h>
  13. #include <openssl/pem.h>
  14. #include <openssl/aes.h>
  15. #include <memory.h>
  16. #include <inttypes.h>
  17. #include "Datacenter.h"
  18. #include "Connection.h"
  19. #include "MTProtoScheme.h"
  20. #include "ApiScheme.h"
  21. #include "FileLog.h"
  22. #include "NativeByteBuffer.h"
  23. #include "ByteArray.h"
  24. #include "BuffersStorage.h"
  25. #include "ConnectionsManager.h"
  26. #include "Config.h"
  27. #include "Handshake.h"
  28. thread_local static SHA256_CTX sha256Ctx;
  29. Datacenter::Datacenter(int32_t instance, uint32_t id) {
  30. instanceNum = instance;
  31. datacenterId = id;
  32. for (auto & a : uploadConnection) {
  33. a = nullptr;
  34. }
  35. for (auto & a : downloadConnection) {
  36. a = nullptr;
  37. }
  38. for (auto & a : proxyConnection) {
  39. a = nullptr;
  40. }
  41. }
  42. Datacenter::Datacenter(int32_t instance, NativeByteBuffer *data) {
  43. instanceNum = instance;
  44. for (auto & a : uploadConnection) {
  45. a = nullptr;
  46. }
  47. for (auto & a : downloadConnection) {
  48. a = nullptr;
  49. }
  50. for (auto & a : proxyConnection) {
  51. a = nullptr;
  52. }
  53. uint32_t currentVersion = data->readUint32(nullptr);
  54. if (currentVersion >= 2 && currentVersion <= configVersion) {
  55. datacenterId = data->readUint32(nullptr);
  56. if (currentVersion >= 3) {
  57. lastInitVersion = data->readUint32(nullptr);
  58. }
  59. if (currentVersion >= 10) {
  60. lastInitMediaVersion = data->readUint32(nullptr);
  61. }
  62. int count = currentVersion >= 5 ? 4 : 1;
  63. for (int b = 0; b < count; b++) {
  64. std::vector<TcpAddress> *array;
  65. switch (b) {
  66. case 0:
  67. array = &addressesIpv4;
  68. break;
  69. case 1:
  70. array = &addressesIpv6;
  71. break;
  72. case 2:
  73. array = &addressesIpv4Download;
  74. break;
  75. case 3:
  76. array = &addressesIpv6Download;
  77. break;
  78. default:
  79. array = nullptr;
  80. break;
  81. }
  82. if (array == nullptr) {
  83. continue;
  84. }
  85. uint32_t len = data->readUint32(nullptr);
  86. for (uint32_t a = 0; a < len; a++) {
  87. std::string address = data->readString(nullptr);
  88. uint32_t port = data->readUint32(nullptr);
  89. int32_t flags;
  90. std::string secret;
  91. if (currentVersion >= 7) {
  92. flags = data->readInt32(nullptr);
  93. } else {
  94. flags = 0;
  95. }
  96. if (currentVersion >= 11) {
  97. secret = data->readString(nullptr);
  98. } else if (currentVersion >= 9) {
  99. secret = data->readString(nullptr);
  100. if (!secret.empty()) {
  101. size_t size = secret.size() / 2;
  102. char *result = new char[size];
  103. for (int32_t i = 0; i < size; i++) {
  104. result[i] = (char) (char2int(secret[i * 2]) * 16 + char2int(secret[i * 2 + 1]));
  105. }
  106. secret = std::string(result, size);
  107. delete[] result;
  108. }
  109. }
  110. (*array).push_back(TcpAddress(address, port, flags, secret));
  111. }
  112. }
  113. if (currentVersion >= 6) {
  114. isCdnDatacenter = data->readBool(nullptr);
  115. }
  116. uint32_t len = data->readUint32(nullptr);
  117. if (len != 0) {
  118. authKeyPerm = data->readBytes(len, nullptr);
  119. }
  120. if (currentVersion >= 4) {
  121. authKeyPermId = data->readInt64(nullptr);
  122. } else {
  123. len = data->readUint32(nullptr);
  124. if (len != 0) {
  125. authKeyPermId = data->readInt64(nullptr);
  126. }
  127. }
  128. if (currentVersion >= 8) {
  129. len = data->readUint32(nullptr);
  130. if (len != 0) {
  131. authKeyTemp = data->readBytes(len, nullptr);
  132. }
  133. authKeyTempId = data->readInt64(nullptr);
  134. }
  135. if (currentVersion >= 12) {
  136. len = data->readUint32(nullptr);
  137. if (len != 0) {
  138. authKeyMediaTemp = data->readBytes(len, nullptr);
  139. }
  140. authKeyMediaTempId = data->readInt64(nullptr);
  141. }
  142. authorized = data->readInt32(nullptr) != 0;
  143. len = data->readUint32(nullptr);
  144. for (uint32_t a = 0; a < len; a++) {
  145. auto salt = new TL_future_salt();
  146. salt->valid_since = data->readInt32(nullptr);
  147. salt->valid_until = data->readInt32(nullptr);
  148. salt->salt = data->readInt64(nullptr);
  149. serverSalts.push_back(std::unique_ptr<TL_future_salt>(salt));
  150. }
  151. if (currentVersion >= 13) {
  152. len = data->readUint32(nullptr);
  153. for (uint32_t a = 0; a < len; a++) {
  154. auto salt = new TL_future_salt();
  155. salt->valid_since = data->readInt32(nullptr);
  156. salt->valid_until = data->readInt32(nullptr);
  157. salt->salt = data->readInt64(nullptr);
  158. mediaServerSalts.push_back(std::unique_ptr<TL_future_salt>(salt));
  159. }
  160. }
  161. }
  162. if (config == nullptr) {
  163. config = new Config(instanceNum, "dc" + to_string_int32(datacenterId) + "conf.dat");
  164. }
  165. NativeByteBuffer *buffer = config->readConfig();
  166. if (buffer != nullptr) {
  167. uint32_t version = buffer->readUint32(nullptr);
  168. if (version >= 1) {
  169. currentPortNumIpv4 = buffer->readUint32(nullptr);
  170. currentAddressNumIpv4 = buffer->readUint32(nullptr);
  171. currentPortNumIpv6 = buffer->readUint32(nullptr);
  172. currentAddressNumIpv6 = buffer->readUint32(nullptr);
  173. currentPortNumIpv4Download = buffer->readUint32(nullptr);
  174. currentAddressNumIpv4Download = buffer->readUint32(nullptr);
  175. currentPortNumIpv6Download = buffer->readUint32(nullptr);
  176. currentAddressNumIpv6Download = buffer->readUint32(nullptr);
  177. }
  178. buffer->reuse();
  179. } else {
  180. currentPortNumIpv4 = 0;
  181. currentAddressNumIpv4 = 0;
  182. currentPortNumIpv6 = 0;
  183. currentAddressNumIpv6 = 0;
  184. currentPortNumIpv4Download = 0;
  185. currentAddressNumIpv4Download = 0;
  186. currentPortNumIpv6Download = 0;
  187. currentAddressNumIpv6Download = 0;
  188. }
  189. }
  190. TcpAddress *Datacenter::getCurrentAddress(uint32_t flags) {
  191. uint32_t currentAddressNum;
  192. std::vector<TcpAddress> *addresses;
  193. if (flags == 0 && (authKeyPerm == nullptr || PFS_ENABLED && authKeyTemp == nullptr) && !addressesIpv4Temp.empty()) {
  194. flags = TcpAddressFlagTemp;
  195. }
  196. if ((flags & TcpAddressFlagTemp) != 0) {
  197. currentAddressNum = currentAddressNumIpv4Temp;
  198. addresses = &addressesIpv4Temp;
  199. } else if ((flags & TcpAddressFlagDownload) != 0) {
  200. if ((flags & TcpAddressFlagIpv6) != 0) {
  201. currentAddressNum = currentAddressNumIpv6Download;
  202. addresses = &addressesIpv6Download;
  203. } else {
  204. currentAddressNum = currentAddressNumIpv4Download;
  205. addresses = &addressesIpv4Download;
  206. }
  207. } else {
  208. if ((flags & TcpAddressFlagIpv6) != 0) {
  209. currentAddressNum = currentAddressNumIpv6;
  210. addresses = &addressesIpv6;
  211. } else {
  212. currentAddressNum = currentAddressNumIpv4;
  213. addresses = &addressesIpv4;
  214. }
  215. }
  216. if (addresses->empty()) {
  217. return nullptr;
  218. }
  219. if ((flags & TcpAddressFlagStatic) != 0) {
  220. for (auto & addresse : *addresses) {
  221. if ((addresse.flags & TcpAddressFlagStatic) != 0) {
  222. return &addresse;
  223. }
  224. }
  225. }
  226. if (currentAddressNum >= addresses->size()) {
  227. currentAddressNum = 0;
  228. if ((flags & TcpAddressFlagTemp) != 0) {
  229. currentAddressNumIpv4Temp = currentAddressNum;
  230. } else if ((flags & TcpAddressFlagDownload) != 0) {
  231. if ((flags & TcpAddressFlagIpv6) != 0) {
  232. currentAddressNumIpv6Download = currentAddressNum;
  233. } else {
  234. currentAddressNumIpv4Download = currentAddressNum;
  235. }
  236. } else {
  237. if ((flags & TcpAddressFlagIpv6) != 0) {
  238. currentAddressNumIpv6 = currentAddressNum;
  239. } else {
  240. currentAddressNumIpv4 = currentAddressNum;
  241. }
  242. }
  243. }
  244. return &(*addresses)[currentAddressNum];
  245. }
  246. int32_t Datacenter::getCurrentPort(uint32_t flags) {
  247. uint32_t currentAddressNum;
  248. uint32_t currentPortNum;
  249. std::vector<TcpAddress> *addresses;
  250. if (flags == 0 && (authKeyPerm == nullptr || PFS_ENABLED && authKeyTemp == nullptr) && !addressesIpv4Temp.empty()) {
  251. flags = TcpAddressFlagTemp;
  252. }
  253. if ((flags & TcpAddressFlagTemp) != 0) {
  254. currentAddressNum = currentAddressNumIpv4Temp;
  255. currentPortNum = currentPortNumIpv4Temp;
  256. addresses = &addressesIpv4Temp;
  257. } else if ((flags & TcpAddressFlagDownload) != 0) {
  258. if ((flags & TcpAddressFlagIpv6) != 0) {
  259. currentAddressNum = currentAddressNumIpv6Download;
  260. currentPortNum = currentPortNumIpv6Download;
  261. addresses = &addressesIpv6Download;
  262. } else {
  263. currentAddressNum = currentAddressNumIpv4Download;
  264. currentPortNum = currentPortNumIpv4Download;
  265. addresses = &addressesIpv4Download;
  266. }
  267. } else {
  268. if ((flags & TcpAddressFlagIpv6) != 0) {
  269. currentAddressNum = currentAddressNumIpv6;
  270. currentPortNum = currentPortNumIpv6;
  271. addresses = &addressesIpv6;
  272. } else {
  273. currentAddressNum = currentAddressNumIpv4;
  274. currentPortNum = currentPortNumIpv4;
  275. addresses = &addressesIpv4;
  276. }
  277. }
  278. if (addresses->empty()) {
  279. return 443;
  280. }
  281. if ((flags & TcpAddressFlagStatic) != 0) {
  282. uint32_t num = 0;
  283. for (auto & addresse : *addresses) {
  284. if ((addresse.flags & TcpAddressFlagStatic) != 0) {
  285. currentAddressNum = num;
  286. break;
  287. }
  288. num++;
  289. }
  290. }
  291. if (currentAddressNum >= addresses->size()) {
  292. currentAddressNum = 0;
  293. if ((flags & TcpAddressFlagTemp) != 0) {
  294. currentAddressNumIpv4Temp = currentAddressNum;
  295. } else if ((flags & TcpAddressFlagDownload) != 0) {
  296. if ((flags & TcpAddressFlagIpv6) != 0) {
  297. currentAddressNumIpv6Download = currentAddressNum;
  298. } else {
  299. currentAddressNumIpv4Download = currentAddressNum;
  300. }
  301. } else {
  302. if ((flags & TcpAddressFlagIpv6) != 0) {
  303. currentAddressNumIpv6 = currentAddressNum;
  304. } else {
  305. currentAddressNumIpv4 = currentAddressNum;
  306. }
  307. }
  308. }
  309. if (currentPortNum >= 4) {
  310. currentPortNum = 0;
  311. if ((flags & TcpAddressFlagTemp) != 0) {
  312. currentPortNumIpv4Temp = currentAddressNum;
  313. } else if ((flags & TcpAddressFlagDownload) != 0) {
  314. if ((flags & TcpAddressFlagIpv6) != 0) {
  315. currentPortNumIpv6Download = currentPortNum;
  316. } else {
  317. currentPortNumIpv4Download = currentPortNum;
  318. }
  319. } else {
  320. if ((flags & TcpAddressFlagIpv6) != 0) {
  321. currentPortNumIpv6 = currentPortNum;
  322. } else {
  323. currentPortNumIpv4 = currentPortNum;
  324. }
  325. }
  326. }
  327. TcpAddress *address = &((*addresses) [currentAddressNum]);
  328. int32_t port;
  329. if (!address->secret.empty()) {
  330. port = -1;
  331. } else {
  332. port = defaultPorts[currentPortNum];
  333. }
  334. if (port == -1) {
  335. return address->port;
  336. }
  337. return port;
  338. }
  339. void Datacenter::addAddressAndPort(std::string address, uint32_t port, uint32_t flags, std::string secret) {
  340. std::vector<TcpAddress> *addresses;
  341. if ((flags & TcpAddressFlagTemp) != 0) {
  342. addresses = &addressesIpv4Temp;
  343. } else if ((flags & TcpAddressFlagDownload) != 0) {
  344. if ((flags & TcpAddressFlagIpv6) != 0) {
  345. addresses = &addressesIpv6Download;
  346. } else {
  347. addresses = &addressesIpv4Download;
  348. }
  349. } else {
  350. if ((flags & TcpAddressFlagIpv6) != 0) {
  351. addresses = &addressesIpv6;
  352. } else {
  353. addresses = &addressesIpv4;
  354. }
  355. }
  356. for (auto & addresse : *addresses) {
  357. if (addresse.address == address && addresse.port == port) {
  358. return;
  359. }
  360. }
  361. addresses->push_back(TcpAddress(address, port, flags, secret));
  362. }
  363. void Datacenter::nextAddressOrPort(uint32_t flags) {
  364. uint32_t currentPortNum;
  365. uint32_t currentAddressNum;
  366. std::vector<TcpAddress> *addresses;
  367. if (flags == 0 && (authKeyPerm == nullptr || PFS_ENABLED && authKeyTemp == nullptr) && !addressesIpv4Temp.empty()) {
  368. flags = TcpAddressFlagTemp;
  369. }
  370. if ((flags & TcpAddressFlagTemp) != 0) {
  371. currentPortNum = currentPortNumIpv4Temp;
  372. currentAddressNum = currentAddressNumIpv4Temp;
  373. addresses = &addressesIpv4Temp;
  374. } else if ((flags & TcpAddressFlagDownload) != 0) {
  375. if ((flags & TcpAddressFlagIpv6) != 0) {
  376. currentPortNum = currentPortNumIpv6Download;
  377. currentAddressNum = currentAddressNumIpv6Download;
  378. addresses = &addressesIpv6Download;
  379. } else {
  380. currentPortNum = currentPortNumIpv4Download;
  381. currentAddressNum = currentAddressNumIpv4Download;
  382. addresses = &addressesIpv4Download;
  383. }
  384. } else {
  385. if ((flags & TcpAddressFlagIpv6) != 0) {
  386. currentPortNum = currentPortNumIpv6;
  387. currentAddressNum = currentAddressNumIpv6;
  388. addresses = &addressesIpv6;
  389. } else {
  390. currentPortNum = currentPortNumIpv4;
  391. currentAddressNum = currentAddressNumIpv4;
  392. addresses = &addressesIpv4;
  393. }
  394. }
  395. bool tryNextPort = true;
  396. if ((flags & TcpAddressFlagStatic) == 0 && currentAddressNum < addresses->size()) {
  397. TcpAddress *currentAddress = &((*addresses)[currentAddressNum]);
  398. tryNextPort = (currentAddress->flags & TcpAddressFlagStatic) == 0;
  399. }
  400. if (tryNextPort && currentPortNum + 1 < 4) {
  401. currentPortNum++;
  402. } else {
  403. if (currentAddressNum + 1 < addresses->size()) {
  404. currentAddressNum++;
  405. } else {
  406. repeatCheckingAddresses = true;
  407. currentAddressNum = 0;
  408. }
  409. currentPortNum = 0;
  410. }
  411. if ((flags & TcpAddressFlagTemp) != 0) {
  412. currentPortNumIpv4Temp = currentPortNum;
  413. currentAddressNumIpv4Temp = currentAddressNum;
  414. } else if ((flags & TcpAddressFlagDownload) != 0) {
  415. if ((flags & TcpAddressFlagIpv6) != 0) {
  416. currentPortNumIpv6Download = currentPortNum;
  417. currentAddressNumIpv6Download = currentAddressNum;
  418. } else {
  419. currentPortNumIpv4Download = currentPortNum;
  420. currentAddressNumIpv4Download = currentAddressNum;
  421. }
  422. } else {
  423. if ((flags & TcpAddressFlagIpv6) != 0) {
  424. currentPortNumIpv6 = currentPortNum;
  425. currentAddressNumIpv6 = currentAddressNum;
  426. } else {
  427. currentPortNumIpv4 = currentPortNum;
  428. currentAddressNumIpv4 = currentAddressNum;
  429. }
  430. }
  431. }
  432. bool Datacenter::isCustomPort(uint32_t flags) {
  433. uint32_t currentPortNum;
  434. if (flags == 0 && (authKeyPerm == nullptr || PFS_ENABLED && authKeyTemp == nullptr) && !addressesIpv4Temp.empty()) {
  435. flags = TcpAddressFlagTemp;
  436. }
  437. if ((flags & TcpAddressFlagTemp) != 0) {
  438. currentPortNum = currentPortNumIpv4Temp;
  439. } else if ((flags & TcpAddressFlagDownload) != 0) {
  440. if ((flags & TcpAddressFlagIpv6) != 0) {
  441. currentPortNum = currentPortNumIpv6Download;
  442. } else {
  443. currentPortNum = currentPortNumIpv4Download;
  444. }
  445. } else {
  446. if ((flags & TcpAddressFlagIpv6) != 0) {
  447. currentPortNum = currentPortNumIpv6;
  448. } else {
  449. currentPortNum = currentPortNumIpv4;
  450. }
  451. }
  452. return defaultPorts[currentPortNum] != -1;
  453. }
  454. void Datacenter::storeCurrentAddressAndPortNum() {
  455. if (config == nullptr) {
  456. config = new Config(instanceNum, "dc" + to_string_int32(datacenterId) + "conf.dat");
  457. }
  458. NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(128);
  459. buffer->writeInt32(paramsConfigVersion);
  460. buffer->writeInt32(currentPortNumIpv4);
  461. buffer->writeInt32(currentAddressNumIpv4);
  462. buffer->writeInt32(currentPortNumIpv6);
  463. buffer->writeInt32(currentAddressNumIpv6);
  464. buffer->writeInt32(currentPortNumIpv4Download);
  465. buffer->writeInt32(currentAddressNumIpv4Download);
  466. buffer->writeInt32(currentPortNumIpv6Download);
  467. buffer->writeInt32(currentAddressNumIpv6Download);
  468. config->writeConfig(buffer);
  469. buffer->reuse();
  470. }
  471. void Datacenter::resetAddressAndPortNum() {
  472. currentPortNumIpv4 = 0;
  473. currentAddressNumIpv4 = 0;
  474. currentPortNumIpv6 = 0;
  475. currentAddressNumIpv6 = 0;
  476. currentPortNumIpv4Download = 0;
  477. currentAddressNumIpv4Download = 0;
  478. currentPortNumIpv6Download = 0;
  479. currentAddressNumIpv6Download = 0;
  480. storeCurrentAddressAndPortNum();
  481. }
  482. void Datacenter::replaceAddresses(std::vector<TcpAddress> &newAddresses, uint32_t flags) {
  483. isCdnDatacenter = (flags & 8) != 0;
  484. TcpAddress *currentTcpAddress = getCurrentAddress(flags);
  485. std::string currentAddress = currentTcpAddress != nullptr ? currentTcpAddress->address : "";
  486. if ((flags & TcpAddressFlagTemp) != 0) {
  487. addressesIpv4Temp = newAddresses;
  488. } else if ((flags & TcpAddressFlagDownload) != 0) {
  489. if ((flags & TcpAddressFlagIpv6) != 0) {
  490. addressesIpv6Download = newAddresses;
  491. } else {
  492. addressesIpv4Download = newAddresses;
  493. }
  494. } else {
  495. if ((flags & TcpAddressFlagIpv6) != 0) {
  496. addressesIpv6 = newAddresses;
  497. } else {
  498. addressesIpv4 = newAddresses;
  499. }
  500. }
  501. TcpAddress *newTcpAddress = getCurrentAddress(flags);
  502. std::string newAddress = newTcpAddress != nullptr ? newTcpAddress->address : "";
  503. if (currentAddress.compare(newAddress)) {
  504. if ((flags & TcpAddressFlagTemp) != 0) {
  505. currentPortNumIpv4Temp = 0;
  506. } else if ((flags & TcpAddressFlagDownload) != 0) {
  507. if ((flags & TcpAddressFlagIpv6) != 0) {
  508. currentPortNumIpv6Download = 0;
  509. } else {
  510. currentPortNumIpv4Download = 0;
  511. }
  512. } else {
  513. if ((flags & TcpAddressFlagIpv6) != 0) {
  514. currentPortNumIpv6 = 0;
  515. } else {
  516. currentPortNumIpv4 = 0;
  517. }
  518. }
  519. }
  520. }
  521. void Datacenter::serializeToStream(NativeByteBuffer *stream) {
  522. stream->writeInt32(configVersion);
  523. stream->writeInt32(datacenterId);
  524. stream->writeInt32(lastInitVersion);
  525. stream->writeInt32(lastInitMediaVersion);
  526. size_t size;
  527. for (int b = 0; b < 4; b++) {
  528. std::vector<TcpAddress> *array;
  529. switch (b) {
  530. case 0:
  531. array = &addressesIpv4;
  532. break;
  533. case 1:
  534. array = &addressesIpv6;
  535. break;
  536. case 2:
  537. array = &addressesIpv4Download;
  538. break;
  539. case 3:
  540. array = &addressesIpv6Download;
  541. break;
  542. default:
  543. array = nullptr;
  544. break;
  545. }
  546. if (array == nullptr) {
  547. continue;
  548. }
  549. stream->writeInt32((int32_t) (size = array->size()));
  550. for (uint32_t a = 0; a < size; a++) {
  551. stream->writeString((*array)[a].address);
  552. stream->writeInt32((*array)[a].port);
  553. stream->writeInt32((*array)[a].flags);
  554. stream->writeString((*array)[a].secret);
  555. }
  556. }
  557. stream->writeBool(isCdnDatacenter);
  558. if (authKeyPerm != nullptr) {
  559. stream->writeInt32(authKeyPerm->length);
  560. stream->writeBytes(authKeyPerm);
  561. } else {
  562. stream->writeInt32(0);
  563. }
  564. stream->writeInt64(authKeyPermId);
  565. if (authKeyTemp != nullptr) {
  566. stream->writeInt32(authKeyTemp->length);
  567. stream->writeBytes(authKeyTemp);
  568. } else {
  569. stream->writeInt32(0);
  570. }
  571. stream->writeInt64(authKeyTempId);
  572. if (authKeyMediaTemp != nullptr) {
  573. stream->writeInt32(authKeyMediaTemp->length);
  574. stream->writeBytes(authKeyMediaTemp);
  575. } else {
  576. stream->writeInt32(0);
  577. }
  578. stream->writeInt64(authKeyMediaTempId);
  579. stream->writeInt32(authorized ? 1 : 0);
  580. stream->writeInt32((int32_t) (size = serverSalts.size()));
  581. for (uint32_t a = 0; a < size; a++) {
  582. stream->writeInt32(serverSalts[a]->valid_since);
  583. stream->writeInt32(serverSalts[a]->valid_until);
  584. stream->writeInt64(serverSalts[a]->salt);
  585. }
  586. stream->writeInt32((int32_t) (size = mediaServerSalts.size()));
  587. for (uint32_t a = 0; a < size; a++) {
  588. stream->writeInt32(mediaServerSalts[a]->valid_since);
  589. stream->writeInt32(mediaServerSalts[a]->valid_until);
  590. stream->writeInt64(mediaServerSalts[a]->salt);
  591. }
  592. }
  593. void Datacenter::clearAuthKey(HandshakeType type) {
  594. if (type == HandshakeTypeAll || isCdnDatacenter) {
  595. if (authKeyPerm != nullptr) {
  596. delete authKeyPerm;
  597. authKeyPerm = nullptr;
  598. if (LOGS_ENABLED) DEBUG_D("dc%d account%u clear authKeyPerm", datacenterId, instanceNum);
  599. }
  600. authKeyPermId = 0;
  601. serverSalts.clear();
  602. }
  603. if (type == HandshakeTypeMediaTemp || type == HandshakeTypeAll) {
  604. if (authKeyMediaTemp != nullptr) {
  605. delete authKeyMediaTemp;
  606. authKeyMediaTemp = nullptr;
  607. if (LOGS_ENABLED) DEBUG_D("dc%d account%u clear authKeyMediaTemp", datacenterId, instanceNum);
  608. }
  609. authKeyMediaTempId = 0;
  610. lastInitMediaVersion = 0;
  611. mediaServerSalts.clear();
  612. }
  613. if (type == HandshakeTypeTemp || type == HandshakeTypeAll) {
  614. if (authKeyTemp != nullptr) {
  615. delete authKeyTemp;
  616. authKeyTemp = nullptr;
  617. if (LOGS_ENABLED) DEBUG_D("dc%d account%u clear authKeyTemp", datacenterId, instanceNum);
  618. }
  619. authKeyTempId = 0;
  620. lastInitVersion = 0;
  621. }
  622. handshakes.clear();
  623. }
  624. void Datacenter::clearServerSalts(bool media) {
  625. std::vector<std::unique_ptr<TL_future_salt>> &salts = media ? mediaServerSalts : serverSalts;
  626. salts.clear();
  627. }
  628. int64_t Datacenter::getServerSalt(bool media) {
  629. int32_t date = ConnectionsManager::getInstance(instanceNum).getCurrentTime();
  630. bool cleanupNeeded = false;
  631. int64_t result = 0;
  632. int32_t maxRemainingInterval = 0;
  633. std::vector<std::unique_ptr<TL_future_salt>> &salts = media ? mediaServerSalts : serverSalts;
  634. size_t size = salts.size();
  635. for (uint32_t a = 0; a < size; a++) {
  636. TL_future_salt *salt = salts[a].get();
  637. if (salt->valid_until < date) {
  638. cleanupNeeded = true;
  639. } else if (salt->valid_since <= date && salt->valid_until > date) {
  640. if (maxRemainingInterval == 0 || abs(salt->valid_until - date) > maxRemainingInterval) {
  641. maxRemainingInterval = abs(salt->valid_until - date);
  642. result = salt->salt;
  643. }
  644. }
  645. }
  646. if (cleanupNeeded) {
  647. size = salts.size();
  648. for (uint32_t i = 0; i < size; i++) {
  649. if (salts[i]->valid_until < date) {
  650. salts.erase(salts.begin() + i);
  651. size--;
  652. i--;
  653. }
  654. }
  655. }
  656. if (result == 0) {
  657. if (LOGS_ENABLED) DEBUG_D("dc%u valid salt not found", datacenterId);
  658. }
  659. return result;
  660. }
  661. void Datacenter::mergeServerSalts(TL_future_salts *futureSalts, bool media) {
  662. if (futureSalts->salts.empty()) {
  663. return;
  664. }
  665. std::vector<std::unique_ptr<TL_future_salt>> &salts = media ? mediaServerSalts : serverSalts;
  666. int32_t date = ConnectionsManager::getInstance(instanceNum).getCurrentTime();
  667. std::vector<int64_t> existingSalts;
  668. existingSalts.reserve(salts.size());
  669. size_t size = salts.size();
  670. for (uint32_t a = 0; a < size; a++) {
  671. existingSalts.push_back(salts[a]->salt);
  672. }
  673. bool added = false;
  674. size = futureSalts->salts.size();
  675. for (uint32_t a = 0; a < size; a++) {
  676. int64_t value = futureSalts->salts[a]->salt;
  677. if (std::find(existingSalts.begin(), existingSalts.end(), value) == existingSalts.end() && futureSalts->salts[a]->valid_until > date) {
  678. salts.push_back(std::unique_ptr<TL_future_salt>(std::move(futureSalts->salts[a])));
  679. added = true;
  680. }
  681. }
  682. if (added) {
  683. std::sort(salts.begin(), salts.end(), [](const std::unique_ptr<TL_future_salt> &x, const std::unique_ptr<TL_future_salt> &y) { return x->valid_since < y->valid_since; });
  684. }
  685. }
  686. void Datacenter::addServerSalt(std::unique_ptr<TL_future_salt> &serverSalt, bool media) {
  687. std::vector<std::unique_ptr<TL_future_salt>> &salts = media ? mediaServerSalts : serverSalts;
  688. size_t size = salts.size();
  689. for (uint32_t a = 0; a < size; a++) {
  690. if (salts[a]->salt == serverSalt->salt) {
  691. return;
  692. }
  693. }
  694. salts.push_back(std::move(serverSalt));
  695. std::sort(salts.begin(), salts.end(), [](const std::unique_ptr<TL_future_salt> &x, const std::unique_ptr<TL_future_salt> &y) { return x->valid_since < y->valid_since; });
  696. }
  697. bool Datacenter::containsServerSalt(int64_t value, bool media) {
  698. std::vector<std::unique_ptr<TL_future_salt>> &salts = media ? mediaServerSalts : serverSalts;
  699. size_t size = salts.size();
  700. for (uint32_t a = 0; a < size; a++) {
  701. if (salts[a]->salt == value) {
  702. return true;
  703. }
  704. }
  705. return false;
  706. }
  707. void Datacenter::suspendConnections(bool suspendPush) {
  708. if (genericConnection != nullptr) {
  709. genericConnection->suspendConnection();
  710. }
  711. if (suspendPush && pushConnection != nullptr) {
  712. pushConnection->suspendConnection();
  713. }
  714. if (genericMediaConnection != nullptr) {
  715. genericMediaConnection->suspendConnection();
  716. }
  717. if (tempConnection != nullptr) {
  718. tempConnection->suspendConnection();
  719. }
  720. for (auto & a : uploadConnection) {
  721. if (a != nullptr) {
  722. a->suspendConnection();
  723. }
  724. }
  725. for (auto & a : downloadConnection) {
  726. if (a != nullptr) {
  727. a->suspendConnection();
  728. }
  729. }
  730. }
  731. void Datacenter::getSessions(std::vector<int64_t> &sessions) {
  732. if (genericConnection != nullptr) {
  733. sessions.push_back(genericConnection->getSessionId());
  734. }
  735. if (genericMediaConnection != nullptr) {
  736. sessions.push_back(genericMediaConnection->getSessionId());
  737. }
  738. if (tempConnection != nullptr) {
  739. sessions.push_back(tempConnection->getSessionId());
  740. }
  741. for (auto & a : uploadConnection) {
  742. if (a != nullptr) {
  743. sessions.push_back(a->getSessionId());
  744. }
  745. }
  746. for (auto & a : downloadConnection) {
  747. if (a != nullptr) {
  748. sessions.push_back(a->getSessionId());
  749. }
  750. }
  751. for (auto & a : proxyConnection) {
  752. if (a != nullptr) {
  753. sessions.push_back(a->getSessionId());
  754. }
  755. }
  756. }
  757. void Datacenter::recreateSessions(HandshakeType type) {
  758. if (type == HandshakeTypeAll || type == HandshakeTypeTemp || type == HandshakeTypePerm) {
  759. if (genericConnection != nullptr) {
  760. genericConnection->recreateSession();
  761. }
  762. if (tempConnection != nullptr) {
  763. tempConnection->recreateSession();
  764. }
  765. for (auto & a : uploadConnection) {
  766. if (a != nullptr) {
  767. a->recreateSession();
  768. }
  769. }
  770. for (auto & a : proxyConnection) {
  771. if (a != nullptr) {
  772. a->recreateSession();
  773. }
  774. }
  775. }
  776. if (type == HandshakeTypeAll || type == HandshakeTypeMediaTemp || type == HandshakeTypePerm) {
  777. for (auto & a : downloadConnection) {
  778. if (a != nullptr) {
  779. a->recreateSession();
  780. }
  781. }
  782. if (genericMediaConnection != nullptr) {
  783. genericMediaConnection->recreateSession();
  784. }
  785. }
  786. }
  787. Connection *Datacenter::createProxyConnection(uint8_t num) {
  788. if (proxyConnection[num] == nullptr) {
  789. proxyConnection[num] = new Connection(this, ConnectionTypeProxy, num);
  790. }
  791. return proxyConnection[num];
  792. }
  793. Connection *Datacenter::createDownloadConnection(uint8_t num) {
  794. if (downloadConnection[num] == nullptr) {
  795. downloadConnection[num] = new Connection(this, ConnectionTypeDownload, num);
  796. }
  797. return downloadConnection[num];
  798. }
  799. Connection *Datacenter::createUploadConnection(uint8_t num) {
  800. if (uploadConnection[num] == nullptr) {
  801. uploadConnection[num] = new Connection(this, ConnectionTypeUpload, num);
  802. }
  803. return uploadConnection[num];
  804. }
  805. Connection *Datacenter::createGenericConnection() {
  806. if (genericConnection == nullptr) {
  807. genericConnection = new Connection(this, ConnectionTypeGeneric, 0);
  808. }
  809. return genericConnection;
  810. }
  811. Connection *Datacenter::createGenericMediaConnection() {
  812. if (genericMediaConnection == nullptr) {
  813. genericMediaConnection = new Connection(this, ConnectionTypeGenericMedia, 0);
  814. }
  815. return genericMediaConnection;
  816. }
  817. Connection *Datacenter::createPushConnection() {
  818. if (pushConnection == nullptr) {
  819. pushConnection = new Connection(this, ConnectionTypePush, 0);
  820. }
  821. return pushConnection;
  822. }
  823. Connection *Datacenter::createTempConnection() {
  824. if (tempConnection == nullptr) {
  825. tempConnection = new Connection(this, ConnectionTypeTemp, 0);
  826. }
  827. return tempConnection;
  828. }
  829. uint32_t Datacenter::getDatacenterId() {
  830. return datacenterId;
  831. }
  832. bool Datacenter::isHandshakingAny() {
  833. return !handshakes.empty();
  834. }
  835. bool Datacenter::isHandshaking(bool media) {
  836. if (handshakes.empty()) {
  837. return false;
  838. }
  839. if (media && (isCdnDatacenter || !PFS_ENABLED)) {
  840. media = false;
  841. }
  842. for (auto & iter : handshakes) {
  843. Handshake *handshake = iter.get();
  844. if (handshake->getType() == HandshakeTypePerm || (media && handshake->getType() == HandshakeTypeMediaTemp) || (!media && handshake->getType() != HandshakeTypeMediaTemp)) {
  845. return true;
  846. }
  847. }
  848. return false;
  849. }
  850. bool Datacenter::isHandshaking(HandshakeType type) {
  851. if (handshakes.empty()) {
  852. return false;
  853. }
  854. for (auto & iter : handshakes) {
  855. Handshake *handshake = iter.get();
  856. if (handshake->getType() == type) {
  857. return true;
  858. }
  859. }
  860. return false;
  861. }
  862. void Datacenter::beginHandshake(HandshakeType handshakeType, bool reconnect) {
  863. if (handshakeType == HandshakeTypeCurrent) {
  864. for (auto & iter : handshakes) {
  865. Handshake *handshake = iter.get();
  866. handshake->beginHandshake(reconnect);
  867. }
  868. } else {
  869. if (authKeyPerm == nullptr) {
  870. if (!isHandshaking(HandshakeTypePerm)) {
  871. auto handshake = new Handshake(this, HandshakeTypePerm, this);
  872. handshakes.push_back(std::unique_ptr<Handshake>(handshake));
  873. handshake->beginHandshake(reconnect);
  874. }
  875. } else if (PFS_ENABLED) {
  876. if (handshakeType == HandshakeTypeAll || handshakeType == HandshakeTypeTemp) {
  877. if (!isHandshaking(HandshakeTypeTemp)) {
  878. auto handshake = new Handshake(this, HandshakeTypeTemp, this);
  879. handshakes.push_back(std::unique_ptr<Handshake>(handshake));
  880. handshake->beginHandshake(reconnect);
  881. }
  882. }
  883. if ((handshakeType == HandshakeTypeAll || handshakeType == HandshakeTypeMediaTemp) && hasMediaAddress()) {
  884. if (!isHandshaking(HandshakeTypeMediaTemp)) {
  885. auto handshake = new Handshake(this, HandshakeTypeMediaTemp, this);
  886. handshakes.push_back(std::unique_ptr<Handshake>(handshake));
  887. handshake->beginHandshake(reconnect);
  888. }
  889. }
  890. }
  891. }
  892. }
  893. void Datacenter::onHandshakeConnectionClosed(Connection *connection) {
  894. if (handshakes.empty()) {
  895. return;
  896. }
  897. bool media = connection->getConnectionType() == ConnectionTypeGenericMedia;
  898. for (auto & iter : handshakes) {
  899. Handshake *handshake = iter.get();
  900. if ((media && handshake->getType() == HandshakeTypeMediaTemp) || (!media && handshake->getType() != HandshakeTypeMediaTemp)) {
  901. handshake->onHandshakeConnectionClosed();
  902. }
  903. }
  904. }
  905. void Datacenter::onHandshakeConnectionConnected(Connection *connection) {
  906. if (handshakes.empty()) {
  907. return;
  908. }
  909. bool media = connection->getConnectionType() == ConnectionTypeGenericMedia;
  910. for (auto & iter : handshakes) {
  911. Handshake *handshake = iter.get();
  912. if ((media && handshake->getType() == HandshakeTypeMediaTemp) || (!media && handshake->getType() != HandshakeTypeMediaTemp)) {
  913. handshake->onHandshakeConnectionConnected();
  914. }
  915. }
  916. }
  917. void Datacenter::aesIgeEncryption(uint8_t *buffer, uint8_t *key, uint8_t *iv, bool encrypt, bool changeIv, uint32_t length) {
  918. uint8_t *ivBytes = iv;
  919. if (!changeIv) {
  920. ivBytes = new uint8_t[32];
  921. memcpy(ivBytes, iv, 32);
  922. }
  923. AES_KEY akey;
  924. if (!encrypt) {
  925. AES_set_decrypt_key(key, 32 * 8, &akey);
  926. AES_ige_encrypt(buffer, buffer, length, &akey, ivBytes, AES_DECRYPT);
  927. } else {
  928. AES_set_encrypt_key(key, 32 * 8, &akey);
  929. AES_ige_encrypt(buffer, buffer, length, &akey, ivBytes, AES_ENCRYPT);
  930. }
  931. if (!changeIv) {
  932. delete [] ivBytes;
  933. }
  934. }
  935. void Datacenter::processHandshakeResponse(bool media, TLObject *message, int64_t messageId) {
  936. if (handshakes.empty()) {
  937. return;
  938. }
  939. for (auto & iter : handshakes) {
  940. Handshake *handshake = iter.get();
  941. if ((media && handshake->getType() == HandshakeTypeMediaTemp) || (!media && handshake->getType() != HandshakeTypeMediaTemp)) {
  942. handshake->processHandshakeResponse(message, messageId);
  943. }
  944. }
  945. }
  946. TLObject *Datacenter::getCurrentHandshakeRequest(bool media) {
  947. if (handshakes.empty()) {
  948. return nullptr;
  949. }
  950. for (auto & iter : handshakes) {
  951. Handshake *handshake = iter.get();
  952. if ((media && handshake->getType() == HandshakeTypeMediaTemp) || (!media && handshake->getType() != HandshakeTypeMediaTemp)) {
  953. return handshake->getCurrentHandshakeRequest();
  954. }
  955. }
  956. return nullptr;
  957. }
  958. inline void generateMessageKey(int32_t instanceNum, uint8_t *authKey, uint8_t *messageKey, uint8_t *result, bool incoming, int mtProtoVersion) {
  959. uint32_t x = incoming ? 8 : 0;
  960. thread_local static uint8_t sha[68];
  961. switch (mtProtoVersion) {
  962. case 2:
  963. SHA256_Init(&sha256Ctx);
  964. SHA256_Update(&sha256Ctx, messageKey, 16);
  965. SHA256_Update(&sha256Ctx, authKey + x, 36);
  966. SHA256_Final(sha, &sha256Ctx);
  967. SHA256_Init(&sha256Ctx);
  968. SHA256_Update(&sha256Ctx, authKey + 40 + x, 36);
  969. SHA256_Update(&sha256Ctx, messageKey, 16);
  970. SHA256_Final(sha + 32, &sha256Ctx);
  971. memcpy(result, sha, 8);
  972. memcpy(result + 8, sha + 32 + 8, 16);
  973. memcpy(result + 8 + 16, sha + 24, 8);
  974. memcpy(result + 32, sha + 32, 8);
  975. memcpy(result + 32 + 8, sha + 8, 16);
  976. memcpy(result + 32 + 8 + 16, sha + 32 + 24, 8);
  977. break;
  978. default:
  979. memcpy(sha + 20, messageKey, 16);
  980. memcpy(sha + 20 + 16, authKey + x, 32);
  981. SHA1(sha + 20, 48, sha);
  982. memcpy(result, sha, 8);
  983. memcpy(result + 32, sha + 8, 12);
  984. memcpy(sha + 20, authKey + 32 + x, 16);
  985. memcpy(sha + 20 + 16, messageKey, 16);
  986. memcpy(sha + 20 + 16 + 16, authKey + 48 + x, 16);
  987. SHA1(sha + 20, 48, sha);
  988. memcpy(result + 8, sha + 8, 12);
  989. memcpy(result + 32 + 12, sha, 8);
  990. memcpy(sha + 20, authKey + 64 + x, 32);
  991. memcpy(sha + 20 + 32, messageKey, 16);
  992. SHA1(sha + 20, 48, sha);
  993. memcpy(result + 8 + 12, sha + 4, 12);
  994. memcpy(result + 32 + 12 + 8, sha + 16, 4);
  995. memcpy(sha + 20, messageKey, 16);
  996. memcpy(sha + 20 + 16, authKey + 96 + x, 32);
  997. SHA1(sha + 20, 48, sha);
  998. memcpy(result + 32 + 12 + 8 + 4, sha, 8);
  999. break;
  1000. }
  1001. }
  1002. ByteArray *Datacenter::getAuthKey(ConnectionType connectionType, bool perm, int64_t *authKeyId, int32_t allowPendingKey) {
  1003. bool usePermKey = isCdnDatacenter || perm || !PFS_ENABLED;
  1004. if (usePermKey) {
  1005. if (authKeyId != nullptr) {
  1006. *authKeyId = authKeyPermId;
  1007. }
  1008. return authKeyPerm;
  1009. } else {
  1010. bool media = Connection::isMediaConnectionType(connectionType) && hasMediaAddress();
  1011. ByteArray *authKeyPending = nullptr;
  1012. int64_t authKeyPendingId = 0;
  1013. for (auto & iter : handshakes) {
  1014. Handshake *handshake = iter.get();
  1015. if ((media && handshake->getType() == HandshakeTypeMediaTemp) || (!media && handshake->getType() == HandshakeTypeTemp)) {
  1016. authKeyPending = handshake->getPendingAuthKey();
  1017. authKeyPendingId = handshake->getPendingAuthKeyId();
  1018. break;
  1019. }
  1020. }
  1021. if ((allowPendingKey & 1) != 0 && authKeyPending != nullptr) {
  1022. if (authKeyId != nullptr) {
  1023. *authKeyId = authKeyPendingId;
  1024. }
  1025. return authKeyPending;
  1026. } else if (media) {
  1027. if (authKeyId != nullptr) {
  1028. *authKeyId = authKeyMediaTempId;
  1029. }
  1030. return authKeyMediaTemp;
  1031. } else {
  1032. if (authKeyId != nullptr) {
  1033. *authKeyId = authKeyTempId;
  1034. }
  1035. return authKeyTemp;
  1036. }
  1037. }
  1038. }
  1039. NativeByteBuffer *Datacenter::createRequestsData(std::vector<std::unique_ptr<NetworkMessage>> &requests, int32_t *quickAckId, Connection *connection, bool pfsInit) {
  1040. int64_t authKeyId;
  1041. ByteArray *authKey = getAuthKey(connection->getConnectionType(), pfsInit, &authKeyId, 1);
  1042. if (authKey == nullptr) {
  1043. return nullptr;
  1044. }
  1045. int64_t messageId;
  1046. TLObject *messageBody;
  1047. bool freeMessageBody = false;
  1048. int32_t messageSeqNo;
  1049. if (requests.size() == 1) {
  1050. NetworkMessage *networkMessage = requests[0].get();
  1051. if (networkMessage->message->outgoingBody != nullptr) {
  1052. messageBody = networkMessage->message->outgoingBody;
  1053. } else {
  1054. messageBody = networkMessage->message->body.get();
  1055. }
  1056. if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) send message (session: 0x%" PRIx64 ", seqno: %d, messageid: 0x%" PRIx64 "): %s(%p)", connection, instanceNum, datacenterId, connection->getConnectionType(), (uint64_t) connection->getSessionId(), networkMessage->message->seqno, (uint64_t) networkMessage->message->msg_id, typeid(*messageBody).name(), messageBody);
  1057. auto messageTime = (int64_t) (networkMessage->message->msg_id / 4294967296.0 * 1000);
  1058. int64_t currentTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMillis() + (int64_t) ConnectionsManager::getInstance(instanceNum).getTimeDifference() * 1000;
  1059. if (!pfsInit && (networkMessage->forceContainer || messageTime < currentTime - 30000 || messageTime > currentTime + 25000)) {
  1060. if (LOGS_ENABLED) DEBUG_D("wrap message in container");
  1061. auto messageContainer = new TL_msg_container();
  1062. messageContainer->messages.push_back(std::move(networkMessage->message));
  1063. messageId = ConnectionsManager::getInstance(instanceNum).generateMessageId();
  1064. messageBody = messageContainer;
  1065. messageSeqNo = connection->generateMessageSeqNo(false);
  1066. freeMessageBody = true;
  1067. } else {
  1068. messageId = networkMessage->message->msg_id;
  1069. messageSeqNo = networkMessage->message->seqno;
  1070. }
  1071. } else {
  1072. if (LOGS_ENABLED) DEBUG_D("start write messages to container");
  1073. auto messageContainer = new TL_msg_container();
  1074. size_t count = requests.size();
  1075. for (uint32_t a = 0; a < count; a++) {
  1076. NetworkMessage *networkMessage = requests[a].get();
  1077. if (networkMessage->message->outgoingBody != nullptr) {
  1078. messageBody = networkMessage->message->outgoingBody;
  1079. } else {
  1080. messageBody = networkMessage->message->body.get();
  1081. }
  1082. if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) send message (session: 0x%" PRIx64 ", seqno: %d, messageid: 0x%" PRIx64 "): %s(%p)", connection, instanceNum, datacenterId, connection->getConnectionType(), (uint64_t) connection->getSessionId(), networkMessage->message->seqno, (uint64_t) networkMessage->message->msg_id, typeid(*messageBody).name(), messageBody);
  1083. messageContainer->messages.push_back(std::unique_ptr<TL_message>(std::move(networkMessage->message)));
  1084. }
  1085. messageId = ConnectionsManager::getInstance(instanceNum).generateMessageId();
  1086. messageBody = messageContainer;
  1087. freeMessageBody = true;
  1088. messageSeqNo = connection->generateMessageSeqNo(false);
  1089. }
  1090. int32_t mtProtoVersion;
  1091. if (pfsInit) {
  1092. mtProtoVersion = 1;
  1093. } else {
  1094. mtProtoVersion = 2;
  1095. }
  1096. uint32_t messageSize = messageBody->getObjectSize();
  1097. uint32_t additionalSize = (32 + messageSize) % 16;
  1098. if (additionalSize != 0) {
  1099. additionalSize = 16 - additionalSize;
  1100. }
  1101. if (mtProtoVersion == 2) {
  1102. uint8_t index;
  1103. RAND_bytes(&index, 1);
  1104. additionalSize += (2 + (index % 14)) * 16;
  1105. }
  1106. NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(24 + 32 + messageSize + additionalSize);
  1107. buffer->writeInt64(authKeyId);
  1108. buffer->position(24);
  1109. if (pfsInit) {
  1110. int64_t value;
  1111. RAND_bytes((uint8_t *) &value, 8);
  1112. buffer->writeInt64(value);
  1113. RAND_bytes((uint8_t *) &value, 8);
  1114. buffer->writeInt64(value);
  1115. } else {
  1116. buffer->writeInt64(getServerSalt(Connection::isMediaConnectionType(connection->getConnectionType())));
  1117. buffer->writeInt64(connection->getSessionId());
  1118. }
  1119. buffer->writeInt64(messageId);
  1120. buffer->writeInt32(messageSeqNo);
  1121. buffer->writeInt32(messageSize);
  1122. messageBody->serializeToStream(buffer);
  1123. if (freeMessageBody) {
  1124. delete messageBody;
  1125. }
  1126. if (additionalSize != 0) {
  1127. RAND_bytes(buffer->bytes() + 24 + 32 + messageSize, additionalSize);
  1128. }
  1129. thread_local static uint8_t messageKey[96];
  1130. switch (mtProtoVersion) {
  1131. case 2: {
  1132. SHA256_Init(&sha256Ctx);
  1133. SHA256_Update(&sha256Ctx, authKey->bytes + 88, 32);
  1134. SHA256_Update(&sha256Ctx, buffer->bytes() + 24, 32 + messageSize + additionalSize);
  1135. SHA256_Final(messageKey, &sha256Ctx);
  1136. if (quickAckId != nullptr) {
  1137. *quickAckId = (((messageKey[0] & 0xff)) |
  1138. ((messageKey[1] & 0xff) << 8) |
  1139. ((messageKey[2] & 0xff) << 16) |
  1140. ((messageKey[3] & 0xff) << 24)) & 0x7fffffff;
  1141. }
  1142. break;
  1143. }
  1144. default: {
  1145. SHA1(buffer->bytes() + 24, 32 + messageSize, messageKey + 4);
  1146. if (quickAckId != nullptr) {
  1147. *quickAckId = (((messageKey[4] & 0xff)) |
  1148. ((messageKey[5] & 0xff) << 8) |
  1149. ((messageKey[6] & 0xff) << 16) |
  1150. ((messageKey[7] & 0xff) << 24)) & 0x7fffffff;
  1151. }
  1152. break;
  1153. }
  1154. }
  1155. memcpy(buffer->bytes() + 8, messageKey + 8, 16);
  1156. generateMessageKey(instanceNum, authKey->bytes, messageKey + 8, messageKey + 32, false, mtProtoVersion);
  1157. aesIgeEncryption(buffer->bytes() + 24, messageKey + 32, messageKey + 64, true, false, buffer->limit() - 24);
  1158. return buffer;
  1159. }
  1160. bool Datacenter::decryptServerResponse(int64_t keyId, uint8_t *key, uint8_t *data, uint32_t length, Connection *connection) {
  1161. int64_t authKeyId;
  1162. ByteArray *authKey = getAuthKey(connection->getConnectionType(), false, &authKeyId, 1);
  1163. if (authKey == nullptr) {
  1164. return false;
  1165. }
  1166. bool error = authKeyId != keyId;
  1167. thread_local static uint8_t messageKey[96];
  1168. generateMessageKey(instanceNum, authKey->bytes, key, messageKey + 32, true, 2);
  1169. aesIgeEncryption(data, messageKey + 32, messageKey + 64, false, false, length);
  1170. uint32_t messageLength;
  1171. memcpy(&messageLength, data + 28, sizeof(uint32_t));
  1172. uint32_t paddingLength = length - (messageLength + 32);
  1173. error |= (messageLength > length - 32);
  1174. error |= (paddingLength < 12);
  1175. error |= (paddingLength > 1024);
  1176. SHA256_Init(&sha256Ctx);
  1177. SHA256_Update(&sha256Ctx, authKey->bytes + 88 + 8, 32);
  1178. SHA256_Update(&sha256Ctx, data, length);
  1179. SHA256_Final(messageKey, &sha256Ctx);
  1180. for (uint32_t i = 0; i < 16; i++) {
  1181. error |= (messageKey[i + 8] != key[i]);
  1182. }
  1183. return !error;
  1184. }
  1185. bool Datacenter::hasPermanentAuthKey() {
  1186. return authKeyPerm != nullptr;
  1187. }
  1188. int64_t Datacenter::getPermanentAuthKeyId() {
  1189. return authKeyPermId;
  1190. }
  1191. bool Datacenter::hasAuthKey(ConnectionType connectionType, int32_t allowPendingKey) {
  1192. return getAuthKey(connectionType, false, nullptr, allowPendingKey) != nullptr;
  1193. }
  1194. Connection *Datacenter::createConnectionByType(uint32_t connectionType) {
  1195. uint8_t connectionNum = (uint8_t) (connectionType >> 16);
  1196. connectionType = connectionType & 0x0000ffff;
  1197. switch (connectionType) {
  1198. case ConnectionTypeGeneric:
  1199. return createGenericConnection();
  1200. case ConnectionTypeGenericMedia:
  1201. return createGenericMediaConnection();
  1202. case ConnectionTypeDownload:
  1203. return createDownloadConnection(connectionNum);
  1204. case ConnectionTypeUpload:
  1205. return createUploadConnection(connectionNum);
  1206. case ConnectionTypePush:
  1207. return createPushConnection();
  1208. case ConnectionTypeTemp:
  1209. return createTempConnection();
  1210. case ConnectionTypeProxy:
  1211. return createProxyConnection(connectionNum);
  1212. default:
  1213. return nullptr;
  1214. }
  1215. }
  1216. Connection *Datacenter::getProxyConnection(uint8_t num, bool create, bool connect) {
  1217. ByteArray *authKey = getAuthKey(ConnectionTypeProxy, false, nullptr, 1);
  1218. if (authKey == nullptr) {
  1219. return nullptr;
  1220. }
  1221. if (create) {
  1222. Connection *connection = createProxyConnection(num);
  1223. if (connect) {
  1224. connection->connect();
  1225. }
  1226. }
  1227. return proxyConnection[num];
  1228. }
  1229. Connection *Datacenter::getDownloadConnection(uint8_t num, bool create) {
  1230. ByteArray *authKey = getAuthKey(ConnectionTypeDownload, false, nullptr, 0);
  1231. if (authKey == nullptr) {
  1232. return nullptr;
  1233. }
  1234. if (create) {
  1235. createDownloadConnection(num)->connect();
  1236. }
  1237. return downloadConnection[num];
  1238. }
  1239. Connection *Datacenter::getUploadConnection(uint8_t num, bool create) {
  1240. ByteArray *authKey = getAuthKey(ConnectionTypeUpload, false, nullptr, 0);
  1241. if (authKey == nullptr) {
  1242. return nullptr;
  1243. }
  1244. if (create) {
  1245. createUploadConnection(num)->connect();
  1246. }
  1247. return uploadConnection[num];
  1248. }
  1249. Connection *Datacenter::getGenericConnection(bool create, int32_t allowPendingKey) {
  1250. ByteArray *authKey = getAuthKey(ConnectionTypeGeneric, false, nullptr, allowPendingKey);
  1251. if (authKey == nullptr) {
  1252. return nullptr;
  1253. }
  1254. if (create) {
  1255. createGenericConnection()->connect();
  1256. }
  1257. return genericConnection;
  1258. }
  1259. Connection *Datacenter::getGenericMediaConnection(bool create, int32_t allowPendingKey) {
  1260. ByteArray *authKey = getAuthKey(ConnectionTypeGenericMedia, false, nullptr, allowPendingKey);
  1261. if (authKey == nullptr) {
  1262. return nullptr;
  1263. }
  1264. if (create) {
  1265. createGenericMediaConnection()->connect();
  1266. }
  1267. return genericMediaConnection;
  1268. }
  1269. Connection *Datacenter::getPushConnection(bool create) {
  1270. ByteArray *authKey = getAuthKey(ConnectionTypePush, false, nullptr, 0);
  1271. if (authKey == nullptr) {
  1272. return nullptr;
  1273. }
  1274. if (create) {
  1275. createPushConnection()->connect();
  1276. }
  1277. return pushConnection;
  1278. }
  1279. Connection *Datacenter::getTempConnection(bool create) {
  1280. ByteArray *authKey = getAuthKey(ConnectionTypeTemp, false, nullptr, 1);
  1281. if (authKey == nullptr) {
  1282. return nullptr;
  1283. }
  1284. if (create) {
  1285. createTempConnection()->connect();
  1286. }
  1287. return tempConnection;
  1288. }
  1289. Connection *Datacenter::getConnectionByType(uint32_t connectionType, bool create, int32_t allowPendingKey) {
  1290. uint8_t connectionNum = (uint8_t) (connectionType >> 16);
  1291. connectionType = connectionType & 0x0000ffff;
  1292. switch (connectionType) {
  1293. case ConnectionTypeGeneric:
  1294. return getGenericConnection(create, allowPendingKey);
  1295. case ConnectionTypeGenericMedia:
  1296. return getGenericMediaConnection(create, allowPendingKey);
  1297. case ConnectionTypeDownload:
  1298. return getDownloadConnection(connectionNum, create);
  1299. case ConnectionTypeUpload:
  1300. return getUploadConnection(connectionNum, create);
  1301. case ConnectionTypePush:
  1302. return getPushConnection(create);
  1303. case ConnectionTypeTemp:
  1304. return getTempConnection(create);
  1305. case ConnectionTypeProxy:
  1306. return getProxyConnection(connectionNum, create, create);
  1307. default:
  1308. return nullptr;
  1309. }
  1310. }
  1311. void Datacenter::onHandshakeComplete(Handshake *handshake, int64_t keyId, ByteArray *authKey, int32_t timeDifference) {
  1312. HandshakeType type = handshake->getType();
  1313. for (auto iter = handshakes.begin(); iter != handshakes.end(); iter++) {
  1314. if (iter->get() == handshake) {
  1315. handshakes.erase(iter);
  1316. if (type == HandshakeTypePerm) {
  1317. authKeyPermId = keyId;
  1318. authKeyPerm = authKey;
  1319. if (!isCdnDatacenter && PFS_ENABLED) {
  1320. beginHandshake(HandshakeTypeAll, false);
  1321. }
  1322. } else {
  1323. if (type == HandshakeTypeTemp) {
  1324. authKeyTempId = keyId;
  1325. authKeyTemp = authKey;
  1326. lastInitVersion = 0;
  1327. } else if (type == HandshakeTypeMediaTemp) {
  1328. authKeyMediaTempId = keyId;
  1329. authKeyMediaTemp = authKey;
  1330. lastInitMediaVersion = 0;
  1331. }
  1332. }
  1333. ConnectionsManager::getInstance(instanceNum).onDatacenterHandshakeComplete(this, type, timeDifference);
  1334. break;
  1335. }
  1336. }
  1337. }
  1338. void Datacenter::exportAuthorization() {
  1339. if (exportingAuthorization || isCdnDatacenter) {
  1340. return;
  1341. }
  1342. exportingAuthorization = true;
  1343. auto request = new TL_auth_exportAuthorization();
  1344. request->dc_id = datacenterId;
  1345. if (LOGS_ENABLED) DEBUG_D("dc%u begin export authorization", datacenterId);
  1346. ConnectionsManager::getInstance(instanceNum).sendRequest(request, [&](TLObject *response, TL_error *error, int32_t networkType, int64_t responseTime) {
  1347. if (error == nullptr) {
  1348. auto res = (TL_auth_exportedAuthorization *) response;
  1349. auto request2 = new TL_auth_importAuthorization();
  1350. request2->bytes = std::move(res->bytes);
  1351. request2->id = res->id;
  1352. if (LOGS_ENABLED) DEBUG_D("dc%u begin import authorization", datacenterId);
  1353. ConnectionsManager::getInstance(instanceNum).sendRequest(request2, [&](TLObject *response2, TL_error *error2, int32_t networkType, int64_t responseTime) {
  1354. if (error2 == nullptr) {
  1355. authorized = true;
  1356. ConnectionsManager::getInstance(instanceNum).onDatacenterExportAuthorizationComplete(this);
  1357. } else {
  1358. if (LOGS_ENABLED) DEBUG_D("dc%u failed import authorization", datacenterId);
  1359. }
  1360. exportingAuthorization = false;
  1361. }, nullptr, RequestFlagEnableUnauthorized | RequestFlagWithoutLogin, datacenterId, ConnectionTypeGeneric, true);
  1362. } else {
  1363. if (LOGS_ENABLED) DEBUG_D("dc%u failed export authorization", datacenterId);
  1364. exportingAuthorization = false;
  1365. }
  1366. }, nullptr, 0, DEFAULT_DATACENTER_ID, ConnectionTypeGeneric, true);
  1367. }
  1368. bool Datacenter::isExportingAuthorization() {
  1369. return exportingAuthorization;
  1370. }
  1371. bool Datacenter::hasMediaAddress() {
  1372. std::vector<TcpAddress> *addresses;
  1373. int strategy = ConnectionsManager::getInstance(instanceNum).getIpStratagy();
  1374. if (strategy == USE_IPV6_ONLY) {
  1375. addresses = &addressesIpv6Download;
  1376. } else {
  1377. addresses = &addressesIpv4Download;
  1378. }
  1379. return !addresses->empty();
  1380. }
  1381. void Datacenter::resetInitVersion() {
  1382. lastInitVersion = 0;
  1383. lastInitMediaVersion = 0;
  1384. }
  1385. bool Datacenter::isRepeatCheckingAddresses() {
  1386. bool b = repeatCheckingAddresses;
  1387. repeatCheckingAddresses = false;
  1388. return b;
  1389. }
  1390. TL_help_configSimple *Datacenter::decodeSimpleConfig(NativeByteBuffer *buffer) {
  1391. TL_help_configSimple *result = nullptr;
  1392. if (buffer->limit() < 256) {
  1393. return result;
  1394. }
  1395. static std::string public_key =
  1396. "-----BEGIN RSA PUBLIC KEY-----\n"
  1397. "MIIBCgKCAQEAyr+18Rex2ohtVy8sroGPBwXD3DOoKCSpjDqYoXgCqB7ioln4eDCF\n"
  1398. "fOBUlfXUEvM/fnKCpF46VkAftlb4VuPDeQSS/ZxZYEGqHaywlroVnXHIjgqoxiAd\n"
  1399. "192xRGreuXIaUKmkwlM9JID9WS2jUsTpzQ91L8MEPLJ/4zrBwZua8W5fECwCCh2c\n"
  1400. "9G5IzzBm+otMS/YKwmR1olzRCyEkyAEjXWqBI9Ftv5eG8m0VkBzOG655WIYdyV0H\n"
  1401. "fDK/NWcvGqa0w/nriMD6mDjKOryamw0OP9QuYgMN0C9xMW9y8SmP4h92OAWodTYg\n"
  1402. "Y1hZCxdv6cs5UnW9+PWvS+WIbkh+GaWYxwIDAQAB\n"
  1403. "-----END RSA PUBLIC KEY-----";
  1404. BIO *keyBio = BIO_new(BIO_s_mem());
  1405. BIO_write(keyBio, public_key.c_str(), (int) public_key.length());
  1406. RSA *rsaKey = PEM_read_bio_RSAPublicKey(keyBio, nullptr, nullptr, nullptr);
  1407. if (rsaKey == nullptr) {
  1408. if (rsaKey == nullptr) {
  1409. if (LOGS_ENABLED) DEBUG_E("Invalid rsa public key");
  1410. return nullptr;
  1411. }
  1412. }
  1413. BIGNUM x, y;
  1414. uint8_t *bytes = buffer->bytes();
  1415. BN_CTX *bnContext = BN_CTX_new();
  1416. BN_init(&x);
  1417. BN_init(&y);
  1418. BN_bin2bn(bytes, 256, &x);
  1419. if (BN_mod_exp(&y, &x, rsaKey->e, rsaKey->n, bnContext) == 1) {
  1420. unsigned l = 256 - BN_num_bytes(&y);
  1421. memset(bytes, 0, l);
  1422. if (BN_bn2bin(&y, bytes + l) == 256 - l) {
  1423. AES_KEY aeskey;
  1424. unsigned char iv[16];
  1425. memcpy(iv, bytes + 16, 16);
  1426. AES_set_decrypt_key(bytes, 256, &aeskey);
  1427. AES_cbc_encrypt(bytes + 32, bytes + 32, 256 - 32, &aeskey, iv, AES_DECRYPT);
  1428. EVP_MD_CTX ctx;
  1429. unsigned char sha256_out[32];
  1430. unsigned olen = 0;
  1431. EVP_MD_CTX_init(&ctx);
  1432. EVP_DigestInit_ex(&ctx, EVP_sha256(), NULL);
  1433. EVP_DigestUpdate(&ctx, bytes + 32, 256 - 32 - 16);
  1434. EVP_DigestFinal_ex(&ctx, sha256_out, &olen);
  1435. EVP_MD_CTX_cleanup(&ctx);
  1436. if (olen == 32) {
  1437. if (memcmp(bytes + 256 - 16, sha256_out, 16) == 0) {
  1438. unsigned data_len = *(unsigned *) (bytes + 32);
  1439. if (data_len && data_len <= 256 - 32 - 16 && !(data_len & 3)) {
  1440. buffer->position(32 + 4);
  1441. bool error = false;
  1442. result = TL_help_configSimple::TLdeserialize(buffer, buffer->readUint32(&error), 0, error);
  1443. if (error) {
  1444. if (result != nullptr) {
  1445. delete result;
  1446. result = nullptr;
  1447. }
  1448. }
  1449. } else {
  1450. if (LOGS_ENABLED) DEBUG_E("TL data length field invalid - %d", data_len);
  1451. }
  1452. } else {
  1453. if (LOGS_ENABLED) DEBUG_E("RSA signature check FAILED (SHA256 mismatch)");
  1454. }
  1455. }
  1456. }
  1457. }
  1458. BN_CTX_free(bnContext);
  1459. BN_free(&x);
  1460. BN_free(&y);
  1461. RSA_free(rsaKey);
  1462. BIO_free(keyBio);
  1463. return result;
  1464. }