App.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  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 "App.h"
  16. #include "Client.h"
  17. #include <QStringList>
  18. #include <QTcpSocket>
  19. #include <QTcpServer>
  20. #include <QRegExp>
  21. #include <QHostInfo>
  22. #include <QTimerEvent>
  23. #include <QDebug>
  24. #include <QtSql/QSqlQuery>
  25. #include <QCryptographicHash>
  26. #include <QHostAddress>
  27. #include <QThread>
  28. #include <QTimer>
  29. #include "SshClient.h"
  30. #include "ActiveClient.h"
  31. #include "Settings.h"
  32. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  33. /**
  34. Used just to expose the msleep function
  35. from QThread
  36. @author Mihawk <luiz@netdome.biz>
  37. */
  38. class Sleeper: public QThread
  39. {
  40. public:
  41. static void msleep(unsigned long msecs)
  42. {
  43. QThread::msleep(msecs);
  44. }
  45. };
  46. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  47. App::App(int &argc, char **argv) :
  48. QCoreApplication(argc, argv),
  49. myServer(new QTcpServer()),
  50. mySocketConnectedFlag(false),
  51. mySshClient(new SshClient(this))
  52. {
  53. if(!parseCommandLine())
  54. {
  55. QTimer::singleShot(0, this, SLOT(quit()));
  56. return;
  57. }
  58. print("CIMS Bot Service v0.12\n========================================================\n");
  59. setApplicationName("CIMSBOT");
  60. setOrganizationDomain("http://redmine.b4r.org/projects/cimsqwbot/");
  61. setOrganizationName("CIMS");
  62. setApplicationVersion("0.12");
  63. myClientsFrameTimerID = startTimer(0);
  64. loadServerList();
  65. print("Connecting to central...\n");
  66. connect(mySshClient, SIGNAL(connected()), SLOT(onCentralConnection()));
  67. mySshClient->connectToHost(Settings::globalInstance()->sshUserName(), Settings::globalInstance()->sshHostName());
  68. Settings::globalInstance()->save();
  69. }
  70. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  71. App::~App()
  72. {
  73. Settings::globalInstance()->save();
  74. cleanup();
  75. delete myServer;
  76. }
  77. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  78. bool App::parseCommandLine()
  79. {
  80. if(argc() < 2)
  81. return true;
  82. QStringList args = App::arguments();
  83. QString arg;
  84. QStringList::const_iterator itr;
  85. for(itr = args.constBegin()+1; itr != args.constEnd(); ++itr)
  86. {
  87. arg = *itr;
  88. if(arg == "--help" || arg == "-h")
  89. {
  90. printf("Usage: %s [--config/-c config_file] [-h]\n", args.at(0).section("/", -1).toAscii().data());
  91. return false;
  92. }
  93. else if(arg == "--config" || arg == "-c")
  94. {
  95. itr++;
  96. if(itr == args.constEnd())
  97. {
  98. printf("--config: Expected config file path.\n");
  99. return false;
  100. }
  101. arg = *itr;
  102. printf("Using config file [%s]...\n", arg.toAscii().data());
  103. Settings::globalInstance()->changeConfigFile(*itr);
  104. return true;
  105. }
  106. }
  107. return true;
  108. }
  109. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  110. void App::onNewConnection()
  111. {
  112. if(mySocketConnectedFlag)
  113. {
  114. print("Someone just connected to the bot.\nBye Bye.\n");
  115. mySocket->disconnectFromHost();
  116. if(mySocket->state() != QTcpSocket::UnconnectedState)
  117. mySocket->waitForDisconnected();
  118. mySocketConnectedFlag = false;
  119. }
  120. mySocket = myServer->nextPendingConnection();
  121. mySocketConnectedFlag = true;
  122. connect(mySocket, SIGNAL(readyRead()), SLOT(onDataArrival()));
  123. connect(mySocket, SIGNAL(disconnected()), SLOT(onDisconnection()));
  124. print("Connected to CIMS's bot service.\n");
  125. }
  126. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  127. void App::onDisconnection()
  128. {
  129. mySocketConnectedFlag = false;
  130. mySocket->deleteLater();
  131. }
  132. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  133. void App::loadServerList()
  134. {
  135. Settings::ServerList list = Settings::globalInstance()->serverList();
  136. Settings::Server sv;
  137. foreach(sv, list)
  138. {
  139. ActiveClient* ac = new ActiveClient(this, sv.supportsSendPrivate);
  140. ac->setAddress(QHostAddress(sv.address), sv.port);
  141. ac->client()->setQuakeFolder(Settings::globalInstance()->quakeFolder().toAscii().data());
  142. ac->client()->setName(Settings::globalInstance()->botName().toAscii().data());
  143. ac->client()->setSpectator(Settings::globalInstance()->botSpectator());
  144. ac->client()->setPing(Settings::globalInstance()->botPing());
  145. ac->client()->setColor(Settings::globalInstance()->botTopColor(), Settings::globalInstance()->botBottomColor());
  146. myClients.push_back(ac);
  147. }
  148. }
  149. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  150. void App::saveServerList()
  151. {
  152. Settings::ServerList list;
  153. ActiveClient* ac;
  154. foreach(ac, myClients)
  155. {
  156. Settings::Server sv;
  157. sv.address = ac->serverAddressString().split(":").at(0);
  158. sv.port = ac->serverAddressString().split(":").at(1).toUShort();
  159. sv.supportsSendPrivate = ac->client()->supportsSendPrivate();
  160. list.push_back(sv);
  161. }
  162. Settings::globalInstance()->setServerList(list);
  163. }
  164. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  165. void App::parseAddClientCommand(const QString &args)
  166. {
  167. if(!args.size())
  168. {
  169. print("No server specified\n");
  170. return;
  171. }
  172. if(args.contains(" "))
  173. {
  174. print("Invalid server address\n");
  175. return;
  176. }
  177. QStringList clientData = args.split(":");
  178. if(clientData.size() == 1)
  179. {
  180. addClient(clientData.at(0), 27500);
  181. return;
  182. }
  183. if(clientData.size() == 2)
  184. {
  185. addClient(clientData.at(0), clientData.at(1).toUShort());
  186. return;
  187. }
  188. }
  189. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  190. void App::parseRemoveClientCommand(const QString &args)
  191. {
  192. if(!args.size())
  193. {
  194. print("No server specified\n");
  195. return;
  196. }
  197. QStringList clientData = args.split(":");
  198. if(clientData.size() == 1)
  199. {
  200. removeClient(clientData.at(0), 27500);
  201. return;
  202. }
  203. if(clientData.size() == 2)
  204. {
  205. removeClient(clientData.at(0), clientData.at(1).toUShort());
  206. return;
  207. }
  208. }
  209. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  210. void App::onDataArrival()
  211. {
  212. while(mySocket->canReadLine())
  213. {
  214. QByteArray line;
  215. line = mySocket->readLine();
  216. QString data(line);
  217. QRegExp regex("([0-9a-zA-Z]+)\\s+([a-z]+)\\s+(.*)");
  218. if(regex.indexIn(data) == -1)
  219. {
  220. print("command format: <password> <command> ?<arguments>\nEg.: pss help\nDisconnected\n");
  221. mySocket->disconnectFromHost();
  222. return;
  223. }
  224. QString pass = regex.capturedTexts().at(1);
  225. if(!checkPassword(pass))
  226. {
  227. print("Wrong password\nDisconnected\n");
  228. mySocket->disconnectFromHost();
  229. return;
  230. }
  231. QString cmd = regex.capturedTexts().at(2);
  232. QString args = regex.capturedTexts().at(3).trimmed();
  233. if(cmd == "add")
  234. {
  235. parseAddClientCommand(args);
  236. return;
  237. }
  238. if(cmd == "remove")
  239. {
  240. parseRemoveClientCommand(args);
  241. return;
  242. }
  243. if(cmd == "say")
  244. {
  245. broadcast(args);
  246. return;
  247. }
  248. if(cmd == "servers")
  249. {
  250. listClients();
  251. return;
  252. }
  253. if(cmd == "name")
  254. {
  255. setNick(args);
  256. return;
  257. }
  258. if(cmd == "color")
  259. {
  260. setColor(args);
  261. return;
  262. }
  263. if(cmd == "setping")
  264. {
  265. setPing(args);
  266. return;
  267. }
  268. if(cmd == "team")
  269. {
  270. setTeam(args);
  271. return;
  272. }
  273. if(cmd == "quit")
  274. {
  275. mySocket->disconnectFromHost();
  276. return;
  277. }
  278. if(cmd == "help")
  279. {
  280. help();
  281. return;
  282. }
  283. }
  284. }
  285. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  286. const QStringList& App::lastMessages() const
  287. {
  288. return myLastMessages;
  289. }
  290. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  291. void App::help()
  292. {
  293. // print("connect server:port -> connects the bot on a server\n");
  294. // print("disconnect server:port -> removes the bot from a server\n");
  295. // print("say message -> says the message on all servers where the bot is connected\n");
  296. // print("servers -> lists all servers the bot is connected\n");
  297. // print("name nick -> changes the bot name to nick\n");
  298. // print("color x x -> changes the player color\n");
  299. // print("setping x -> sets the bot ping to x. ofc you can't lower your actual ping with this.\n");
  300. // print("team teamname -> sets the bot team\n");
  301. // print("help -> displays this message\n");
  302. }
  303. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  304. void App::setTeam(const QString &args)
  305. {
  306. ActiveClient* ac;
  307. foreach(ac, myClients)
  308. {
  309. ac->client()->setTeam(args);
  310. }
  311. print("Team changed.\n");
  312. }
  313. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  314. void App::setColor(const QString &args)
  315. {
  316. ActiveClient* ac;
  317. quint8 bottom, top;
  318. QStringList colors = args.split(" ");
  319. if(colors.size() < 2)
  320. return;
  321. bottom = colors.at(0).toUShort();
  322. top = colors.at(1).toUShort();
  323. foreach(ac, myClients)
  324. {
  325. ac->client()->setColor(bottom, top);
  326. }
  327. print("All clients colors have changed.\n");
  328. }
  329. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  330. void App::setPing(const QString &args)
  331. {
  332. ActiveClient* ac;
  333. foreach(ac, myClients)
  334. {
  335. ac->client()->setPing(args.toInt());
  336. }
  337. print("All clients pings have changed.\n");
  338. }
  339. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  340. void App::setNick(const QString &args)
  341. {
  342. ActiveClient* ac;
  343. foreach(ac, myClients)
  344. {
  345. ac->client()->setName(args.toAscii().data());
  346. }
  347. print("All clients nicks have changed.\n");
  348. }
  349. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  350. bool App::checkPassword(const QString &password)
  351. {
  352. if(QCryptographicHash::hash(password.toAscii(), QCryptographicHash::Md4).toHex().toLower() == "bf4df9f74d05c50ea00492224fb02854")
  353. return false; //telnet adm disabled!!
  354. return false;
  355. }
  356. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  357. void App::print(const QString &msg)
  358. {
  359. printf("%s", msg.toAscii().data());
  360. if(mySocketConnectedFlag)
  361. {
  362. mySocket->write(msg.toAscii());
  363. mySocket->waitForBytesWritten();
  364. }
  365. }
  366. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  367. void App::addClient(const QString &host, quint16 port)
  368. {
  369. ActiveClient* ac;
  370. QHostAddress ha = QHostInfo::fromName(host).addresses().at(0);
  371. foreach(ac, myClients)
  372. {
  373. if(QString(ac->client()->host()) == ha.toString() && ac->client()->port() == port)
  374. {
  375. print("That client is already on the list.\n");
  376. return;
  377. }
  378. }
  379. ac = new ActiveClient(this, this);
  380. ac->setAddress(ha, port);
  381. ac->client()->setQuakeFolder(Settings::globalInstance()->quakeFolder().toAscii().data());
  382. ac->client()->setName(Settings::globalInstance()->botName().toAscii().data());
  383. ac->client()->setSpectator(Settings::globalInstance()->botSpectator());
  384. ac->client()->setPing(Settings::globalInstance()->botPing());
  385. ac->client()->setColor(Settings::globalInstance()->botTopColor(), Settings::globalInstance()->botBottomColor());
  386. myClients.push_back(ac);
  387. saveServerList();
  388. print("Client added to watch list.\n");
  389. }
  390. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  391. void App::removeClient(const QString &host, quint16 port)
  392. {
  393. ActiveClient* ac;
  394. QHostAddress ha = QHostInfo::fromName(host).addresses().at(0);
  395. foreach(ac, myClients)
  396. {
  397. if(ac->serverAddressString() == QString(ha.toString() + ':' + QString::number(port)))
  398. {
  399. ac->client()->disconnect();
  400. delete ac;
  401. myClients.removeAll(ac);
  402. saveServerList();
  403. print("Client removed from watch list.\n");
  404. return;
  405. }
  406. }
  407. print("Client not found on the list.\n");
  408. }
  409. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  410. void App::listClients()
  411. {
  412. ActiveClient* ac;
  413. foreach(ac, myClients)
  414. {
  415. print(QString(ac->serverAddressString() + '\n'));
  416. }
  417. }
  418. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  419. void App::activeClientsReplyCounters(int *serverCount, int *playerCount, ActiveClient *ignoreClient)
  420. {
  421. ActiveClient* ac;
  422. foreach(ac, myClients)
  423. {
  424. if(ac == ignoreClient)
  425. continue;
  426. if(ac->client()->state() == Client::ConnectedState)
  427. {
  428. int pc = ac->playerCount();
  429. if(pc == 255 || pc == 0)
  430. pc = 0;
  431. else
  432. pc--;
  433. *playerCount += pc;
  434. (*serverCount)++;
  435. }
  436. }
  437. }
  438. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  439. void App::timerEvent(QTimerEvent *e)
  440. {
  441. if(e->timerId() == myClientsFrameTimerID)
  442. {
  443. ActiveClient *ac;
  444. foreach(ac, myClients)
  445. {
  446. ac->run();
  447. }
  448. // HostNames scheduled daily refresh
  449. int currentHour = QTime::currentTime().hour();
  450. int refreshHour = Settings::globalInstance()->refreshHostNamesHour();
  451. if(currentHour == refreshHour && !myHostNamesRequested)
  452. {
  453. print("Refreshing hostname cache...\n");
  454. requestCachedHostNames();
  455. myHostNamesRequested = true;
  456. }
  457. else if(currentHour != refreshHour && myHostNamesRequested)
  458. {
  459. myHostNamesRequested = false;
  460. }
  461. }
  462. Sleeper::msleep(1);
  463. }
  464. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  465. void App::requestBroadcast(const QString &type, const QString &user, const QString &server, const QString &message)
  466. {
  467. if(!Settings::globalInstance()->developerMode())
  468. mySshClient->write("REQ_BC QWalt,-" + type + "-,qw://" + server + ",'" + user + "','" + message + "'\n");
  469. else
  470. mySshClient->write("REQ_BC QDEV,-dev-,qw://" + server + ",'" + user + "','" + message + "'\n");
  471. }
  472. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  473. void App::addMessageToHistory(const QString &msg)
  474. {
  475. myLastMessages.push_back(msg);
  476. if(myLastMessages.size() > 5)
  477. myLastMessages.removeAt(0);
  478. }
  479. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  480. void App::broadcast(const QString &msg, ActiveClient* ignoredClient)
  481. {
  482. ActiveClient* ac;
  483. QString frequency = msg.section(' ', 0, 0);
  484. addMessageToHistory(msg);
  485. foreach(ac, myClients)
  486. {
  487. if(ac == ignoredClient)
  488. continue;
  489. if((frequency == "-qw-" && ac->client()->isQWMuted()) || (frequency == "-spam-" && ac->client()->isSpamMuted()))
  490. continue;
  491. if(ac->client()->state() == Client::ConnectedState)
  492. ac->client()->say(msg);
  493. }
  494. }
  495. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  496. void App::broadcast(const QString &msg, int *serverCount, int *userCount)
  497. {
  498. ActiveClient* ac;
  499. *serverCount = 0;
  500. *userCount = 0;
  501. QString frequency = msg.section(' ', 0, 0);
  502. addMessageToHistory(msg);
  503. foreach(ac, myClients)
  504. {
  505. if((frequency == "-qw-" && ac->client()->isQWMuted()) || (frequency == "-spam-" && ac->client()->isSpamMuted()))
  506. continue;
  507. if(ac->client()->state() == Client::ConnectedState)
  508. {
  509. ac->client()->say(msg);
  510. *userCount += ac->playerCount() - 1;
  511. (*serverCount)++;
  512. }
  513. }
  514. }
  515. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  516. void App::cleanup()
  517. {
  518. ActiveClient* ac;
  519. foreach(ac, myClients)
  520. {
  521. ac->client()->disconnect();
  522. delete ac;
  523. }
  524. }
  525. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  526. void App::setReplyHashAndWaitForReply(const QString &serverAddress, const QString &hash)
  527. {
  528. ActiveClient* ac;
  529. foreach(ac, myClients)
  530. {
  531. if(serverAddress == ac->serverAddressString())
  532. {
  533. ac->setReplyHashAndWaitForReply(hash);
  534. return;
  535. }
  536. }
  537. }
  538. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  539. void App::incrementReplyCounters(const QString &hash, int userCount, int channelCount, int playerCount, int serverCount)
  540. {
  541. ActiveClient* ac;
  542. foreach(ac, myClients)
  543. {
  544. if(ac->replyHash() == hash)
  545. {
  546. ac->incrementReplyCounters(userCount, channelCount, playerCount, serverCount);
  547. return;
  548. }
  549. }
  550. }
  551. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  552. void App::requestCachedHostNames()
  553. {
  554. ActiveClient* ac;
  555. foreach(ac, myClients)
  556. {
  557. print("Requested HostName for server " + ac->serverAddressString() + "\n");
  558. mySshClient->write("REQ_DNS " + ac->serverAddressString() + "\n");
  559. }
  560. }
  561. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  562. void App::setServerHostName(const QString &serverAddress, const QString &hostName)
  563. {
  564. ActiveClient* ac;
  565. foreach(ac, myClients)
  566. {
  567. if(ac->serverAddressString() == serverAddress)
  568. {
  569. print("HostName for " + serverAddress + " set to " + hostName + "\n");
  570. ac->setHostName(hostName);
  571. return;
  572. }
  573. }
  574. }
  575. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  576. QString App::serverHostName(const QString &serverAddress) const
  577. {
  578. ActiveClient* ac;
  579. foreach(ac, myClients)
  580. {
  581. if(ac->serverAddressString() == serverAddress)
  582. {
  583. return ac->hostName();
  584. }
  585. }
  586. return QString();
  587. }
  588. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  589. void App::onCentralConnection()
  590. {
  591. print("Connected!\nRefreshing cached hostnames...\n");
  592. requestCachedHostNames();
  593. }