client.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. #include <include/client.hpp>
  2. #include <arpa/inet.h>
  3. #include <netdb.h>
  4. #include <string.h>
  5. #include <sys/socket.h>
  6. #include <sys/types.h>
  7. #include <unistd.h>
  8. #include <functional>
  9. #include <algorithm>
  10. #include <cstring>
  11. #include <QDebug>
  12. #include <QByteArray>
  13. #include <iostream>
  14. #include <vector>
  15. #include <future>
  16. #define FLATBUFFERS_DEBUG_VERIFICATION_FAILURE
  17. #include <headers/kmessage_codec.hpp>
  18. #include <headers/instatask_generated.h>
  19. using namespace KData;
  20. using namespace IGData;
  21. static const int MAX_PACKET_SIZE = 4096;
  22. static const int HEADER_SIZE = 4;
  23. flatbuffers::FlatBufferBuilder builder(1024);
  24. /**
  25. * @brief Client::createMessageHandler
  26. * @param [in] {std::function<void()>} cb A non-returning function to be called without parameter
  27. * @returns {MessageHandler} A message loop handler
  28. */
  29. Client::MessageHandler Client::createMessageHandler(
  30. std::function<void()> cb) {
  31. return MessageHandler(cb);
  32. }
  33. /**
  34. * @brief Client::Client
  35. * @constructor
  36. * @param [in] {QWidget*} parent
  37. * @param [in] {int} count
  38. * @param [in] {char**} arguments
  39. */
  40. Client::Client(QWidget *parent, int count, char** arguments) : QDialog(parent), argc(count), argv(arguments), m_client_socket_fd(-1), m_commands({}), executing(false) {
  41. qRegisterMetaType<QVector<QString>>("QVector<QString>");
  42. }
  43. /**
  44. * @brief Client::~Client
  45. * @destructor
  46. */
  47. Client::~Client() {
  48. closeConnection();
  49. }
  50. /**
  51. * @brief Client::handleMessages
  52. */
  53. void Client::handleMessages() {
  54. uint8_t receive_buffer[MAX_PACKET_SIZE];
  55. for (;;) {
  56. memset(receive_buffer, 0, MAX_PACKET_SIZE);
  57. ssize_t bytes_received = 0;
  58. bytes_received = recv(m_client_socket_fd, receive_buffer, MAX_PACKET_SIZE, 0);
  59. if (bytes_received == 0) { // Finish message loop
  60. break;
  61. }
  62. size_t end_idx = findNullIndex(receive_buffer);
  63. std::string data_string{receive_buffer, receive_buffer + end_idx};
  64. qDebug() << "Received data from KServer: \n" << data_string.c_str();
  65. if (isPong(data_string.c_str())) {
  66. qDebug() << "Server returned pong";
  67. continue;
  68. }
  69. StringVec s_v{};
  70. if (isNewSession(data_string.c_str())) { // Session Start
  71. m_commands = getArgMap(data_string.c_str());
  72. for (const auto& [k, v] : m_commands) { // Receive available commands
  73. s_v.push_back(v.data());
  74. }
  75. emit Client::messageReceived(COMMANDS_UPDATE_TYPE, "New Session", s_v); // Update UI
  76. } else if (serverWaitingForFile(data_string.c_str())) { // Server expects a file
  77. processFileQueue();
  78. } else if (isEvent(data_string.c_str())) { // Receiving event
  79. QString event = getEvent(data_string.c_str());
  80. QVector<QString> args = getArgs(data_string.c_str());
  81. emit Client::messageReceived(EVENT_UPDATE_TYPE, event, args); // Update UI (event)
  82. if (isUploadCompleteEvent(event.toUtf8().constData())) { // Upload complete
  83. if (!args.isEmpty()) {
  84. sent_files.at(sent_files.size() - 1).timestamp = std::stoi(args.at(0).toUtf8().constData());
  85. if (outgoing_files.isEmpty()) {
  86. sendTaskEncoded(TaskType::INSTAGRAM, m_task);
  87. } else {
  88. sendEncoded(createOperation("FileUpload", {"Subsequent file"}));
  89. }
  90. }
  91. }
  92. }
  93. std::string formatted_json = getJsonString(data_string);
  94. emit Client::messageReceived(MESSAGE_UPDATE_TYPE, QString::fromUtf8(formatted_json.data(), formatted_json.size()), {});
  95. }
  96. memset(receive_buffer, 0, 2048);
  97. ::close(m_client_socket_fd);
  98. // ::shutdown(m_client_socket_fd, SHUT_RDWR);
  99. }
  100. void Client::processFileQueue() {
  101. KFileData outgoing_file = outgoing_files.dequeue();
  102. sendFileEncoded(outgoing_file.bytes);
  103. sent_files.push_back(SentFile{.name = outgoing_file.name, .type = outgoing_file.type });
  104. }
  105. /**
  106. * @brief Client::start
  107. */
  108. void Client::start() {
  109. if (m_client_socket_fd == -1) {
  110. m_client_socket_fd = socket(AF_INET, SOCK_STREAM, 0);
  111. if (m_client_socket_fd != -1) {
  112. sockaddr_in server_socket;
  113. char* end;
  114. server_socket.sin_family = AF_INET;
  115. auto port_value = strtol(argv[2], &end, 10);
  116. if (port_value < 0 || end == argv[2]) {
  117. return;
  118. }
  119. int socket_option = 1;
  120. // Free up the port to begin listening again
  121. setsockopt(m_client_socket_fd, SOL_SOCKET, SO_REUSEADDR, &socket_option,
  122. sizeof(socket_option));
  123. server_socket.sin_port = htons(port_value);
  124. inet_pton(AF_INET, argv[1], &server_socket.sin_addr.s_addr);
  125. if (::connect(m_client_socket_fd, reinterpret_cast<sockaddr*>(&server_socket),
  126. sizeof(server_socket)) != -1) {
  127. std::string start_operation_string = createOperation("start", {});
  128. // Send operation as an encoded message
  129. sendEncoded(start_operation_string);
  130. // Delegate message handling to its own thread
  131. std::function<void()> message_send_fn = [this]() {
  132. this->handleMessages();
  133. };
  134. MessageHandler message_handler = createMessageHandler(message_send_fn);
  135. // Handle received messages on separate thread
  136. std::thread (message_handler).detach();
  137. } else {
  138. qDebug() << errno;
  139. ::close(m_client_socket_fd);
  140. }
  141. } else {
  142. qDebug() << "Failed to create new connection";
  143. }
  144. } else {
  145. qDebug() << "Connection already in progress";
  146. }
  147. }
  148. /**
  149. * @brief Client::sendMessage
  150. * @param [in] {const QString&} The message to send
  151. */
  152. void Client::sendMessage(const QString& s) {
  153. if (m_client_socket_fd != -1) {
  154. std::string json_string {"{\"type\":\"custom\", \"message\": \""};
  155. json_string += s.toUtf8().data();
  156. json_string += "\", \"args\":\"placeholder\"}";
  157. // Send custom message as an encoded message
  158. sendEncoded(json_string);
  159. } else {
  160. qDebug() << "You must first open a connection";
  161. }
  162. }
  163. /**
  164. * @brief Client::sendEncoded
  165. * @param [in] {std::string message} The message to send
  166. */
  167. void Client::sendEncoded(std::string message) {
  168. std::vector<uint8_t> fb_byte_vector{message.begin(), message.end()};
  169. auto byte_vector = builder.CreateVector(fb_byte_vector);
  170. auto k_message = CreateMessage(builder, 69, byte_vector);
  171. builder.Finish(k_message);
  172. uint8_t* encoded_message_buffer = builder.GetBufferPointer();
  173. uint32_t size = builder.GetSize();
  174. uint8_t send_buffer[MAX_PACKET_SIZE];
  175. memset(send_buffer, 0, MAX_PACKET_SIZE);
  176. send_buffer[0] = (size & 0xFF) >> 24;
  177. send_buffer[1] = (size & 0xFF) >> 16;
  178. send_buffer[2] = (size & 0xFF) >> 8;
  179. send_buffer[3] = (size & 0xFF);
  180. send_buffer[4] = (TaskCode::GENMSGBYTE & 0xFF);
  181. std::memcpy(send_buffer + 5, encoded_message_buffer, size);
  182. qDebug() << "Sending encoded message";
  183. std::string message_to_send{};
  184. for (unsigned int i = 0; i < (size + 5); i++) {
  185. message_to_send += (char)*(send_buffer + i);
  186. }
  187. qDebug() << "Encoded message size: " << (size + 5);
  188. // Send start operation
  189. ::send(m_client_socket_fd, send_buffer, size + 5, 0);
  190. builder.Clear();
  191. }
  192. /**
  193. * @brief getTaskFileInfo
  194. * @param [in] {std::vector<SentFile>} files The files to produce an information string from
  195. * @return std::string A string with the following format denoting each file:
  196. * `1580057341filename|image::`
  197. */
  198. std::string getTaskFileInfo(std::vector<SentFile> files) {
  199. std::string info{};
  200. for (const auto& f : files) {
  201. info += std::to_string(f.timestamp);
  202. info += f.name.toUtf8().constData();
  203. info += "|";
  204. if (f.type == FileType::VIDEO) {
  205. info += "video";
  206. } else {
  207. info += "image";
  208. }
  209. info += "::";
  210. }
  211. qDebug() << "File Info: " << info.c_str();
  212. return info;
  213. }
  214. /**
  215. * @brief Client::sendTaskEncoded
  216. * @param [in] {TaskType} type The type of task
  217. * @param [in] {std::vector<std::string>} args The task arguments
  218. */
  219. void Client::sendTaskEncoded(TaskType type, std::vector<std::string> args) {
  220. if (type == TaskType::INSTAGRAM) {
  221. if (args.size() < 7) {
  222. qDebug() << "Not enough arguments to send an IGTask";
  223. return;
  224. }
  225. auto file_info = builder.CreateString(getTaskFileInfo(sent_files));
  226. auto time = builder.CreateString(args.at(0).c_str(), args.at(0).size());
  227. auto description = builder.CreateString(args.at(1).c_str(), args.at(1).size());
  228. auto hashtags = builder.CreateString(args.at(2).c_str(), args.at(2).size());
  229. auto requested_by = builder.CreateString(args.at(3).c_str(), args.at(3).size());
  230. auto requested_by_phrase = builder.CreateString(args.at(4).c_str(), args.at(4).size());
  231. auto promote_share = builder.CreateString(args.at(5).c_str(), args.at(5).size());
  232. auto link_bio = builder.CreateString(args.at(6).c_str(), args.at(6).size());
  233. auto is_video = args.at(7) == "1";
  234. auto header = builder.CreateString(args.at(8).c_str(), args.at(8).size());
  235. flatbuffers::Offset<IGTask> ig_task = CreateIGTask(builder, 96, file_info, time, description, hashtags, requested_by, requested_by_phrase, promote_share, link_bio, is_video, 16, header);
  236. builder.Finish(ig_task);
  237. uint8_t* encoded_message_buffer = builder.GetBufferPointer();
  238. uint32_t size = builder.GetSize();
  239. uint8_t send_buffer[MAX_PACKET_SIZE];
  240. memset(send_buffer, 0, MAX_PACKET_SIZE);
  241. send_buffer[0] = (size >> 24) & 0xFF;
  242. send_buffer[1] = (size >> 16) & 0xFF;
  243. send_buffer[2] = (size >> 8) & 0xFF;
  244. send_buffer[3] = size & 0xFF;
  245. send_buffer[4] = (TaskCode::IGTASKBYTE & 0xFF);
  246. std::memcpy(send_buffer + 5, encoded_message_buffer, size);
  247. qDebug() << "Ready to send:";
  248. std::string message_to_send{};
  249. for (unsigned int i = 0; i < (size + 5); i++) {
  250. message_to_send += (char)*(send_buffer + i);
  251. qDebug() << (char)*(send_buffer + i);
  252. }
  253. qDebug() << "Final size: " << (size + 5);
  254. // Send start operation
  255. ::send(m_client_socket_fd, send_buffer, size + 5, 0);
  256. builder.Clear();
  257. sent_files.clear();
  258. }
  259. }
  260. /**
  261. * @brief Client::sendPackets
  262. * @param [in] {uint8_t*} data A pointer to a buffer of bytes
  263. * @param [in] {int} size The size of the buffer to be packetized and sent
  264. */
  265. void Client::sendPackets(uint8_t* data, int size) {
  266. uint32_t total_size = static_cast<uint32_t>(size + HEADER_SIZE);
  267. uint32_t total_packets = static_cast<uint32_t>(ceil(
  268. static_cast<double>(
  269. static_cast<double>(total_size) / static_cast<double>(MAX_PACKET_SIZE)) // total size / packet
  270. )
  271. );
  272. uint32_t idx = 0;
  273. for (; idx < total_packets; idx++) {
  274. bool is_first_packet = (idx == 0);
  275. bool is_last_packet = (idx == (total_packets - 1));
  276. if (is_first_packet) {
  277. uint32_t first_packet_size =
  278. std::min(size + HEADER_SIZE, MAX_PACKET_SIZE);
  279. uint8_t packet[first_packet_size];
  280. packet[0] = (total_size >> 24) & 0xFF;
  281. packet[1] = (total_size >> 16) & 0xFF;
  282. packet[2] = (total_size >> 8) & 0xFF;
  283. packet[3] = (total_size) & 0xFF;
  284. std::memcpy(packet + HEADER_SIZE, data, first_packet_size - HEADER_SIZE);
  285. /**
  286. * SEND PACKET !!!
  287. */
  288. ::send(m_client_socket_fd, packet, first_packet_size, 0);
  289. if (is_last_packet) {
  290. break;
  291. }
  292. continue;
  293. }
  294. int offset = (idx * MAX_PACKET_SIZE) - HEADER_SIZE;
  295. uint32_t packet_size = std::min(size - offset, MAX_PACKET_SIZE);
  296. uint8_t packet[packet_size];
  297. std::memcpy(packet, data + offset, packet_size);
  298. /**
  299. * SEND PACKET !!!
  300. */
  301. ::send(m_client_socket_fd, packet, packet_size, 0);
  302. if (is_last_packet) {
  303. // cleanup
  304. qDebug() << "Last packet of file sent";
  305. }
  306. }
  307. }
  308. void Client::ping() {
  309. if (m_client_socket_fd != -1) {
  310. uint8_t send_buffer[5];
  311. memset(send_buffer, 0, 5);
  312. send_buffer[4] = (TaskCode::PINGBYTE & 0xFF);
  313. qDebug() << "Pinging server";
  314. ::send(m_client_socket_fd, send_buffer, 5, 0);
  315. }
  316. }
  317. /**
  318. * @brief Client::sendFileEncoded
  319. * @param [in] {QByteArray} bytes An array of bytes to send
  320. */
  321. void Client::sendFileEncoded(QByteArray bytes) {
  322. sendPackets(reinterpret_cast<uint8_t*>(bytes.data()), bytes.size());
  323. }
  324. /**
  325. * @brief Client::closeConnection
  326. */
  327. void Client::closeConnection() {
  328. if (m_client_socket_fd != -1) {
  329. std::string stop_operation_string = createOperation("stop", {});
  330. // Send operation as an encoded message
  331. sendEncoded(stop_operation_string);
  332. // Clean up socket file descriptor
  333. ::shutdown(m_client_socket_fd, SHUT_RDWR);
  334. ::close(m_client_socket_fd);
  335. m_client_socket_fd = -1;
  336. return;
  337. }
  338. qDebug() << "There is no active connection to close";
  339. }
  340. /**
  341. * @brief Client::setSelectedApp
  342. * @param [in] TYPE SHOULD CHANGE app_names
  343. */
  344. void Client::setSelectedApp(std::vector<QString> app_names) {
  345. selected_commands.clear();
  346. for (const auto& name : app_names) {
  347. qDebug() << "Matching mask to " << name;
  348. for (const auto& command : m_commands) {
  349. if (command.second.c_str() == name.toUtf8()) {
  350. selected_commands.push_back(command.first);
  351. }
  352. }
  353. }
  354. }
  355. /**
  356. * @brief Client::getSelectedApp
  357. * @returns {int} The mask representing the selected application
  358. */
  359. int Client::getSelectedApp() {
  360. if (selected_commands.size() == 1) {
  361. return selected_commands.at(0);
  362. } else {
  363. QMessageBox::warning(this, tr("App Selection Error"), tr("Unable to retrieve app selection"));
  364. }
  365. return -1;
  366. }
  367. /**
  368. * @brief Client::getAppName
  369. * @param [in] {int} mask The mask representing the application
  370. * @returns {QString} The application name
  371. */
  372. QString Client::getAppName(int mask) {
  373. auto app = m_commands.find(mask);
  374. if (app != m_commands.end()) {
  375. return QString{app->second.c_str()};
  376. }
  377. return QString{""};
  378. }
  379. /**
  380. * @brief Client::execute
  381. */
  382. void Client::execute() {
  383. if (!selected_commands.empty()) {
  384. executing = true;
  385. for (const auto& command : selected_commands) {
  386. auto app_name = getAppName(command);
  387. auto message = app_name + " pending";
  388. auto request_id = QUuid::createUuid().toString(QUuid::StringFormat::WithoutBraces);
  389. emit Client::messageReceived(PROCESS_REQUEST_TYPE, message, { QString{command}, app_name, request_id });
  390. std::string execute_operation = createOperation("Execute", {std::to_string(command), std::string(request_id.toUtf8().constData())});
  391. sendEncoded(execute_operation);
  392. }
  393. }
  394. }
  395. /**
  396. * @brief Client::scheduleTask
  397. * @param [in] {std::vector<std::string>} task_args The task arguments
  398. * @param [in] {bool} file_pending A boolean indicating whether there are files being sent for this task
  399. */
  400. void Client::scheduleTask(std::vector<std::string> task_args, bool file_pending) {
  401. if (file_pending) {
  402. m_task = task_args;
  403. } else {
  404. qDebug() << "Requesting a task to be scheduled";
  405. sendTaskEncoded(TaskType::INSTAGRAM, task_args);
  406. }
  407. }
  408. /**
  409. * @brief Client::sendFiles
  410. * @param [in] {QVector<const QByteArray} files The files to be sent
  411. */
  412. void Client::sendFiles(QVector<KFileData> files) {
  413. if (outgoing_files.isEmpty()) {
  414. for (const auto & file : files) {
  415. outgoing_files.enqueue(file);
  416. }
  417. std::string send_file_operation = createOperation("FileUpload", {});
  418. sendEncoded(send_file_operation);
  419. } else {
  420. qDebug() << "Still attempting to send a different file";
  421. }
  422. }