resolver.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. #include "cppcodec/base32_rfc4648.hpp"
  2. #include "resolver.h"
  3. #include "funcs.h"
  4. #include "HTTPheaders.h"
  5. #include <QTcpSocket>
  6. #include <QRegularExpression>
  7. #include <QJsonArray>
  8. #include <QDateTime>
  9. #include <QHostInfo>
  10. #include <QDebug>
  11. #include <QFile>
  12. #ifdef _WIN32
  13. #include <ws2tcpip.h>
  14. #else
  15. #include <arpa/inet.h>
  16. #endif
  17. constexpr int LIMIT_TO_READ = 2048;
  18. Resolver::Resolver(const QString& addr, quint16 port, QObject* parent) :
  19. QObject(parent),
  20. m_tcpServer(new QTcpServer),
  21. m_address(addr),
  22. m_port(port),
  23. m_NoApi(false),
  24. m_NoHttp(false),
  25. m_NoResolve(false)
  26. {
  27. if (!m_tcpServer->listen(m_address, m_port)) {
  28. throw "Server not binded";
  29. }
  30. qInfo().noquote() << "<-" << m_tcpServer->serverAddress().toString() + " : " +
  31. QString::number(m_tcpServer->serverPort()) << "[" + QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz") + "]";
  32. connect(m_tcpServer, SIGNAL(newConnection()), this, SLOT(slotNewUser()));
  33. }
  34. void Resolver::disableAPI()
  35. {
  36. m_NoApi = true;
  37. }
  38. void Resolver::disableWebPage()
  39. {
  40. m_NoHttp = true;
  41. }
  42. void Resolver::disableResolv()
  43. {
  44. m_NoResolve = true;
  45. http::HTML_PAGE.replace("IPv6 address or domain", "IPv6 address or meship domain");
  46. }
  47. void Resolver::slotNewUser()
  48. {
  49. if (!m_tcpServer->isListening()) return;
  50. QTcpSocket* clientSocket = m_tcpServer->nextPendingConnection();
  51. connect (clientSocket, SIGNAL(readyRead()), this, SLOT(slotReadyClient()));
  52. connect (clientSocket, SIGNAL(disconnected()), clientSocket, SLOT(deleteLater()));
  53. }
  54. void Resolver::slotReadyClient()
  55. {
  56. QTcpSocket* clientSocket = static_cast<QTcpSocket*>(sender());
  57. QString req = clientSocket->read(LIMIT_TO_READ);
  58. qInfo().noquote() << "\n->" << clientSocket->peerAddress().toString()
  59. << "[" + QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz") + "]";
  60. QSharedPointer<QTextStream> ts(new QTextStream(clientSocket));
  61. if (m_NoHttp and (req.startsWith("HEAD /") or req.startsWith("GET /toConverting") or req.startsWith("GET / ")))
  62. {
  63. qInfo().noquote() << " └ HTML (dropped)";
  64. *ts << http::HEADER_REJECT;
  65. }
  66. else if (m_NoApi and req.startsWith("GET /api/"))
  67. {
  68. qInfo().noquote() << " └ API (dropped)";
  69. JsonAnswer a;
  70. a.setValue("status", false);
  71. *ts << a.result();
  72. }
  73. else if (req.startsWith("GET /api/"))
  74. {
  75. qInfo().noquote() << " └ API";
  76. req.contains("toConverting=") ?
  77. processPage(req, ts, false) :
  78. startPage(ts, false);
  79. }
  80. else if (req.startsWith("GET /"))
  81. {
  82. qInfo().noquote() << " └ HTML";
  83. req.contains("toConverting=") ?
  84. processPage(req, ts, true) :
  85. startPage(ts, true);
  86. }
  87. else if (req.startsWith("HEAD /"))
  88. {
  89. qInfo().noquote() << " └ HEAD request";
  90. *ts << http::HEADER_OK;
  91. }
  92. clientSocket->close();
  93. }
  94. void Resolver::convertStrToRaw(const QString &str, Address &array)
  95. {
  96. inet_pton(AF_INET6, str.toUtf8(), (void*)array.data());
  97. }
  98. QString Resolver::getBase32(const Address &rawAddr)
  99. {
  100. return cppcodec::base32_rfc4648::encode(rawAddr.data(), ADDRIPV6_SIZE).c_str();
  101. }
  102. QString Resolver::decodeMeshToIP(const QString &meshname)
  103. {
  104. std::string mesh = pickupStringForMeshname(meshname.toStdString()) + "======"; // 6 паддингов - норма для IPv6 адреса
  105. std::vector<uint8_t> raw;
  106. try {
  107. raw = cppcodec::base32_rfc4648::decode(mesh);
  108. } catch (cppcodec::padding_error const&) {
  109. return QString();
  110. } catch (cppcodec::symbol_error const&) {
  111. return QString();
  112. }
  113. Address rawAddr;
  114. for(int i = 0; i < 16; ++i)
  115. rawAddr[i] = raw[i];
  116. return getAddress(rawAddr);
  117. }
  118. std::string Resolver::pickupStringForMeshname(std::string str)
  119. {
  120. bool dot = false;
  121. std::string::iterator delend;
  122. for (auto it = str.begin(); it != str.end(); it++)
  123. {
  124. *it = toupper(*it); // делаем все буквы заглавными для обработки
  125. if(*it == '.') {
  126. delend = it;
  127. dot = true;
  128. }
  129. }
  130. if (dot)
  131. for (auto it = str.end(); it != delend; it--)
  132. str.pop_back(); // удаляем доменную зону
  133. return str;
  134. }
  135. QString Resolver::getAddress(const Address& rawAddr)
  136. {
  137. char ipStrBuf[46];
  138. inet_ntop(AF_INET6, rawAddr.data(), ipStrBuf, 46);
  139. return QString(ipStrBuf);
  140. }
  141. void Resolver::startPage(QSharedPointer<QTextStream> ts, bool html)
  142. {
  143. if (html)
  144. {
  145. qInfo().noquote() << " └ Start page";
  146. QString page = http::HTML_PAGE;
  147. QString css = http::CSS_DEFAULT;
  148. QString text;
  149. if (m_NoApi and not m_NoResolve)
  150. {
  151. text = "<p>Input any domain to resolve or IPv6 to convert to <a href=\"https://github.com/zhoreeq/meshname\" style=\"text-decoration: none\">meship</a>.</p>";
  152. }
  153. else if (m_NoApi and m_NoResolve)
  154. {
  155. text = "<p>Input meship domain to resolve or IPv6 to convert to <a href=\"https://github.com/zhoreeq/meshname\" style=\"text-decoration: none\">meship</a>.</p>";
  156. }
  157. else if (not m_NoResolve)
  158. {
  159. text = "<p>Input any domain to resolve or IPv6 to convert to <a href=\"https://github.com/zhoreeq/meshname\" style=\"text-decoration: none\">meship</a>.</p>"
  160. "<p>Also you can use Mario DNS tool via API to get result in JSON (GET request like a /api/toConverting=yourvalue).";
  161. }
  162. else
  163. { // no resolve
  164. text = "<p>Input meship domain to resolve or IPv6 to convert to <a href=\"https://github.com/zhoreeq/meshname\" style=\"text-decoration: none\">meship</a>.</p>"
  165. "<p>Also you can use Mario DNS tool via API to get result in JSON (GET request like a /api/toConverting=yourvalue).";
  166. }
  167. css.replace("{{COLOR}}", "gray");
  168. page.replace("{{STYLES}}", css);
  169. page.replace("{{TEXT}}", text);
  170. *ts << page;
  171. }
  172. else
  173. {
  174. QString msg;
  175. if (m_NoResolve) {
  176. msg = "Push meship domain to resolve or IPv6 to convert to meship like a /api/toConverting=yourvalue";
  177. } else {
  178. msg = "Push any domain to resolve or IPv6 to convert to meship like a /api/toConverting=yourvalue";
  179. }
  180. qInfo().noquote() << " └ Incorrect request";
  181. JsonAnswer a;
  182. a.setValue("status", false);
  183. a.setValue("answer", msg);
  184. *ts << a.result();
  185. }
  186. }
  187. void Resolver::startPageWithMessage(const QString & value, QSharedPointer<QTextStream> ts, const QString & msg, bool html)
  188. {
  189. qInfo().noquote() << " └ " + msg;
  190. if (html)
  191. {
  192. QString page = http::HTML_PAGE;
  193. QString css = http::CSS_DEFAULT;
  194. css.replace("{{COLOR}}", "red");
  195. page.replace("{{STYLES}}", css);
  196. page.replace("{{TEXT}}", msg);
  197. if (!value.isEmpty()) {
  198. page.replace(QRegularExpression("placeholder=\".*domain\""), "value=\"" + value + "\"");
  199. }
  200. *ts << page;
  201. }
  202. else
  203. {
  204. JsonAnswer a;
  205. a.setValue("status", false);
  206. a.setValue("answer", msg);
  207. *ts << a.result();
  208. }
  209. }
  210. void Resolver::processPage(const QString& req, QSharedPointer<QTextStream> ts, bool html)
  211. {
  212. QString value = funcs::getValue(req, "toConverting");
  213. value.remove('+');
  214. value = QByteArray::fromPercentEncoding(value.toUtf8());
  215. qInfo().noquote() << " └ " + value;
  216. const uint8_t MAX_LEN = 60;
  217. if (value.size() > MAX_LEN)
  218. {
  219. startPageWithMessage("", ts, "Maximum input value length = " + QString::number(MAX_LEN), html);
  220. }
  221. else if (value == "version") {
  222. toVersion(value, ts, html);
  223. }
  224. else if (value.contains(":")) {
  225. toMeship(value, ts, html);
  226. }
  227. else if (value.endsWith(".meship")) {
  228. toIp(value, ts, html);
  229. }
  230. else if (value.contains(".") and not m_NoResolve) {
  231. toRealResolv(value, ts, html);
  232. }
  233. else
  234. {
  235. QString text;
  236. m_NoResolve
  237. ? text ="Input value must contains meship domain or IPv6"
  238. : text = "Input value must contains domain or IPv6";
  239. startPageWithMessage(value, ts, text, html);
  240. }
  241. }
  242. void Resolver::toMeship(const QString & value, QSharedPointer<QTextStream> ts, bool html)
  243. {
  244. Address rawAddr;
  245. convertStrToRaw(value, rawAddr);
  246. QString base32 = getBase32(rawAddr);
  247. base32 = base32.toLower();
  248. base32.remove('=');
  249. base32 += ".meship";
  250. if (html)
  251. {
  252. QString page = http::HTML_PAGE;
  253. QString css = http::CSS_DEFAULT;
  254. css.replace("{{COLOR}}", "green");
  255. page.replace("{{STYLES}}", css);
  256. page.replace("{{TEXT}}", base32);
  257. page.replace(QRegularExpression("placeholder=\".*domain\""), "value=\"" + value + "\"");
  258. *ts << page;
  259. }
  260. else
  261. {
  262. JsonAnswer a;
  263. a.setValue("status", true);
  264. a.setValue("answer", base32);
  265. *ts << a.result();
  266. }
  267. }
  268. void Resolver::toIp(const QString & value, QSharedPointer<QTextStream> ts, bool html)
  269. {
  270. QString result = decodeMeshToIP(value);
  271. if (result.isEmpty()) {
  272. startPageWithMessage(value, ts, "Failed: meship domain must have 26 base32 (RFC4648) characters only", html);
  273. return;
  274. }
  275. if (html)
  276. {
  277. QString page = http::HTML_PAGE;
  278. QString css = http::CSS_DEFAULT;
  279. css.replace("{{COLOR}}", "green");
  280. page.replace("{{STYLES}}", css);
  281. page.replace("{{TEXT}}", result);
  282. page.replace(QRegularExpression("placeholder=\".*domain\""), "value=\"" + value + "\"");
  283. *ts << page;
  284. }
  285. else
  286. {
  287. JsonAnswer a;
  288. a.setValue("status", true);
  289. a.setValue("answer", result);
  290. *ts << a.result();
  291. }
  292. }
  293. void Resolver::toRealResolv(const QString & value, QSharedPointer<QTextStream> ts, bool html)
  294. {
  295. QHostInfo host = QHostInfo::fromName(value);
  296. if (host.error() == QHostInfo::NoError)
  297. {
  298. auto addrs = host.addresses();
  299. if (html)
  300. {
  301. QString addresses;
  302. for (auto a: addrs) {
  303. addresses += a.toString() + "<br>";
  304. }
  305. QString page = http::HTML_PAGE;
  306. QString css = http::CSS_DEFAULT;
  307. css.replace("{{COLOR}}", "green");
  308. page.replace("{{STYLES}}", css);
  309. page.replace("{{TEXT}}", addresses);
  310. page.replace(QRegularExpression("placeholder=\".*domain\""), "value=\"" + value + "\"");
  311. *ts << page;
  312. }
  313. else
  314. {
  315. QJsonArray array;
  316. for (const auto& address: addrs)
  317. {
  318. array.push_back(address.toString());
  319. }
  320. JsonAnswer a;
  321. a.setValue("status", true);
  322. a.setValue("answer", array);
  323. *ts << a.result();
  324. }
  325. }
  326. else
  327. {
  328. QString msg;
  329. if (value.endsWith(".meshname")) {
  330. msg = "Domain not resolved. Try \".meship\" instead \".meshname\" for direct translation to address";
  331. } else {
  332. msg = "Failed: " + host.errorString();
  333. }
  334. startPageWithMessage(value, ts, msg, html);
  335. }
  336. }
  337. void Resolver::toVersion(const QString &value , QSharedPointer<QTextStream> ts, bool html)
  338. {
  339. if (html)
  340. {
  341. QString page = http::HTML_PAGE;
  342. QString css = http::CSS_DEFAULT;
  343. css.replace("{{COLOR}}", "gray");
  344. page.replace("{{STYLES}}", css);
  345. page.replace("{{TEXT}}", VERSION);
  346. page.replace(QRegularExpression("placeholder=\".*domain\""), "value=\"" + value + "\"");
  347. *ts << page;
  348. }
  349. else
  350. {
  351. JsonAnswer a;
  352. a.setValue("status", true);
  353. a.setValue("answer", VERSION);
  354. *ts << a.result();
  355. }
  356. }