App.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. #include "App.h"
  2. #include "Client.h"
  3. #include <QStringList>
  4. #include <QTcpSocket>
  5. #include <QTcpServer>
  6. #include <QRegExp>
  7. #include <QHostInfo>
  8. #include <QTimerEvent>
  9. #include <QDebug>
  10. #include <QtSql/QSqlQuery>
  11. #include <QCryptographicHash>
  12. #include <QHostAddress>
  13. #include "SshClient.h"
  14. #include "ServerQueryThread.h"
  15. App::App(int &argc, char **argv) :
  16. QCoreApplication(argc, argv),
  17. myServer(new QTcpServer()),
  18. mySocketConnectedFlag(false),
  19. myQWNETSshClient(new SshClient(this))
  20. {
  21. print("CIMS Bot Service v0.101\n=========================================================\n");
  22. setApplicationName("CIMSBOT");
  23. setOrganizationDomain("qwbr.tk");
  24. setOrganizationName("CIMS");
  25. setApplicationVersion("0.101");
  26. myServer->listen(QHostAddress::Any, 45000);
  27. connect(myServer, SIGNAL(newConnection()), SLOT(onNewConnection()));
  28. myClientsFrameTimerID = startTimer(0);
  29. myQWNETSshClient->connectToHost("stomp", "b4r.org");
  30. }
  31. void App::onNewConnection()
  32. {
  33. if(mySocketConnectedFlag)
  34. {
  35. print("Someone just connected to the bot.\nBye Bye.\n");
  36. mySocket->disconnectFromHost();
  37. if(mySocket->state() != QTcpSocket::UnconnectedState)
  38. mySocket->waitForDisconnected();
  39. mySocketConnectedFlag = false;
  40. }
  41. mySocket = myServer->nextPendingConnection();
  42. mySocketConnectedFlag = true;
  43. connect(mySocket, SIGNAL(readyRead()), SLOT(onDataArrival()));
  44. connect(mySocket, SIGNAL(disconnected()), SLOT(onDisconnection()));
  45. print("Connected to CIMS's bot service.\n");
  46. /* Set socket on clients for echoing */
  47. ActiveClient* ac;
  48. foreach(ac, myClients)
  49. {
  50. ac->client()->setSocket(mySocket);
  51. }
  52. }
  53. void App::onDisconnection()
  54. {
  55. /* set all sockets to null so it doenst echo anything on a dangling pointer */
  56. ActiveClient* ac;
  57. foreach(ac, myClients)
  58. {
  59. ac->client()->setSocket(NULL);
  60. }
  61. mySocketConnectedFlag = false;
  62. mySocket->deleteLater();
  63. }
  64. void App::loadClients()
  65. {
  66. }
  67. void App::connectToServer(const QString &args)
  68. {
  69. if(!args.size())
  70. {
  71. print("No server specified\n");
  72. return;
  73. }
  74. if(args.contains(" "))
  75. {
  76. print("Invalid server address\n");
  77. return;
  78. }
  79. QStringList clientData = args.split(":");
  80. if(clientData.size() == 1)
  81. {
  82. addClient(clientData.at(0), 27500);
  83. return;
  84. }
  85. if(clientData.size() == 2)
  86. {
  87. addClient(clientData.at(0), clientData.at(1).toUShort());
  88. return;
  89. }
  90. }
  91. void App::disconnectFromServer(const QString &args)
  92. {
  93. if(!args.size())
  94. {
  95. print("No server specified\n");
  96. return;
  97. }
  98. QStringList clientData = args.split(":");
  99. if(clientData.size() == 1)
  100. {
  101. removeClient(clientData.at(0), 27500);
  102. return;
  103. }
  104. if(clientData.size() == 2)
  105. {
  106. removeClient(clientData.at(0), clientData.at(1).toUShort());
  107. return;
  108. }
  109. }
  110. void App::onDataArrival()
  111. {
  112. while(mySocket->canReadLine())
  113. {
  114. QByteArray line;
  115. line = mySocket->readLine();
  116. QString data(line);
  117. QRegExp regex("([0-9a-zA-Z]+)\\s+([a-z]+)\\s+(.*)");
  118. if(regex.indexIn(data) == -1)
  119. {
  120. print("command format: <password> <command> ?<arguments>\nEg.: pss help\nDisconnected\n");
  121. mySocket->disconnectFromHost();
  122. return;
  123. }
  124. QString pass = regex.capturedTexts().at(1);
  125. if(!checkPassword(pass))
  126. {
  127. print("Wrong password\nDisconnected\n");
  128. mySocket->disconnectFromHost();
  129. return;
  130. }
  131. QString cmd = regex.capturedTexts().at(2);
  132. QString args = regex.capturedTexts().at(3).trimmed();
  133. if(cmd == "connect")
  134. {
  135. connectToServer(args);
  136. return;
  137. }
  138. if(cmd == "disconnect")
  139. {
  140. disconnectFromServer(args);
  141. return;
  142. }
  143. if(cmd == "say")
  144. {
  145. say(args);
  146. return;
  147. }
  148. if(cmd == "say_team")
  149. {
  150. sayTeam(args);
  151. return;
  152. }
  153. if(cmd == "servers")
  154. {
  155. listClients();
  156. return;
  157. }
  158. if(cmd == "name")
  159. {
  160. setNick(args);
  161. return;
  162. }
  163. if(cmd == "color")
  164. {
  165. setColor(args);
  166. return;
  167. }
  168. if(cmd == "setping")
  169. {
  170. setPing(args);
  171. return;
  172. }
  173. if(cmd == "team")
  174. {
  175. setTeam(args);
  176. return;
  177. }
  178. if(cmd == "quit")
  179. {
  180. mySocket->disconnectFromHost();
  181. return;
  182. }
  183. if(cmd == "help")
  184. {
  185. help();
  186. return;
  187. }
  188. }
  189. }
  190. void App::help()
  191. {
  192. print("connect server:port -> connects the bot on a server\n");
  193. print("disconnect server:port -> removes the bot from a server\n");
  194. print("say message -> says the message on all servers where the bot is connected\n");
  195. print("say_team message -> says the message on all servers where the bot is connected\n");
  196. print("servers -> lists all servers the bot is connected\n");
  197. print("name nick -> changes the bot name to nick\n");
  198. print("color x x -> changes the player color\n");
  199. print("setping x -> sets the bot ping to x. ofc you can't lower your actual ping with this.\n");
  200. print("team teamname -> sets the bot team\n");
  201. print("help -> displays this message\n");
  202. }
  203. void App::setTeam(const QString &args)
  204. {
  205. ActiveClient* ac;
  206. foreach(ac, myClients)
  207. {
  208. ac->client()->setTeam(args);
  209. }
  210. print("Team changed.\n");
  211. }
  212. void App::setColor(const QString &args)
  213. {
  214. ActiveClient* ac;
  215. quint8 bottom, top;
  216. QStringList colors = args.split(" ");
  217. if(colors.size() < 2)
  218. return;
  219. bottom = colors.at(0).toUShort();
  220. top = colors.at(1).toUShort();
  221. foreach(ac, myClients)
  222. {
  223. ac->client()->setColor(bottom, top);
  224. }
  225. print("All clients colors have changed.\n");
  226. }
  227. void App::setPing(const QString &args)
  228. {
  229. ActiveClient* ac;
  230. foreach(ac, myClients)
  231. {
  232. ac->client()->setPing(args.toInt());
  233. }
  234. print("All clients pings have changed.\n");
  235. }
  236. void App::setNick(const QString &args)
  237. {
  238. ActiveClient* ac;
  239. foreach(ac, myClients)
  240. {
  241. ac->client()->setName(args.toAscii().data());
  242. }
  243. print("All clients nicks have changed.\n");
  244. }
  245. bool App::checkPassword(const QString &password)
  246. {
  247. if(QCryptographicHash::hash(password.toAscii(), QCryptographicHash::Md4).toHex().toLower() == "bf4df9f74d05c50ea00492224fb02854")
  248. return true;
  249. return false;
  250. }
  251. void App::print(const QString &msg)
  252. {
  253. printf("%s", msg.toAscii().data());
  254. if(mySocketConnectedFlag)
  255. {
  256. mySocket->write(msg.toAscii());
  257. mySocket->waitForBytesWritten();
  258. }
  259. }
  260. void App::addClient(const QString &host, quint16 port)
  261. {
  262. ActiveClient* ac;
  263. QHostAddress ha = QHostInfo::fromName(host).addresses().at(0);
  264. foreach(ac, myClients)
  265. {
  266. if(QString(ac->client()->host()) == ha.toString() && ac->client()->port() == port)
  267. {
  268. print("That client is already on the list.\n");
  269. return;
  270. }
  271. }
  272. ac = new ActiveClient(this);
  273. if(mySocketConnectedFlag)
  274. {
  275. if(mySocket->state() == QTcpSocket::ConnectedState)
  276. {
  277. ac->client()->setSocket(mySocket);
  278. }
  279. }
  280. ac->setAddress(ha, port);
  281. ac->client()->setQuakeFolder(mySettings.value("quakeFolder", App::applicationDirPath()).toString().toAscii().data());
  282. ac->client()->setName(mySettings.value("botName", "cimsbot").toString().toAscii().data());
  283. ac->client()->setSpectator(true);
  284. ac->client()->setPing(120);
  285. ac->client()->setColor(11, 13);
  286. myClients.push_back(ac);
  287. }
  288. void App::removeClient(const QString &host, quint16 port)
  289. {
  290. ActiveClient* ac;
  291. QHostAddress ha = QHostInfo::fromName(host).addresses().at(0);
  292. foreach(ac, myClients)
  293. {
  294. if(QString(ac->client()->host()) == ha.toString() && ac->client()->port() == port)
  295. {
  296. ac->client()->disconnect();
  297. delete ac;
  298. myClients.removeAll(ac);
  299. print("Client removed.\n");
  300. return;
  301. }
  302. }
  303. print("Client not found on the list.\n");
  304. }
  305. void App::say(const QString &msg, int *serverCount, int *userCount)
  306. {
  307. ActiveClient* ac;
  308. *serverCount = 0;
  309. *userCount = 0;
  310. foreach(ac, myClients)
  311. {
  312. if(ac->client()->state() == Client::ConnectedState)
  313. {
  314. ac->client()->say(msg);
  315. *userCount += ac->queryThread()->playerCount() - 1;
  316. (*serverCount)++;
  317. }
  318. }
  319. print("Say command sent to all clients\n");
  320. }
  321. void App::say(const QString &msg)
  322. {
  323. ActiveClient* ac;
  324. foreach(ac, myClients)
  325. {
  326. if(ac->client()->state() == Client::ConnectedState)
  327. {
  328. ac->client()->say(msg);
  329. }
  330. }
  331. print("Say command sent to all clients\n");
  332. }
  333. void App::sayTeam(const QString &msg)
  334. {
  335. ActiveClient* ac;
  336. foreach(ac, myClients)
  337. {
  338. ac->client()->sayTeam(msg);
  339. }
  340. print("Say_team command sent to all clients\n");
  341. }
  342. void App::listClients()
  343. {
  344. ActiveClient* ac;
  345. foreach(ac, myClients)
  346. {
  347. QString reply(ac->client()->host());
  348. reply.append(":" + QString::number(ac->client()->port()) + "\n");
  349. print(reply.toAscii().data());
  350. }
  351. }
  352. void App::activeClientsReplyCounters(int *serverCount, int *playerCount)
  353. {
  354. ActiveClient* ac;
  355. foreach(ac, myClients)
  356. {
  357. if(ac->client()->state() == Client::ConnectedState)
  358. {
  359. int pc = ac->queryThread()->playerCount();
  360. if(pc == 255 || pc == 0)
  361. pc = 0;
  362. else
  363. pc--;
  364. *playerCount += pc;
  365. (*serverCount)++;
  366. }
  367. }
  368. }
  369. void App::timerEvent(QTimerEvent *e)
  370. {
  371. if(e->timerId() == myClientsFrameTimerID)
  372. {
  373. ActiveClient *ac;
  374. foreach(ac, myClients)
  375. {
  376. ac->run();
  377. }
  378. return;
  379. }
  380. }
  381. void App::requestBroadcast(const QString &type, const QString &user, const QString &server, const QString &message)
  382. {
  383. //REQ_BC QDEV,-dev-,qw://123.123,'testuser','test, with '',``twists''$ hehe'
  384. qDebug() << "REQ_BC QDEV,-" + type + "-,qw://" + server + ",'" + user + "','" + message + "'";
  385. myQWNETSshClient->write("REQ_BC QDEV,-" + type + "-,qw://" + server + ",'" + user + "','" + message + "'\n");
  386. }
  387. void App::broadcast(const QString &msg)
  388. {
  389. say(msg);
  390. }
  391. void App::broadcast(const QString &msg, int *serverCount, int *userCount)
  392. {
  393. qDebug() << "Broadcasting" << msg;
  394. say(msg, serverCount, userCount);
  395. }
  396. void App::cleanup()
  397. {
  398. ActiveClient* ac;
  399. foreach(ac, myClients)
  400. {
  401. ac->client()->disconnect();
  402. delete ac;
  403. }
  404. }
  405. App::~App()
  406. {
  407. cleanup();
  408. delete myServer;
  409. }
  410. void App::setReplyHash(const QString &serverAddress, const QString &hash)
  411. {
  412. ActiveClient* ac;
  413. foreach(ac, myClients)
  414. {
  415. if(serverAddress == ac->serverAddressString())
  416. {
  417. ac->setReplyHash(hash);
  418. return;
  419. }
  420. }
  421. }
  422. void App::incrementReplyCounters(const QString &hash, int userCount, int serverCount)
  423. {
  424. ActiveClient* ac;
  425. foreach(ac, myClients)
  426. {
  427. if(ac->replyHash() == hash)
  428. {
  429. ac->incrementReplyCounters(userCount, serverCount);
  430. return;
  431. }
  432. }
  433. }
  434. //========================================================================
  435. App::ActiveClient::ActiveClient(App *app):
  436. myApp(app),
  437. myClient(new Client(app)),
  438. myQueryThread(new ServerQueryThread()),
  439. myBroadcastReplyTimer(new QTimer()),
  440. myUniqueUserCount(0),
  441. myUniqueServerCount(0)
  442. {
  443. }
  444. App::ActiveClient::~ActiveClient()
  445. {
  446. delete myClient;
  447. if(queryThread()->isRunning())
  448. queryThread()->stopQueryThread();
  449. while(queryThread()->isRunning());
  450. delete myQueryThread;
  451. delete myBroadcastReplyTimer;
  452. }
  453. Client* App::ActiveClient::client()
  454. {
  455. return myClient;
  456. }
  457. ServerQueryThread* App::ActiveClient::queryThread()
  458. {
  459. return myQueryThread;
  460. }
  461. void App::ActiveClient::setAddress(const QHostAddress &address, quint16 port)
  462. {
  463. queryThread()->setAddress(address, port);
  464. }
  465. void App::ActiveClient::run()
  466. {
  467. /* If the client is disconnect check if there is at least one player connected to the server */
  468. if(client()->state() == Client::DisconnectedState)
  469. {
  470. if(!queryThread()->isRunning())
  471. {
  472. queryThread()->startQueryThread();
  473. return;
  474. }
  475. int playerCount = queryThread()->playerCount();
  476. if(playerCount != 255 && playerCount > 0 && myDisconnectTime.elapsed() > 10000)
  477. {
  478. myApp->print("Players online on server " + queryThread()->serverAddress().toString() + ":" + QString::number(queryThread()->serverPort()) + ". Joining...\n");
  479. client()->connect(queryThread()->serverAddress().toString().toAscii(), queryThread()->serverPort());
  480. }
  481. return;
  482. }
  483. /* If the client is connected and left alone on the server, disconnect yourself */
  484. if(client()->state() == Client::ConnectedState)
  485. {
  486. int playerCount = queryThread()->playerCount();
  487. if(playerCount == 1 && client()->isOnServer())
  488. {
  489. myApp->print("I was left alone on " + queryThread()->serverAddress().toString() + ":" + QString::number(queryThread()->serverPort()) + ". Leaving...\n");
  490. client()->disconnect();
  491. myDisconnectTime.restart();
  492. return;
  493. }
  494. }
  495. /* Say the broadcast count */
  496. if(!myBroadcastReplyTimer->isActive() && myReplyTimerWasActive)
  497. {
  498. myApp->activeClientsReplyCounters(&myUniqueServerCount, &myUniqueUserCount); //add my internal counter to the list
  499. client()->say("::cims:: Sent to " + QString::number(myUniqueServerCount) + " channels, " + QString::number(myUniqueUserCount) + " unique users.");
  500. myUniqueServerCount = myUniqueUserCount = 0;
  501. }
  502. myReplyTimerWasActive = myBroadcastReplyTimer->isActive();
  503. client()->run();
  504. }
  505. const QString App::ActiveClient::serverAddressString()
  506. {
  507. return QString(queryThread()->serverAddress().toString() + ':' + QString::number(queryThread()->serverPort()));
  508. }
  509. void App::ActiveClient::setReplyHash(const QString &hash)
  510. {
  511. myReplyHash = hash;
  512. /* Wait for 5 seconds */
  513. myBroadcastReplyTimer->setSingleShot(true);
  514. myBroadcastReplyTimer->start(5000);
  515. }
  516. const QString& App::ActiveClient::replyHash() const
  517. {
  518. return myReplyHash;
  519. }
  520. bool App::ActiveClient::isWaitingReply() const
  521. {
  522. return myBroadcastReplyTimer->isActive();
  523. }
  524. void App::ActiveClient::incrementReplyCounters(int userCount, int serverCount)
  525. {
  526. if(!myBroadcastReplyTimer->isActive())
  527. return;
  528. myUniqueUserCount += userCount;
  529. myUniqueServerCount += serverCount;
  530. }