client.cpp 10 KB

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