SshClient.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. /*
  2. GNU General Public License version 3 notice
  3. Copyright (C) 2012 Mihawk <luiz@netdome.biz>. All rights reserved.
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 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 General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see < http://www.gnu.org/licenses/ >.
  14. */
  15. #include "SshClient.h"
  16. #include "App.h"
  17. #include "Settings.h"
  18. #include "ActiveClient.h"
  19. #include <QProcess>
  20. #include <QRegExp>
  21. #include <QDateTime>
  22. #include <QTimerEvent>
  23. #include <QStringList>
  24. #include <Pinger.h>
  25. #include <QDebug>
  26. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  27. SshClient::SshClient(App* app, QObject *parent) :
  28. QObject(parent),
  29. myApp(app),
  30. myProcess(new QProcess(this)),
  31. myCommandRegex(new QRegExp("^([0-9]{4}-[0-9]{2}-[0-9]{2}\\s[0-9]{2}:[0-9]{2}:[0-9]{2})\\s(\\+[0-9]{4}):\\s(.+)$")),
  32. myConnectedFlag(false),
  33. myConnectionTimerID(0),
  34. myPingTimerID(0),
  35. myPongTimerID(0)
  36. {
  37. connect(myProcess, SIGNAL(readyRead()), SLOT(read()));
  38. connect(myProcess, SIGNAL(finished(int)), SLOT(exited(int)));
  39. }
  40. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  41. SshClient::~SshClient()
  42. {
  43. delete myCommandRegex;
  44. }
  45. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  46. bool SshClient::isConnected() const
  47. {
  48. return myConnectedFlag;
  49. }
  50. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  51. void SshClient::read()
  52. {
  53. QString data(myProcess->readAll().trimmed());
  54. if(data.isEmpty())
  55. return;
  56. QStringList lines = data.split("\n", QString::SkipEmptyParts);
  57. QString line;
  58. foreach(line, lines)
  59. {
  60. line = line.trimmed();
  61. if(myCommandRegex->indexIn(line) != -1)
  62. {
  63. QDateTime time = QDateTime::fromString(myCommandRegex->cap(1), "yyyy-MM-dd HH:mm:ss");
  64. time = time.addSecs(-myCommandRegex->cap(2).toInt()/100*60*60);
  65. parse(time,
  66. myCommandRegex->cap(3).section(' ', 0, 0),
  67. myCommandRegex->cap(3).section(' ', 1)
  68. );
  69. }
  70. }
  71. }
  72. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  73. void SshClient::exited(int)
  74. {
  75. reconnect();
  76. }
  77. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  78. void SshClient::ping()
  79. {
  80. write("PING\n");
  81. myPingTimerID = startTimer(30000);
  82. }
  83. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  84. void SshClient::pong()
  85. {
  86. killTimer(myPingTimerID);
  87. myPingTimerID = -1;
  88. myPongTimerID = startTimer(30000);
  89. }
  90. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  91. void SshClient::write(const QString &data)
  92. {
  93. myProcess->write(data.toLatin1());
  94. myProcess->waitForBytesWritten();
  95. }
  96. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  97. void SshClient::parse(const QDateTime &time, const QString &command, const QString &commandData)
  98. {
  99. /* JOINED - Another user has just joined central */
  100. if(command == "JOINED")
  101. {
  102. QRegExp a("^User '([a-zA-Z]+)'.+$");
  103. if(a.indexIn(commandData) != -1)
  104. {
  105. if(!myClients.contains(a.capturedTexts().at(1)))
  106. myClients.push_back(a.capturedTexts().at(1));
  107. }
  108. return;
  109. }
  110. /* PARTED - Another user has left central */
  111. if(command == "PARTED")
  112. {
  113. QRegExp a("^User '([a-zA-Z]+)'.+$");
  114. if(a.indexIn(commandData) != -1)
  115. myClients.removeAll(a.capturedTexts().at(1));
  116. return;
  117. }
  118. /* HELLO - Server acknowledge */
  119. if(command == "HELLO")
  120. {
  121. ping();
  122. myConnectedFlag = true;
  123. killTimer(myConnectionTimerID);
  124. myConnectionTimerID = -1;
  125. emit connected();
  126. return;
  127. }
  128. /* PING PONG - The connection is still up */
  129. if(command == "PONG")
  130. {
  131. pong();
  132. return;
  133. }
  134. /* SYS - Central generic message */
  135. if(command == "SYS")
  136. {
  137. myApp->print("Central Message: " + commandData + "\n");
  138. return;
  139. }
  140. /* BC - Broadcast order from central */
  141. if(command == "BC")
  142. {
  143. QRegExp a("^([A-Za-z0-9]+) (.+),(.+),(.+),'(.+)','(.+)'$");
  144. if(a.indexIn(commandData) == -1)
  145. return;
  146. if(a.cap(2) == "QDEV" && !Settings::globalInstance()->developerMode()) //developer mode not enabled ignore this message from developers
  147. return;
  148. int serverCount, userCount;
  149. myApp->broadcast(a.cap(3) + " " + a.cap(5) + " - " + a.cap(4) + " : " + a.cap(6), &serverCount, &userCount);
  150. if(userCount)
  151. write("BC_RE " + a.cap(1) + " Players=" + QString::number(userCount) + ",Servers=" + QString::number(serverCount) + "\n");
  152. return;
  153. }
  154. /* BC_ID - Broadcast reply with the ID of the broadcast you just generated */
  155. if(command == "BC_ID")
  156. {
  157. //BC_ID 4e5fca581569e168c7a86a0a9a91949f for: QDEV,-dev-,qw://123.123
  158. // qDebug() << commandData;
  159. QRegExp a("^([A-Za-z0-9]+) for: .+,-(.+)-,qw://(.+) [0-9]+/[0-9]+$");
  160. if(a.indexIn(commandData) == -1)
  161. return;
  162. QString hash = a.cap(1);
  163. //QString frequency = a.cap(2);
  164. QString server = a.cap(3);
  165. myApp->setReplyHashAndWaitForReply(server, hash);
  166. return;
  167. }
  168. /* BC_RE - Broadcast reply to increment the counters */
  169. if(command == "BC_RE")
  170. {
  171. QRegExp a("^([A-Za-z0-9]+) (Users|Players)=([0-9]+),(Channels|Servers)=([0-9]+)$");
  172. if(a.indexIn(commandData) == -1)
  173. return;
  174. QString hash = a.cap(1);
  175. QString userType = a.cap(2);
  176. QString channelType = a.cap(4);
  177. int userCount = 0;
  178. int channelCount = 0;
  179. int playerCount = 0;
  180. int serverCount = 0;
  181. if(userType == "Users")
  182. {
  183. userCount = a.cap(3).toInt();
  184. playerCount = 0;
  185. }
  186. else if(userType == "Players")
  187. {
  188. playerCount = a.cap(3).toInt();
  189. userCount = 0;
  190. }
  191. if(channelType == "Channels")
  192. {
  193. channelCount = a.cap(5).toInt();
  194. serverCount = 0;
  195. }
  196. else if(channelType == "Servers")
  197. {
  198. serverCount = a.cap(5).toInt();
  199. channelCount = 0;
  200. }
  201. // qDebug() << commandData;
  202. myApp->incrementReplyCounters(hash, userCount, channelCount, playerCount, serverCount);
  203. return;
  204. }
  205. /* DNS_RE - Reply from REQ_DNS, returns the HostName for the requested ip:port pair */
  206. if(command == "DNS_RE")
  207. {
  208. QRegExp a("^([0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+:[0-9]+) ([0-9A-Za-z][A-Za-z0-9\\-\\.]+)$");
  209. if(a.indexIn(commandData) == -1)
  210. return;
  211. myApp->setServerHostName(a.cap(1), a.cap(2));
  212. return;
  213. }
  214. /* COMMANDS - List of commands allowed for me */
  215. if(command == "COMMANDS")
  216. {
  217. myCommands = commandData.split(", ", QString::SkipEmptyParts);
  218. return;
  219. }
  220. /* ROLES - List of roles I exert */
  221. if(command == "ROLES")
  222. {
  223. myRoles = commandData.split(", ", QString::SkipEmptyParts);
  224. return;
  225. }
  226. /* REQ_ASSIGNMENTS - Central is requesting the server list I have */
  227. if(command == "REQ_ASSIGNMENTS")
  228. {
  229. myApp->print("Server list requested... Sending it now!\n");
  230. foreach (ActiveClient* ac, myApp->clients()) {
  231. Pinger* pinger = new Pinger(ac->address(), ac->port(), this);
  232. connect(pinger, SIGNAL(finished(QHostAddress,quint16,int)), SLOT(assignmentsReply(QHostAddress,quint16,int)));
  233. pinger->ping();
  234. }
  235. return;
  236. }
  237. /* REQ_PING - Requests an given server ping */
  238. if(command == "REQ_PING")
  239. {
  240. QStringList splitCmd = commandData.split(":");
  241. if(splitCmd.size() < 2)
  242. {
  243. write("Malformed REQ_PING command.\n");
  244. return;
  245. }
  246. QString server = splitCmd.at(0);
  247. quint16 port = splitCmd.at(1).toUShort();
  248. Pinger* pinger = new Pinger(QHostAddress(server), port, this);
  249. connect(pinger, SIGNAL(finished(QHostAddress,quint16,int)), SLOT(serverPong(QHostAddress,quint16,int)));
  250. pinger->ping();
  251. return;
  252. }
  253. /* REQ_ASSIGN */
  254. if(command == "REQ_ASSIGN")
  255. {
  256. QRegExp rx("(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}):(\\d{1,5})");
  257. if(rx.indexIn(commandData) == -1)
  258. {
  259. write("Malformed REQ_ASSIGN request.\n");
  260. return;
  261. }
  262. if(myApp->addClient(rx.cap(1), rx.cap(2).toUShort()))
  263. write("ASSIGN_RE " + rx.cap(1) + ":" + rx.cap(2) + " OK\n");
  264. else
  265. write("ASSIGN_RE " + rx.cap(1) + ":" + rx.cap(2) + " FAILED Client already on my list.\n");
  266. return;
  267. }
  268. /* REQ_UNASSIGN */
  269. if(command == "REQ_UNASSIGN")
  270. {
  271. QRegExp rx("(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}):(\\d{1,5})");
  272. if(rx.indexIn(commandData) == -1)
  273. {
  274. write("Malformed REQ_UNASSIGN request.\n");
  275. return;
  276. }
  277. if(myApp->removeClient(rx.cap(1), rx.cap(2).toUShort()))
  278. write("UNASSIGN_RE " + rx.cap(1) + ":" + rx.cap(2) + " OK\n");
  279. else
  280. write("UNASSIGN_RE " + rx.cap(1) + ":" + rx.cap(2) + " FAILED Client not found on my list.\n");
  281. return;
  282. }
  283. /* REQ_MAXSERVERS - Reply with the maximum number of servers we can handle */
  284. if(command == "REQ_MAXSERVERS")
  285. {
  286. write("MAXSERVERS_RE " + QString::number(Settings::globalInstance()->maxServers()) + "\n");
  287. return;
  288. }
  289. myApp->print("Unparsed cmd from central: " + time.toString() + " " + command + " " + commandData + "\n");
  290. }
  291. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  292. bool SshClient::connectToHost(const QString &user, const QString &host, quint16 port)
  293. {
  294. myProcess->start("ssh", QStringList() << user + "@" + host << "-p " + QString::number(port));
  295. myUsername = user;
  296. myHostname = host;
  297. myPort = port;
  298. bool r = myProcess->waitForStarted();
  299. if(!r)
  300. return false;
  301. else
  302. {
  303. myConnectionTimerID = startTimer(60000*3); // up to 3 minutes of waiting
  304. return true;
  305. }
  306. }
  307. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  308. void SshClient::reconnect()
  309. {
  310. if(!myUsername.isEmpty() && !myHostname.isEmpty())
  311. connectToHost(myUsername, myHostname, myPort);
  312. }
  313. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  314. void SshClient::disconnectFromHost()
  315. {
  316. killTimer(myConnectionTimerID);
  317. killTimer(myPingTimerID);
  318. killTimer(myPongTimerID);
  319. myConnectionTimerID = myPingTimerID = myPongTimerID = -1;
  320. myProcess->terminate();
  321. myProcess->waitForFinished();
  322. myConnectedFlag = false;
  323. }
  324. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  325. void SshClient::timerEvent(QTimerEvent *e)
  326. {
  327. if(e->timerId() == myConnectionTimerID)
  328. {
  329. myApp->print("Timedout while trying to connect to central...\n");
  330. disconnectFromHost();
  331. emit error(ConnectionTimedOutError);
  332. return;
  333. }
  334. if(e->timerId() == myPingTimerID)
  335. {
  336. myApp->print("Ping with no pong! Disconnecting from central...\n");
  337. disconnectFromHost();
  338. emit error(ConnectionTimedOutError);
  339. return;
  340. }
  341. if(e->timerId() == myPongTimerID)
  342. {
  343. killTimer(myPongTimerID);
  344. myPongTimerID = -1;
  345. ping();
  346. return;
  347. }
  348. }
  349. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  350. void SshClient::serverPong(const QHostAddress &host, quint16 port, int ms)
  351. {
  352. write("PING_RE " + host.toString() + ":" + QString::number(port) + "," + QString::number(ms) + "\n");
  353. sender()->deleteLater();
  354. }
  355. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  356. void SshClient::assignmentsReply(const QHostAddress &host, quint16 port, int ms)
  357. {
  358. QString fullAddress = host.toString() + ":" + QString::number(port);
  359. write("ASSIGNMENTS_RE " + host.toString() + ":" + QString::number(port) + "," + QString::number(ms) + "\n");
  360. sender()->deleteLater();
  361. }