ioman.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. #include "../include/ioman.h"
  2. #include "../include/global.h"
  3. #include <boost/asio.hpp>
  4. #include <iostream>
  5. #include <boost/algorithm/string.hpp>
  6. #include <string>
  7. #include <vector>
  8. #include <readline/history.h>
  9. #include <readline/readline.h>
  10. #include <poll.h>
  11. using std::string;
  12. using std::vector;
  13. using boost::asio::buffer;
  14. using boost::asio::ip::address;
  15. using boost::asio::ip::tcp;
  16. /* this will be provided by main.cpp for the readline callback */
  17. extern IoMan *gIOMAN;
  18. void ioman_externalDebugPrint(string msg) { gIOMAN->printMessage(msg, gIOMAN->OutMsgType::debug); }
  19. IoMan::IoMan(bool enablessl, const char *certfile) : cmdman(fileman, &ioman_externalDebugPrint), recvbuf(16384) {
  20. ipstring = "";
  21. port = 0;
  22. tcpsock = new tcp::socket(ios);
  23. connected = false;
  24. sendtimestampValid = false;
  25. /* setup json stuff */
  26. Json::CharReaderBuilder rbuilder;
  27. wbuilder.settings_["indentation"] = "";
  28. reader = rbuilder.newCharReader();
  29. runnetwork = false;
  30. runinput = false;
  31. runresponse = false;
  32. usessl = enablessl;
  33. if (usessl) {
  34. sslctx = new boost::asio::ssl::context(boost::asio::ssl::context::sslv23);
  35. sslctx->set_verify_mode(boost::asio::ssl::verify_peer);
  36. sslctx->set_options(boost::asio::ssl::context::no_sslv2);
  37. sslctx->load_verify_file(string(certfile), errcode);
  38. if (errcode) {
  39. throw std::runtime_error("Couldn't initialize SSL, Boost reports: " + errcode.message());
  40. }
  41. sslsock = new boost::asio::ssl::stream<tcp::socket &>(*tcpsock, *sslctx);
  42. }
  43. }
  44. IoMan::~IoMan() {
  45. if (connected) {
  46. disconnect();
  47. }
  48. if (runnetwork) {
  49. networkmutex.lock();
  50. runnetwork = false;
  51. networkmutex.unlock();
  52. tnetwork.join();
  53. }
  54. if (runinput) {
  55. inputmutex.lock();
  56. runinput = false;
  57. inputmutex.unlock();
  58. localcv.notify_all();
  59. tinput.join();
  60. }
  61. if (runresponse) {
  62. responsemutex.lock();
  63. runresponse = false;
  64. responsemutex.unlock();
  65. netcv.notify_all();
  66. tresponse.join();
  67. }
  68. if (usessl)
  69. delete sslsock;
  70. delete tcpsock;
  71. if (usessl)
  72. delete sslctx;
  73. delete reader;
  74. }
  75. void IoMan::printMessage(string nouse, OutMsgType nouse2) {}
  76. vector<string> IoMan::tokenizeInput(string in) {
  77. size_t prev, index, quot;
  78. vector<string> args;
  79. /* tokenize string into command and arguments vector*/
  80. if ((index = in.find(" ")) == string::npos) {
  81. // only command no args
  82. args.push_back(in);
  83. } else {
  84. args.push_back(in.substr(0, index));
  85. index++;
  86. bool end_tokenizing = false;
  87. while (!end_tokenizing) {
  88. // find first char thats not a space
  89. while (in[index] == ' ') {
  90. index++;
  91. // bounds check
  92. if (index == in.size())
  93. end_tokenizing = true;
  94. }
  95. if (end_tokenizing)
  96. break;
  97. in = in.substr(index);
  98. if (in[0] == '\"') {
  99. // quoted string
  100. in = in.substr(1);
  101. index = in.find("\"");
  102. args.push_back(in.substr(0, index));
  103. index++;
  104. /*
  105. tokens.push_back(in.substr(0, ++index));
  106. */
  107. // char after closing quote should be space while within bounds
  108. if (index == in.size())
  109. end_tokenizing = true;
  110. } else {
  111. // non-quoted string
  112. index = in.find(" ");
  113. if (index == string::npos) { // no spaces, last arg
  114. args.push_back(in);
  115. end_tokenizing = true;
  116. } else {
  117. args.push_back(in.substr(0, index));
  118. }
  119. }
  120. }
  121. }
  122. return args;
  123. }
  124. // callback for async connect, used to get timeout
  125. void connect_async_handler(const boost::system::error_code &error) { gIOMAN->errcode = error; }
  126. bool IoMan::connect() {
  127. tcp::endpoint *ep = NULL;
  128. address addr;
  129. Json::Value root;
  130. root["command"] = "connect";
  131. root["address"] = ipstring;
  132. root["port"] = port;
  133. addr = address::from_string(ipstring, errcode);
  134. if (errcode) {
  135. root["error"] = errcode.message();
  136. connected = false;
  137. } else {
  138. if (!ios.stopped())
  139. ios.stop();
  140. ios.restart();
  141. // establish connection
  142. printMessage(string(__PRETTY_FUNCTION__) + string(" connecting to ") + ipstring, debug);
  143. ep = new tcp::endpoint(addr, port);
  144. // connect never returns would_block, initialize errcode so we can determine whats up
  145. errcode = boost::asio::error::would_block;
  146. tcpsock->async_connect(*ep, &connect_async_handler);
  147. ios.run_for(std::chrono::seconds(5));
  148. //~ tcpsock->connect(*ep, errcode);
  149. if (errcode) {
  150. root["error"] = errcode.message();
  151. connected = false;
  152. disconnect();
  153. } else {
  154. connected = true;
  155. root["error"] = "";
  156. }
  157. delete ep;
  158. }
  159. if (usessl) {
  160. // try to do ssl handshake
  161. printMessage(string(__PRETTY_FUNCTION__) + string(" doing ssl handshake with ") + ipstring, debug);
  162. sslsock->handshake(boost::asio::ssl::stream_base::client, errcode);
  163. if (errcode) {
  164. root["error"] = errcode.message();
  165. connected = false;
  166. disconnect();
  167. } else {
  168. connected = true;
  169. root["error"] = "";
  170. }
  171. }
  172. root["accept"] = connected;
  173. printMessage(Json::writeString(wbuilder, root), normal);
  174. return connected;
  175. }
  176. void IoMan::disconnect() {
  177. printMessage("IoMan::disconnect()", debug);
  178. tcpsock->shutdown(tcp::socket::shutdown_both, errcode);
  179. if (errcode)
  180. printMessage(string(__PRETTY_FUNCTION__) + string("tcp shutdown says ") + errcode.message(), debug);
  181. tcpsock->close(errcode);
  182. if (errcode)
  183. printMessage(string(__PRETTY_FUNCTION__) + string("tcp shutdown says ") + errcode.message(), debug);
  184. connected = false;
  185. cmdman.stateSetDisconnected();
  186. }
  187. bool IoMan::init() {
  188. CmdMan::CmdRet ret;
  189. string work;
  190. Json::Value root;
  191. std::unique_lock<std::mutex> ulock;
  192. printMessage(string(__PRETTY_FUNCTION__) + string(" begin"), debug);
  193. runinput = true;
  194. runresponse = true;
  195. tinput = std::thread(&IoMan::inputMain, this);
  196. tresponse = std::thread(&IoMan::responseMain, this);
  197. printWelcomeMessage();
  198. return true;
  199. }
  200. /* loop to fetch data from the network, doing light preprocessing on it to be
  201. * handled by responseMain */
  202. void IoMan::networkMain() {
  203. vector<Json::Value> toput;
  204. char *recvjson;
  205. Json::Value root;
  206. unsigned int jsonsize, readsize;
  207. bool firstWasGood = false;
  208. printMessage("IoMan::networkMain() begin", debug);
  209. networkmutex.lock();
  210. while (runnetwork) {
  211. networkmutex.unlock();
  212. /*
  213. read from network until \n
  214. try to parse json
  215. - output error if not ok
  216. store all ok json in local vector
  217. get networkmutex
  218. put all local jsons into network vector
  219. release networkmutex
  220. */
  221. // read from network
  222. if (usessl)
  223. readsize = boost::asio::read_until(*sslsock, recvbuf, '\n', errcode);
  224. else
  225. readsize = boost::asio::read_until(*tcpsock, recvbuf, '\n', errcode);
  226. printMessage(string(__PRETTY_FUNCTION__) + string(" asio::read() ok ") + std::to_string(readsize), debug);
  227. // printMessage(string("have ") + std::to_string(toprocess.size()) +
  228. // string(" commands"), debug);
  229. timestampmutex.lock();
  230. sendtimestampValid = false;
  231. timestampmutex.unlock();
  232. if (readsize < 1) {
  233. break;
  234. }
  235. if (errcode && errcode != boost::asio::error::eof) {
  236. printMessage("IoMan::networkMain() couldnt read json data\n" + errcode.message(), debug);
  237. continue;
  238. }
  239. recvjson = (char *)(boost::asio::buffer_cast<const char *>(recvbuf.data()));
  240. recvjson[recvbuf.size()] = 0;
  241. while (strchr(recvjson, '\n')) {
  242. // parse
  243. jsonsize = strchr(recvjson, '\n') - recvjson + 1;
  244. printMessage(string(__PRETTY_FUNCTION__) + string(" found jsondata ") + string(recvjson), debug);
  245. if (!reader->parse(recvjson, recvjson + jsonsize, &root, &jsonerror)) {
  246. printMessage("IoMan::networkMain() couldnt parse json data: " + jsonerror, debug);
  247. if (firstWasGood) {
  248. // we found garbage at the end
  249. break;
  250. }
  251. // we found garbage at the beginning
  252. recvbuf.consume(jsonsize);
  253. recvjson += jsonsize;
  254. continue;
  255. }
  256. firstWasGood = true;
  257. recvbuf.consume(jsonsize);
  258. printMessage(string(__PRETTY_FUNCTION__) + string(" remaining recvbuf ") + string(boost::asio::buffer_cast<const char *>(recvbuf.data())), debug);
  259. recvjson += jsonsize;
  260. // store locally
  261. toput.push_back(root);
  262. }
  263. firstWasGood = false;
  264. if (toput.size()) {
  265. // put into global vector
  266. netmutex.lock();
  267. printMessage(string(__PRETTY_FUNCTION__) + string(" get netmutex"), debug);
  268. netinput.insert(netinput.end(), toput.begin(), toput.end());
  269. netmutex.unlock();
  270. printMessage(string(__PRETTY_FUNCTION__) + string(" release netmutex"), debug);
  271. }
  272. netcv.notify_all();
  273. // clean up local stuff
  274. toput = vector<Json::Value>();
  275. recvbuf.consume(recvbuf.size() + 1);
  276. networkmutex.lock();
  277. }
  278. }
  279. /* loop to handle input from the user and responseMain, sending data via network
  280. * if required */
  281. void IoMan::inputMain() {
  282. vector<string> toprocess;
  283. string command;
  284. vector<string> args;
  285. CmdMan::CmdRet cmdret;
  286. std::unique_lock<std::mutex> ulock;
  287. printMessage(string(__PRETTY_FUNCTION__) + string(" begin"), debug);
  288. inputmutex.lock();
  289. while (runinput) {
  290. inputmutex.unlock();
  291. /*
  292. get inputmutex
  293. read all input vector into local vector
  294. release inputmutex
  295. process inputs
  296. send to server if required
  297. */
  298. // read into local vector
  299. ulock = std::unique_lock<std::mutex>(localmutex);
  300. while (!localinput.size() && runinput) {
  301. localcv.wait(ulock);
  302. }
  303. printMessage(string(__PRETTY_FUNCTION__) + string(" has localmutex"), debug);
  304. toprocess = vector<string>(localinput);
  305. localinput = vector<string>();
  306. localmutex.unlock();
  307. printMessage(string(__PRETTY_FUNCTION__) + string(" release localmutex"), debug);
  308. localcv.notify_all();
  309. if (!runinput)
  310. return;
  311. // printMessage(string("have ") + std::to_string(toprocess.size()) +
  312. // string(" commands"), debug);
  313. // process
  314. for (string cmd : toprocess) {
  315. args = tokenizeInput(cmd);
  316. command = args.front();
  317. args.erase(args.begin());
  318. cmdret = cmdman.execute(command, args);
  319. handleInCmdResponse(cmdret);
  320. }
  321. // clean up local stuff
  322. toprocess = vector<string>();
  323. inputmutex.lock();
  324. }
  325. }
  326. void IoMan::handleInCmdResponse(CmdMan::CmdRet cmdret) {
  327. // determine wether to send something and do so if required
  328. if (cmdret.type & CmdMan::rettype::print) {
  329. printMessage(Json::writeString(wbuilder, cmdret.msg), normal);
  330. }
  331. if (cmdret.type & CmdMan::rettype::send) {
  332. printMessage("IoMan::inputMain() sending json \"" + Json::writeString(wbuilder, cmdret.msg) + "\"", debug);
  333. timestampmutex.lock();
  334. if (!sendtimestampValid) {
  335. if (cmdret.type & CmdMan::rettype::noanswerexpected) {
  336. // there will be no answer from the server, do not set a timestamp
  337. } else {
  338. sendtimestampValid = true;
  339. time(&sendtimestamp); // set timestamp
  340. }
  341. }
  342. timestampmutex.unlock();
  343. if (usessl)
  344. boost::asio::write(*sslsock, buffer(Json::writeString(wbuilder, cmdret.msg) + "\n"), errcode);
  345. else
  346. boost::asio::write(*tcpsock, buffer(Json::writeString(wbuilder, cmdret.msg) + "\n"), errcode);
  347. if (errcode) {
  348. printMessage("IoMan::inputMain() couldnt send json data\n" + errcode.message() + "\n", debug);
  349. return;
  350. }
  351. }
  352. if (cmdret.type & CmdMan::rettype::error) {
  353. printMessage(Json::writeString(wbuilder, cmdret.msg), error);
  354. }
  355. if (cmdret.type & CmdMan::rettype::close) {
  356. // connection closed, stop network thread and shutdown any operations remaining
  357. networkmutex.lock();
  358. runnetwork = false;
  359. networkmutex.unlock();
  360. disconnect();
  361. tnetwork.join();
  362. }
  363. if (cmdret.type & CmdMan::rettype::connect) {
  364. ipstring = cmdret.msg["address"].asString();
  365. port = cmdret.msg["port"].asUInt();
  366. if (connect()) {
  367. runnetwork = true;
  368. tnetwork = std::thread(&IoMan::networkMain, this);
  369. // put new commands into global vector
  370. localmutex.lock();
  371. printMessage(string(__PRETTY_FUNCTION__) + string(" get localmutex"), debug);
  372. localinput.push_back("version");
  373. cmdman.stateSetConnectionOk();
  374. localmutex.unlock();
  375. printMessage(string(__PRETTY_FUNCTION__) + string(" release localmutex"), debug);
  376. localcv.notify_all();
  377. }
  378. }
  379. if (cmdret.type & CmdMan::rettype::exit) {
  380. mainmutex.lock();
  381. runmain = false;
  382. mainmutex.unlock();
  383. }
  384. if (cmdret.nextcommand.size()) {
  385. localmutex.lock();
  386. printMessage(string(__PRETTY_FUNCTION__) + string(" get localmutex"), debug);
  387. localinput.push_back(cmdret.nextcommand);
  388. localmutex.unlock();
  389. printMessage(string(__PRETTY_FUNCTION__) + string(" release localmutex"), debug);
  390. localcv.notify_all();
  391. }
  392. }
  393. /* loop to handle responses that have been fetched by netMain and possibly add
  394. * new commands to be handled by inputMain */
  395. void IoMan::responseMain() {
  396. vector<Json::Value> toprocess;
  397. vector<string> toput;
  398. CmdMan::CmdRet cmdret;
  399. std::unique_lock<std::mutex> ulock;
  400. printMessage(string(__PRETTY_FUNCTION__) + string(" begin"), debug);
  401. responsemutex.lock();
  402. while (runresponse) {
  403. responsemutex.unlock();
  404. /*
  405. get networkmutex
  406. read all network vector into local vector
  407. release networkmutex
  408. process all jsons
  409. process putdata
  410. process getdata
  411. process listdata
  412. get inputmutex
  413. place new commands into input vector
  414. release inputmutex
  415. */
  416. // read into local vector
  417. ulock = std::unique_lock<std::mutex>(netmutex);
  418. while (!netinput.size() && runresponse) {
  419. netcv.wait(ulock);
  420. }
  421. printMessage(string(__PRETTY_FUNCTION__) + string(" get netmutex"), debug);
  422. toprocess = vector<Json::Value>(netinput);
  423. netinput = vector<Json::Value>();
  424. netmutex.unlock();
  425. printMessage(string(__PRETTY_FUNCTION__) + string(" release netmutex"), debug);
  426. netcv.notify_all();
  427. if (!runresponse)
  428. return;
  429. // process jsons
  430. for (Json::Value root : toprocess) {
  431. cmdret = cmdman.handle(root);
  432. handleOutCmdResponse(cmdret, toput);
  433. }
  434. if (toput.size()) {
  435. // put new commands into global vector
  436. localmutex.lock();
  437. printMessage(string(__PRETTY_FUNCTION__) + string(" get localmutex"), debug);
  438. localinput.insert(localinput.end(), toput.begin(), toput.end());
  439. localmutex.unlock();
  440. printMessage(string(__PRETTY_FUNCTION__) + string(" release localmutex"), debug);
  441. }
  442. localcv.notify_all();
  443. // clean up local stuff
  444. toprocess = vector<Json::Value>();
  445. toput = vector<string>();
  446. responsemutex.lock();
  447. }
  448. }
  449. void IoMan::handleOutCmdResponse(CmdMan::CmdRet cmdret, vector<string> &toput) {
  450. if (cmdret.type & CmdMan::rettype::close) {
  451. // connection closed, stop network thread and shutdown any operations remaining
  452. networkmutex.lock();
  453. runnetwork = false;
  454. networkmutex.unlock();
  455. disconnect();
  456. tnetwork.join();
  457. if (cmdret.nextcommand.size()) {
  458. toput.push_back(cmdret.nextcommand);
  459. }
  460. }
  461. if (cmdret.type & CmdMan::rettype::error) {
  462. printMessage(Json::writeString(wbuilder, cmdret.msg), error);
  463. }
  464. if (cmdret.type & CmdMan::rettype::print) {
  465. printMessage(Json::writeString(wbuilder, cmdret.msg), normal);
  466. }
  467. if (cmdret.type & CmdMan::rettype::send) {
  468. if (cmdret.nextcommand.size()) {
  469. toput.push_back(cmdret.nextcommand);
  470. }
  471. }
  472. if (cmdret.type & CmdMan::rettype::exit) {
  473. mainmutex.lock();
  474. runmain = false;
  475. mainmutex.unlock();
  476. }
  477. }
  478. /* this is the handler that readlines alternative interface will use to process
  479. * user input */
  480. void ioman_readlineHandler(char *line) {
  481. vector<string> tokens;
  482. if (!line) {
  483. printf("\nNULLBURGER\n");
  484. gIOMAN->mainmutex.lock();
  485. gIOMAN->runmain = false;
  486. gIOMAN->mainmutex.unlock();
  487. } else {
  488. // split input line into tokens
  489. boost::algorithm::split(tokens, std::string(line), boost::algorithm::is_any_of(" "), boost::algorithm::token_compress_on);
  490. if (strlen(line) && tokens.size()) {
  491. add_history(line);
  492. gIOMAN->localmutex.lock();
  493. gIOMAN->printMessage(string(__PRETTY_FUNCTION__) + string(" get localmutex"), gIOMAN->debug);
  494. gIOMAN->localinput.push_back(line);
  495. gIOMAN->localmutex.unlock();
  496. gIOMAN->printMessage(string(__PRETTY_FUNCTION__) + string(" release localmutex"), gIOMAN->debug);
  497. gIOMAN->localcv.notify_all();
  498. }
  499. free(line);
  500. }
  501. }
  502. /* main user input loop */
  503. void IoMan::run() {
  504. printMessage(string(__PRETTY_FUNCTION__) + string(" begin"), debug);
  505. struct pollfd inpipestatus;
  506. inpipestatus.fd = STDIN_FILENO;
  507. inpipestatus.events = POLLIN;
  508. runmain = true;
  509. // Install readline handler
  510. rl_callback_handler_install(getCmdPrompt().c_str(), (rl_vcpfunc_t *)&ioman_readlineHandler);
  511. mainmutex.lock();
  512. while (runmain) {
  513. mainmutex.unlock();
  514. timestampmutex.lock();
  515. if (sendtimestampValid && std::difftime(time(NULL), sendtimestamp) > 15) {
  516. // answer took more than 15 seconds
  517. disconnect();
  518. // cmdman gets informed inside disconnect method
  519. // inform the user by giving output
  520. Json::Value root;
  521. root["command"] = "connectionerror";
  522. root["error"] = "The server does not respond. You are now disconnected.";
  523. printMessage(Json::writeString(wbuilder, root), normal);
  524. sendtimestampValid = false;
  525. }
  526. timestampmutex.unlock();
  527. poll(&inpipestatus, 1, 100);
  528. if (inpipestatus.revents & POLLIN) {
  529. rl_callback_read_char();
  530. }
  531. mainmutex.lock();
  532. }
  533. mainmutex.unlock();
  534. // Clean up the terminal
  535. rl_set_prompt("");
  536. rl_replace_line("", 0);
  537. rl_redisplay();
  538. rl_clear_history();
  539. // Remove the handler
  540. rl_callback_handler_remove();
  541. }