resolver.cpp 13 KB

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