client.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. #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. #include <headers/kmessage_codec.hpp>
  17. #include <headers/json.hpp>
  18. #include <headers/util.hpp>
  19. using namespace KData;
  20. using json = nlohmann::json;
  21. static const int MAX_BUFFER_SIZE = 2048;
  22. static const int MAX_PACKET_SIZE = 4096;
  23. static const int HEADER_SIZE = 4;
  24. flatbuffers::FlatBufferBuilder builder(1024);
  25. /**
  26. * @brief Client::createMessageHandler
  27. * @param cb
  28. * @return
  29. */
  30. Client::MessageHandler Client::createMessageHandler(
  31. std::function<void()> cb) {
  32. return MessageHandler(cb);
  33. }
  34. /**
  35. * @brief Client::Client
  36. * @constructor
  37. * @param parent
  38. * @param count
  39. * @param arguments
  40. */
  41. Client::Client(QWidget *parent, int count, char** arguments) : QDialog(parent), argc(count), argv(arguments), m_client_socket_fd(-1), m_commands({}), executing(false) {
  42. qRegisterMetaType<QVector<QString>>("QVector<QString>");
  43. }
  44. /**
  45. * @brief Client::~Client
  46. * @destructor
  47. */
  48. Client::~Client() {
  49. closeConnection();
  50. }
  51. /**
  52. * @brief Client::handleMessages
  53. */
  54. void Client::handleMessages() {
  55. uint8_t receive_buffer[2048];
  56. for (;;) {
  57. memset(receive_buffer, 0, 2048);
  58. ssize_t bytes_received = 0;
  59. bytes_received = recv(m_client_socket_fd, receive_buffer, 2048 - 2, 0);
  60. receive_buffer[2047] = 0;
  61. if (bytes_received == 0) {
  62. break;
  63. }
  64. size_t end_idx = findNullIndex(receive_buffer);
  65. std::string data_string{receive_buffer, receive_buffer + end_idx};
  66. StringVec s_v{};
  67. if (isNewSession(data_string.c_str())) {
  68. m_commands = getArgMap(data_string.c_str());
  69. for (const auto& [k, v] : m_commands) {
  70. s_v.push_back(v.data());
  71. }
  72. emit Client::messageReceived(COMMANDS_UPDATE_TYPE, "", s_v);
  73. } else if(serverWaitingForFile(data_string.c_str())) {
  74. sendFileEncoded(outgoing_file);
  75. }
  76. std::string formatted_json = getJsonString(data_string);
  77. emit Client::messageReceived(MESSAGE_UPDATE_TYPE, QString::fromUtf8(formatted_json.data(), formatted_json.size()), {});
  78. }
  79. memset(receive_buffer, 0, 2048);
  80. ::close(m_client_socket_fd);
  81. }
  82. /**
  83. * @brief Client::start
  84. * @return A meaningless integer
  85. */
  86. void Client::start() {
  87. if (m_client_socket_fd == -1) {
  88. m_client_socket_fd = socket(AF_INET, SOCK_STREAM, 0);
  89. if (m_client_socket_fd != -1) {
  90. sockaddr_in server_socket;
  91. char* end;
  92. server_socket.sin_family = AF_INET;
  93. auto port_value = strtol(argv[2], &end, 10);
  94. if (port_value < 0 || end == argv[2]) {
  95. return;
  96. }
  97. int socket_option = 1;
  98. // Free up the port to begin listening again
  99. setsockopt(m_client_socket_fd, SOL_SOCKET, SO_REUSEADDR, &socket_option,
  100. sizeof(socket_option));
  101. server_socket.sin_port = htons(port_value);
  102. inet_pton(AF_INET, argv[1], &server_socket.sin_addr.s_addr);
  103. if (::connect(m_client_socket_fd, reinterpret_cast<sockaddr*>(&server_socket),
  104. sizeof(server_socket)) != -1) {
  105. std::string start_operation_string = createOperation("start", {});
  106. // Send operation as an encoded message
  107. sendEncoded(start_operation_string);
  108. // Delegate message handling to its own thread
  109. std::function<void()> message_send_fn = [this]() {
  110. this->handleMessages();
  111. };
  112. MessageHandler message_handler = createMessageHandler(message_send_fn);
  113. // Handle received messages on separate thread
  114. std::thread (message_handler).detach();
  115. } else {
  116. qDebug() << errno;
  117. ::close(m_client_socket_fd);
  118. }
  119. } else {
  120. qDebug() << "Failed to create new connection";
  121. }
  122. } else {
  123. qDebug() << "Connection already in progress";
  124. }
  125. }
  126. /**
  127. * @brief Client::sendMessage
  128. * @param s[in] <const QString&> The message to send
  129. */
  130. void Client::sendMessage(const QString& s) {
  131. if (m_client_socket_fd != -1) {
  132. std::string json_string {"{\"type\":\"custom\", \"message\": \""};
  133. json_string += s.toUtf8().data();
  134. json_string += "\", \"args\":\"placeholder\"}";
  135. // Send custom message as an encoded message
  136. sendEncoded(json_string);
  137. } else {
  138. qDebug() << "You must first open a connection";
  139. }
  140. }
  141. void Client::sendEncoded(std::string message) {
  142. std::vector<uint8_t> fb_byte_vector{message.begin(), message.end()};
  143. auto byte_vector = builder.CreateVector(fb_byte_vector);
  144. auto k_message = CreateMessage(builder, 69, byte_vector);
  145. builder.Finish(k_message);
  146. uint8_t* encoded_message_buffer = builder.GetBufferPointer();
  147. uint32_t size = builder.GetSize();
  148. qDebug() << "Size is " << size;
  149. uint8_t send_buffer[MAX_BUFFER_SIZE];
  150. memset(send_buffer, 0, MAX_BUFFER_SIZE);
  151. send_buffer[0] = (size & 0xFF) >> 24;
  152. send_buffer[1] = (size & 0xFF) >> 16;
  153. send_buffer[2] = (size & 0xFF) >> 8;
  154. send_buffer[3] = (size & 0xFF);
  155. std::memcpy(send_buffer + 4, encoded_message_buffer, size);
  156. qDebug() << "Ready to send:";
  157. std::string message_to_send{};
  158. for (unsigned int i = 0; i < (size + 4); i++) {
  159. message_to_send += (char)*(send_buffer + i);
  160. }
  161. qDebug() << message_to_send.c_str();
  162. // Send start operation
  163. ::send(m_client_socket_fd, send_buffer, size + 4, 0);
  164. builder.Clear();
  165. }
  166. void Client::sendPackets(uint8_t* data, int size) {
  167. uint32_t total_size = static_cast<uint32_t>(size + HEADER_SIZE);
  168. uint32_t total_packets = static_cast<uint32_t>(ceil(
  169. static_cast<double>(
  170. total_size / MAX_PACKET_SIZE) // total size / packet
  171. )
  172. );
  173. uint32_t idx = 0;
  174. for (; idx < total_packets; idx++) {
  175. bool is_first_packet = (idx == 0);
  176. bool is_last_packet = (idx == (total_packets - 1));
  177. if (is_first_packet) {
  178. uint32_t first_packet_size =
  179. std::min(size + HEADER_SIZE, MAX_PACKET_SIZE);
  180. uint8_t packet[first_packet_size];
  181. packet[0] = (total_size >> 24) & 0xFF;
  182. packet[1] = (total_size >> 16) & 0xFF;
  183. packet[2] = (total_size >> 8) & 0xFF;
  184. packet[3] = (total_size) & 0xFF;
  185. std::memcpy(packet + HEADER_SIZE, data, first_packet_size - HEADER_SIZE);
  186. /**
  187. * SEND PACKET !!!
  188. */
  189. ::send(m_client_socket_fd, packet, first_packet_size, 0);
  190. if (is_last_packet) {
  191. break;
  192. }
  193. continue;
  194. }
  195. int offset = (idx * MAX_PACKET_SIZE) - HEADER_SIZE;
  196. uint32_t packet_size = std::min(size - offset, MAX_PACKET_SIZE);
  197. uint8_t packet[packet_size];
  198. std::memcpy(packet, data + offset, packet_size);
  199. /**
  200. * SEND PACKET !!!
  201. */
  202. ::send(m_client_socket_fd, packet, packet_size, 0);
  203. if (is_last_packet) {
  204. // cleanup
  205. outgoing_file.clear();
  206. }
  207. }
  208. }
  209. void Client::sendFileEncoded(QByteArray bytes) {
  210. sendPackets(reinterpret_cast<uint8_t*>(bytes.data()), bytes.size());
  211. }
  212. void Client::closeConnection() {
  213. if (m_client_socket_fd != -1) {
  214. std::string stop_operation_string = createOperation("stop", {});
  215. // Send operation as an encoded message
  216. sendEncoded(stop_operation_string);
  217. // Clean up socket file descriptor
  218. ::shutdown(m_client_socket_fd, SHUT_RDWR);
  219. ::close(m_client_socket_fd);
  220. m_client_socket_fd = -1;
  221. return;
  222. }
  223. qDebug() << "There is no active connection to close";
  224. }
  225. void Client::setSelectedApp(std::vector<QString> app_names) {
  226. selected_commands.clear();
  227. for (const auto& name : app_names) {
  228. qDebug() << "Matching mask to " << name;
  229. for (const auto& command : m_commands) {
  230. if (command.second.c_str() == name.toUtf8()) {
  231. selected_commands.push_back(command.first);
  232. }
  233. }
  234. }
  235. }
  236. void Client::execute() {
  237. if (!selected_commands.empty()) {
  238. executing = true;
  239. for (const auto& command : selected_commands) {
  240. std::string execute_operation = createOperation("Execute", {std::to_string(command)});
  241. sendEncoded(execute_operation);
  242. }
  243. }
  244. }
  245. void Client::sendFile(QByteArray bytes) {
  246. if (outgoing_file.isNull()) {
  247. std::string send_file_operation = createOperation("FileUpload", {});
  248. int size = bytes.size();
  249. qDebug() << size << " bytes to send";
  250. sendEncoded(send_file_operation);
  251. outgoing_file = bytes;
  252. } else {
  253. qDebug() << "Outgoing file buffer is not ready";
  254. }
  255. }