diff --git a/headers/client.h b/headers/client.h index eab04d10769e64c6313c21c3d182e1b7f7afcaf9..33bfd99517145bd3e2756aa4354a1b96a18b80e0 100644 --- a/headers/client.h +++ b/headers/client.h @@ -8,7 +8,6 @@ #include <iostream> #include <linux/if.h> #include <linux/if_packet.h> -#include <mutex> #include <net/ethernet.h> #include <netinet/in.h> #include <stdio.h> @@ -21,15 +20,9 @@ // include local #include "conexao.h" +#include "cores.h" #include "frame.h" -vector<string> CMD_HELP = {"H", "help", "-h", "HELP", "Help", - "-H", "ajuda", "Ajuda", "AJUDA"}; -vector<string> CMD_EXIT = {"exit", "-e", "EXIT", "Exit", - "-E", "sair", "Sair", "SAIR"}; -vector<string> CMD_SEND = {"send", "-s", "SEND", "Send", - "-S", "enviar", "Enviar", "ENVIAR"}; - using namespace std; class client { @@ -52,7 +45,7 @@ private: frame *receive_ack_nack(); vector<frame *> create_frames(vector<char> data, int type); vector<frame *> create_frames_midia(vector<char> data); - frame* send_frame_socket(frame *f); + frame *send_frame_socket(frame *f); int start_transmission(); int end_transmission(); string calc_file_size(string fileName); @@ -80,28 +73,26 @@ frame *client::receive_ack_nack() { do { response = socket->receive_frame(); if (response && response->get_tipo() == ERRO) { - cout << "Espaco insulficiente no destino\n"; + cout << BOLDYELLOW << "Espaco insulficiente no destino\n" << RESET; return NULL; } - } while (response && - !(verify_ack_nack(response))); + } while (response && !(verify_ack_nack(response))); return response; } // Solicita ao socket que envie um frame -frame* client::send_frame_socket(frame *f) { +frame *client::send_frame_socket(frame *f) { // Fica tentando enviar o frame até receber o ack frame *response = new frame(); int retries = 0; do { // envia um frame da fila int bytesSent = socket->send_frame(f); - if ( bytesSent == -1 ) { return NULL; } - + if (bytesSent == -1) { return NULL; } + response = receive_ack_nack(); - if(!response) - return NULL; + if (!response) return NULL; retries++; } while (response->get_dado()[0] != f->get_seq() && retries < NUM_RETRIES); @@ -117,30 +108,30 @@ frame* client::send_frame_socket(frame *f) { // Inicia a transmissao com o servidor int client::start_transmission() { - cout << "\tIniciando transmissao\n"; + // cout<< YELLOW << "\tIniciando transmissao\n" << RESET; ->log frame *ini = new frame(INIT, 0, vector<char>(1, 0)); - frame* enviado = new frame(); + frame *enviado = new frame(); enviado = send_frame_socket(ini); if (!enviado) { - cout << "\tFalha ao iniciar a transmissao\n"; + // cout<< BOLDRED << "\tFalha ao iniciar a transmissao\n" << RESET; ->log return 0; } - cout << "\tTransmissao iniciada com sucesso\n"; + // cout<< GREEN << "\tTransmissao iniciada com sucesso\n" << RESET; ->log return 1; } // Encerra a transmissao com o servidor int client::end_transmission() { - cout << "\tEncerrando a transmissao\n"; + // cout << "\tEncerrando a transmissao\n"; ->log frame *end = new frame(FIMT, 0, vector<char>(1, 0)); - frame* enviado = send_frame_socket(end); + frame *enviado = send_frame_socket(end); if (!enviado) { - cout << "\tFalha ao encerrar a transmissao\n"; + // cout << "\tFalha ao encerrar a transmissao\n"; ->log return 0; } - cout << "\tTransmissao encerrada com sucesso\n"; + // cout << "\tTransmissao encerrada com sucesso\n"; ->log return 1; } @@ -164,16 +155,15 @@ int client::send_frames(vector<frame *> frames) { int iniJanela = 0; while (iniJanela < frames.size()) { - //manda todos os frames de uma vez só - for(frameCounter = 0; frameCounter < TAM_JANELA; frameCounter++){ - if(iniJanela+frameCounter == frames.size()) { break; } + // manda todos os frames de uma vez só + for (frameCounter = 0; frameCounter < TAM_JANELA; frameCounter++) { + if (iniJanela + frameCounter == frames.size()) { break; } janela.push(frameCounter); - + cout << "\tEnviando frame\n"; frames[iniJanela]->imprime(HEX); - - if (socket->send_frame(frames[iniJanela+frameCounter]) == -1) - { + + if (socket->send_frame(frames[iniJanela + frameCounter]) == -1) { cout << "Falha ao enviar o frame\n"; return 0; } @@ -183,7 +173,7 @@ int client::send_frames(vector<frame *> frames) { // Recebe a resposta do servidor for (int i = 0; i < min((int)TAM_JANELA, (int)frames.size()); i++) { - frame* res = NULL; + frame *res = NULL; int retries = 0; do { @@ -191,34 +181,33 @@ int client::send_frames(vector<frame *> frames) { retries++; } while (res == NULL && retries < NUM_RETRIES); - if(res == NULL && retries == NUM_RETRIES){ - return 0; - } - - if(res->get_tipo() == NACK && res->get_dado()[0] == janela.front()){ - cout << "NACK " << (int)res->get_dado()[0] << " recebido\n" ; + if (res == NULL && retries == NUM_RETRIES) { return 0; } + + if (res->get_tipo() == NACK && res->get_dado()[0] == janela.front()) { + cout << "NACK " << (int)res->get_dado()[0] << " recebido\n"; iniJanela += res->get_dado()[0]; janela.pop(); break; } - if(res->get_tipo() == ACK && res->get_dado()[0] == janela.front()){ - cout << "ACK " << (int)res->get_dado()[0] << " recebido\n" ; + if (res->get_tipo() == ACK && res->get_dado()[0] == janela.front()) { + cout << "ACK " << (int)res->get_dado()[0] << " recebido\n"; iniJanela++; janela.pop(); } - else{ + else { i--; } } - //apaga a janela - while(! janela.empty()) janela.pop(); + // apaga a janela + while (!janela.empty()) + janela.pop(); } if (!end_transmission()) { return 0; } - cout << "\tTerminou de enviar todos os frames\n"; + // cout << "\tTerminou de enviar todos os frames\n"; ->log return 1; } @@ -232,7 +221,8 @@ int client::send_frames(vector<frame *> frames) { * @return false */ bool client::verify_ack_nack(frame *received) { - return ((received->get_tipo() == ACK || received->get_tipo() == NACK) && received->chk_crc8()); + return ((received->get_tipo() == ACK || received->get_tipo() == NACK) && + received->chk_crc8()); } /** @@ -262,7 +252,7 @@ int client::send_message(vector<char> data, int type) { string client::calc_file_size(string fileName) { struct stat buffer; if (stat(fileName.c_str(), &buffer) == -1) { - cout << "Arquivo inexistente. Operacao abortada\n"; + cout << YELLOW << "\t--Arquivo inexistente. Operacao abortada--\n" << RESET; return {}; } @@ -291,20 +281,22 @@ void client::send_file() { string fileName; do { - cout << "Digite o nome do arquivo(maximo de " << TAM_DADOS - << " char):\n"; + cout << BOLDWHITE << "Digite o nome do arquivo(maximo de " << TAM_DADOS + << " char):\n" + << RESET; getline(cin, fileName); } while (fileName.size() > TAM_DADOS); fileNameVector.insert(fileNameVector.begin(), fileName.begin(), fileName.end()); + cout << BOLDYELLOW << "\t--Enviando arquivo--\n" << RESET; if (!send_message(fileNameVector, MIDIA)) { - cout << "Falha ao enviar o arquivo\n"; + cout << BOLDRED << "\t--Falha ao enviar o arquivo--\n" << RESET; return; } - cout << "Arquivo enviado com sucesso\n"; + cout << BOLDGREEN << "\t--Arquivo enviado com sucesso--\n" << RESET; } /** @@ -314,14 +306,14 @@ void client::send_file() { */ void client::send_text(string message) { - cout << "Enviando mensagem\n"; + cout << BOLDYELLOW << "\t--Enviando mensagem--\n" << RESET; vector<char> data(message.begin(), message.end()); if (!send_message(data, TEXTO)) - cout << "Limite de timout, mensagem nao foi enviada\n"; - + cout << BOLDRED << "\t--Limite de timout, mensagem nao foi enviada--\n" + << RESET; else - cout << "Mensagem enviada com sucesso\n"; + cout << GREEN << "\t--Mensagem enviada com sucesso--\n" << RESET; } vector<frame *> client::create_frames_midia(vector<char> vectorName) { @@ -346,7 +338,8 @@ vector<frame *> client::create_frames_midia(vector<char> vectorName) { // Cria um vetor com os dados do arquivo vector<char> vectorData = read_file(fileName); if (vectorData.empty()) { - cout << "Falha ao abrir o arquivo para leitura\n"; + cout << BOLDRED << "\t--Falha ao abrir o arquivo para leitura--\n" + << RESET; //->log return vector<frame *>(); } @@ -356,7 +349,7 @@ vector<frame *> client::create_frames_midia(vector<char> vectorName) { // Arruma a sequencia dos frames for (int i = 0; i < framesToSend.size(); i++) - framesToSend[i]->set_seq(i%TAM_JANELA); + framesToSend[i]->set_seq(i % TAM_JANELA); return framesToSend; } @@ -396,30 +389,29 @@ bool client::string_has(string str, vector<string> strList) { } char client::string_cmd(string str) { - if (string_has(str, CMD_HELP)) return 'h'; - - if (string_has(str, CMD_EXIT)) return 'e'; - - if (string_has(str, CMD_SEND)) return 's'; - + if (strcmp(str.c_str(), "-h") == 0) return 'h'; + if (strcmp(str.c_str(), "-e") == 0) return 'e'; + if (strcmp(str.c_str(), "-s") == 0) return 's'; return 'm'; } void client::print_help() { - cout << "Comandos disponiveis:\n"; - cout << "help ou -h ou h ou HELP ou Help ou H ou ajuda ou Ajuda ou AJUDA\n"; - cout << "exit ou -e ou e ou EXIT ou Exit ou E ou sair ou Sair ou SAIR\n"; - cout << "send ou -s ou s ou SEND ou Send ou S ou enviar ou Enviar ou " - "ENVIAR\n"; - cout << "para enviar uma mensagem, digite a mensagem e pressione enter\n"; + cout << BOLDBLUE << "\t---Comandos disponiveis---\n" << RESET; + cout << YELLOW + << "para enviar uma mensagem, digite a mensagem e pressione enter\n" + << RESET; + cout << GREEN << "-s: " << WHITE << "envia um arquivo\n" << RESET; + cout << RED << "-e: " << WHITE << "sai do programa\n" << RESET; + cout << BLUE << "-h: " << WHITE << "exibe os comandos disponíveis\n" << RESET; } // ------------------------------- PUBLIC --------------------------------- // void client::run() { int i; + print_help(); while (true) { - cout << " Digite um comando ou mensagem:\n"; + cout << BOLDWHITE << "\nDigite um comando ou mensagem:\n" << RESET; getline(cin, userInput); char userInputCMD = string_cmd(userInput); @@ -430,7 +422,7 @@ void client::run() { break; case 'e': - cout << "Saindo...\n"; + cout << BOLDYELLOW << "\tSaindo...\n" << RESET; exit(0); break; @@ -443,7 +435,7 @@ void client::run() { break; default: - cout << "Comando invalido\n"; + cout << BOLDMAGENTA << "\tComando invalido\n" << RESET; break; } } diff --git a/headers/conexao.h b/headers/conexao.h index 887ffe4c21987615b9facdb583f98ab68405e4ba..2fcab792cefc8d421796b5278492c9df5abbe9a5 100644 --- a/headers/conexao.h +++ b/headers/conexao.h @@ -19,14 +19,13 @@ #include <arpa/inet.h> // include local +#include "cores.h" #include "frame.h" - using namespace std; #define NUM_RETRIES 10 #define TAM_JANELA 2 - class conexao { private: // ------ Dados ------ // @@ -96,7 +95,6 @@ frame *conexao::receive_frame() { return f; } } while (timestamp() - start <= timeoutMillis); - return NULL; } @@ -119,8 +117,8 @@ int conexao::send_frame(frame *f) { cout << hex << (int(bufferSend[i]) & 0xff) << " "; } cout << "\n"; - if (byteSend < 0) { - cout << "Erro no sendto" << byteSend << "\n"; + if (byteSend < 0) { + cout << "Erro no sendto" << byteSend << "\n"; return -1; } @@ -167,7 +165,7 @@ int conexao::ConexaoRawSocket(char *device) { soquete = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); /*cria socket*/ if (soquete == -1) { - printf("Erro no Socket, verifique se voce eh root\n"); + cout << BOLDRED << "\tErro no Socket, verifique se voce eh root\n" << RESET; exit(-1); } diff --git a/headers/cores.h b/headers/cores.h new file mode 100644 index 0000000000000000000000000000000000000000..ee8f7af19636f09b1478d4dde099aa39f999140a --- /dev/null +++ b/headers/cores.h @@ -0,0 +1,23 @@ +#ifndef COLORS_H +#define COLORS_H + +/*RESET TERMINAL COLOR*/ +#define RESET "\033[0m" // reset terminal color +#define BLACK "\033[30m" +#define RED "\033[31m" // erros +#define GREEN "\033[32m" // sucesso +#define YELLOW "\033[33m" // informações para o usuário +#define BLUE "\033[34m" +#define MAGENTA "\033[35m" // warnings +#define CYAN "\033[36m" +#define WHITE "\033[37m" // caixa de texto +#define BOLDBLACK "\033[1m\033[30m" +#define BOLDRED "\033[1m\033[31m" // erros* +#define BOLDGREEN "\033[1m\033[32m" // sucesso* +#define BOLDYELLOW "\033[1m\033[33m" // informações para o usuário* +#define BOLDBLUE "\033[1m\033[34m" +#define BOLDMAGENTA "\033[1m\033[35m" // warnings* +#define BOLDCYAN "\033[1m\033[36m" +#define BOLDWHITE "\033[1m\033[37m" // caixa de texto* + +#endif diff --git a/headers/server.h b/headers/server.h index 3eb74e6d346a66c7f821be471947a8c6bb2c08be..09359aa1078628e02076e3b2b5fd0746c4422a14 100644 --- a/headers/server.h +++ b/headers/server.h @@ -21,6 +21,7 @@ #include <sys/types.h> // include local +#include "cores.h" #include "frame.h" #include "macros.h" #include "conexao.h" @@ -50,6 +51,7 @@ private: bool create_received_dir (); UL chk_available_size (); int receive_file_size (frame *f); + string create_file_destination(string fileName); ofstream create_file (string fileName); int receive_midia (frame *f); //void send_confirm(frame *fReceive); @@ -155,7 +157,9 @@ bool server::verify_seq(int seq, int lastSeq) { int server::next_tipo_midia(frame *f) { if ( f->get_tipo() != MIDIA ) { return -1; } if ( f->get_seq() == 0 ) { return MIDIA; } - if ( f->get_seq() == 1 ) { return DADOS; } + if ( f->get_seq() == 1 ) { + cout << YELLOW << "\t--Recebendo dados arquivo--\n" << RESET; + return DADOS; } return -1; } @@ -183,7 +187,7 @@ int server::next_tipo_midia(frame *f) { UL server::chk_available_size() { struct statvfs st; if (statvfs(FILE_DESTINATION, &st) == -1) { - cout << "Erro no statvfs, abortado\n"; + // cout << "Erro no statvfs, abortado\n";->log // send_error(); return -1; } @@ -202,12 +206,13 @@ int server::receive_file_size(frame *f) { int fileSize = stoi(f->get_dado()); if (fileSize > availSize * 0.9) { - cout << "Tamanho do arquivo muito grande, abortado\n"; - // send_error(); - return 0; + cout << BOLDMAGENTA << "\t--Tamanho do arquivo muito grande, abortado--\n" + << RESET; + // send_error(); + return 0; } - cout << "Espaco suficiente em disco\n"; + // cout << "Espaco suficiente em disco\n"; ->log return 1; } @@ -217,17 +222,17 @@ bool server::create_received_dir() { // Check if the directory exists struct stat info; if (stat(FILE_DESTINATION, &info) == 0 && (info.st_mode & S_IFDIR)) { - cout << "Diretorio ja existe\n"; + // cout << "Diretorio ja existe\n"; ->log return true; } // create the directory - if (mkdir(FILE_DESTINATION, 0700) == -1) { - cout << "Erro ao criar o diretorio\n"; + if (mkdir(FILE_DESTINATION, 0777) == -1) { + cout << RED << "Erro ao criar o diretorio\n" << RESET; return false; } - cout << "Diretorio criado com sucesso\n"; + // cout << "Diretorio criado com sucesso\n"; ->log return true; } @@ -280,12 +285,30 @@ bool server::create_received_dir() { //} // -ofstream server::create_file(string fileName) { +string server::create_file_destination(string fileName) +{ string fileDestination; fileDestination.append(FILE_DESTINATION); fileDestination.push_back('/'); fileDestination.append(fileName); + return fileDestination; +} + +ofstream server::create_file(string fileName) { + string fileDestination = create_file_destination(fileName); + + cout << BOLDWHITE << "Criando arquivo " << BOLDYELLOW << fileDestination + << BOLDWHITE << ". Digite novo nome ou enter para continuar: " << RESET; + + string newDestination = ""; + getline(cin, newDestination); + if (!newDestination.empty() && newDestination != "\n") { + fileDestination = newDestination; + } + cout << YELLOW << "\t--Criando arquivo: " << fileDestination << "--\n" + << RESET; + // Abre o arquivo para escrita ofstream file; file.open(fileDestination, ios::binary); @@ -317,11 +340,13 @@ int server::receive_midia(frame *f) { if (!file.is_open()) { - cout << "Falha ao criar o arquivo. Abortado\n"; - return 0; + cout << RED << "\tFalha ao criar o arquivo. Abortado\n" << RESET; + file.close(); + remove(create_file_destination(fileName).c_str()); + return 0; } - cout << "Arquivo criado com sucesso\n"; + // cout << BOLDGREEN << "\t--Arquivo recebido com sucesso--\n" << RESET; if ( !file.is_open() ) { return 0; } return 1; } @@ -337,7 +362,7 @@ frame *server::receive_frame_socket() { } while (fReceive == NULL && retries < NUM_RETRIES); if (fReceive == NULL && retries == NUM_RETRIES) { - cout << "Desisti de receber o frame\n"; + // cout << "Desisti de receber o frame\n"; ->log return NULL; } @@ -535,11 +560,13 @@ void server::start_receveing_message() { } while (continueTransmission); - if ( tipo_data == TEXTO ) - cout << ">>>>>>>>>>>>>> Mensagem recebida: " << string(data.begin(), data.end()) << "\n"; + if ( tipo_data == TEXTO ) + cout << BOLDYELLOW << "\t--Mensagem recebida--\n " << BOLDWHITE + << string(data.begin(), data.end()) << "\n" + << RESET; if ( tipo_data == DADOS ) - cout << ">>>>>>>>>>>>>> Arquivo recebido\n"; + cout << BOLDGREEN << "\t--Arquivo recebido com sucesso--\n" << RESET; } // ------------------------------- PUBLIC --------------------------------- // @@ -552,14 +579,17 @@ void server::run() { frame *fReceive; if (!(fReceive = socket->receive_frame())) { continue; } - cout << "Frame recebido:" << endl; - fReceive->imprime(HEX); + // cout << "Frame recebido:" << endl; ->log + // fReceive->imprime(HEX); // Verifica se o frame eh de inicio de transmissao e se nao veio com erro int frameType = fReceive->get_tipo(); - if (frameType != INIT) { cout << "Frame ignorado, n eh INIT\n"; continue; } + if (frameType != INIT) { + // cout << "Frame ignorado, n eh INIT\n"; ->log + continue; + } - cout << "Frame de INIT\n"; + // cout << "Frame de INIT\n"; ->log if (!fReceive->chk_crc8()) { send_nack(fReceive); continue; diff --git a/received/saida.txt b/received/saida.txt deleted file mode 100644 index 1a56033fe38d2af10a0efb1223f107d4b1601fa8..0000000000000000000000000000000000000000 Binary files a/received/saida.txt and /dev/null differ diff --git a/received/texto.txt b/received/texto.txt new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testecor.cpp b/testecor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..79228838598e28fc3e24042b013d6a023efd31dd --- /dev/null +++ b/testecor.cpp @@ -0,0 +1,24 @@ +#include "./headers/cores.h" +#include <iostream> + +int main() { + std::cout << BLACK << "Black\n"; + std::cout << RED << "Red\n"; + std::cout << GREEN << "Green\n"; + std::cout << YELLOW << "Yellow\n"; + std::cout << BLUE << "Blue\n"; + std::cout << MAGENTA << "Magenta\n"; + std::cout << CYAN << "Cyan\n"; + std::cout << WHITE << "White\n"; + std::cout << BOLDBLACK << "Bold Black\n"; + std::cout << BOLDRED << "Bold Red\n"; + std::cout << BOLDGREEN << "Bold Green\n"; + std::cout << BOLDYELLOW << "Bold Yellow\n"; + std::cout << BOLDBLUE << "Bold Blue\n"; + std::cout << BOLDMAGENTA << "Bold Magenta\n"; + std::cout << BOLDCYAN << "Bold Cyan\n"; + std::cout << BOLDWHITE << "Bold White\n"; + std::cout << RESET << "Default\n"; + + return 0; +} \ No newline at end of file diff --git a/text.txt b/text.txt new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/todo.txt b/todo.txt index ac91a4b1800dd80548b6fcd9f4c95b542fe82c8f..72ff90813754027306bdbe261c52b201bbe528ef 100644 --- a/todo.txt +++ b/todo.txt @@ -1,5 +1,12 @@ -> Ver se os frames que estao vindo sao arquivos e juntar eles no arquivo +<<<<<<< HEAD +-> Fazer send_error + +-> Arrumar o receive text + +======= +>>>>>>> db29f5efa0a686ffe08f19d3553a889be3c6e4d5 -> Arrumar a interface -> Demonstracao correcao de erros