public Pacote_Auth AutenticarUsuario(Pacote_Auth Pacote_Auths) { if (Pacote_Auths.DominioCliente == Pacote_Auths.DominioServidor) { if (Pacote_Auths.TEndPointClient != Pacote_Auths.TEndPointServer) { Local = Pacote_Auths; if (!Local.Autenticado) { } else { } Pacote_Auths.Autenticado = true; } else { Pacote_Auths.Autenticado = false; Pacote_Auths.Error = true; Pacote_Auths.EMensagem = "Atualmente o servidor não é um controlador. Favor direcionar para o controlador da sua rede."; } } else { Pacote_Auths.Autenticado = false; Pacote_Auths.Error = true; Pacote_Auths.EMensagem = "Atualmente este servidor não responde por esse domínio. Favor direcionar para o controlador da sua rede."; } return(Pacote_Auths); }
public async Task <bool> HTML_AutenticarUsuario(Pacote_Auth Pacote_AuthWEB) { try { HttpClient URL = new HttpClient(); List <KeyValuePair <string, string> > pairs = Pacote_AuthWEB.ListarAtributos(); var content = new FormUrlEncodedContent(pairs); URL.Timeout = TimeSpan.FromSeconds(3); Task <HttpResponseMessage> Conteudo = URL.PostAsync(_Servidor, content); await Task.WhenAll(Conteudo); if (Conteudo.Result.IsSuccessStatusCode) { string Dados = await Conteudo.Result.Content.ReadAsStringAsync(); Pacote_Base PB = JsonConvert.DeserializeObject <Pacote_Base>(Dados); if (PB.Pacote != TipoPacote.Error) { Pacote_Autenticacao = JsonConvert.DeserializeObject <Pacote_Auth>(PB.Conteudo);; Pacote_Autenticacao.Autenticado = true; Pacote_Autenticacao.Error = false; return(true); } else { Error = JsonConvert.DeserializeObject <Pacote_Error>(PB.Conteudo); return(false); } } else { Pacote_AuthWEB.Autenticado = false; Pacote_AuthWEB.Error = true; Error = new Pacote_Error(); Error.Error = true; Error.Mensagem = "A conexão com o URi não foi estabelecida com sucesso!"; return(false); } } catch (Exception e) { TratadorErros(e, GetType().Name); //Classe Tratador de erros tem métodos para tratar erro a esse nível return(false); } }
/** * Data: 02/04/2019 * Transforma uma string em pacote para acesso. * Return: string */ private dynamic DeserializarPacote(string Pacote) { try { Base = JsonConvert.DeserializeObject <Pacote_Base>(Pacote); switch (Base.Pacote) { case TipoPacote.Auth: Pacote_Auth Auth = JsonConvert.DeserializeObject <Pacote_Auth>(Base.Conteudo); return(Auth); case TipoPacote.Comando: Pacote_Comando Exec = JsonConvert.DeserializeObject <Pacote_Comando>(Base.Conteudo); return(Exec); case TipoPacote.File: Pacote_File File = JsonConvert.DeserializeObject <Pacote_File>(Base.Conteudo); return(File); case TipoPacote.FileSystem: Pacote_SystemFile FileSystem = JsonConvert.DeserializeObject <Pacote_SystemFile>(Base.Conteudo); return(FileSystem); case TipoPacote.Echo: Pacote_PingEcho Ping = JsonConvert.DeserializeObject <Pacote_PingEcho>(Base.Conteudo); return(Ping); case TipoPacote.Replay: Pacote_PingReplay Replay = JsonConvert.DeserializeObject <Pacote_PingReplay>(Base.Conteudo); return(Replay); case TipoPacote.Inicializacao: Pacote_Inicializacao Inicializacao = JsonConvert.DeserializeObject <Pacote_Inicializacao>(Base.Conteudo); return(Inicializacao); default: throw new Exception("Tentativa de envio de pacote não reconhecida pelo sistema."); } } catch (Exception e) { TratadorErros(e, this.GetType().Name);; return(false); } }
/** * <summary> * Converte uma string em uma classe de pacote. * </summary> */ private dynamic DeserializarPacote(string Pacote) { Pacote_Base Base = JsonConvert.DeserializeObject <Pacote_Base>(Pacote); switch (Base.Pacote) { case TipoPacote.Auth: Pacote_Auth Auth = JsonConvert.DeserializeObject <Pacote_Auth>(Base.Conteudo); return(Auth); case TipoPacote.Comando: Pacote_Comando Exec = JsonConvert.DeserializeObject <Pacote_Comando>(Base.Conteudo); return(Exec); case TipoPacote.File: Pacote_File File = JsonConvert.DeserializeObject <Pacote_File>(Base.Conteudo); return(File); case TipoPacote.FileSystem: Pacote_SystemFile FileSystem = JsonConvert.DeserializeObject <Pacote_SystemFile>(Base.Conteudo); return(FileSystem); case TipoPacote.Echo: Pacote_PingEcho Ping = JsonConvert.DeserializeObject <Pacote_PingEcho>(Base.Conteudo); return(Ping); case TipoPacote.Replay: Pacote_PingReplay Replay = JsonConvert.DeserializeObject <Pacote_PingReplay>(Base.Conteudo); return(Replay); case TipoPacote.Inicializacao: Pacote_Inicializacao Inicializacao = JsonConvert.DeserializeObject <Pacote_Inicializacao>(Base.Conteudo); return(Inicializacao); } return(null); }
/** * Data: 27/02/2019 * Adiciona em uma lista os clientes que se concectaram ao servidor. * Return: ParametrosInicializacao */ public bool ConectarCliente(EndPoint Client, Pacote_Auth Autenticacao) { try { foreach (var i in ListaClientes_Conectados) { IPEndPoint IPOrigem = (IPEndPoint)Client; IPEndPoint IPDestino = (IPEndPoint)i.Value; if (IPOrigem.Address.Equals(IPDestino.Address)) { return false; } } ListaClientes_Conectados.Add(new KeyValuePair<Pacote_Auth, EndPoint>(Autenticacao, Client)); return true; } catch (Exception e) { TratadorErros(e, this.GetType().Name); return false; } }
public Pacote_Auth AutenticarUsuario(Pacote_Auth Pacote_Auth) { Livre.Token = Convert.ToString(GetHashCode()); return(Livre); }
/** * <summary> * Realiza o pedido de conexão a um servidor remoto. Após a conexão será enviado ao servidor um pedido de confirmação de recebimento de uma string, o * servidor deverá responder com uma string contendo os caracteres 200OK. Após essa confirmação o cliente envia um pacote contendo todas as informações * para realizar as trocas de informações. * <para>Assíncrono</para> * </summary> */ public async Task <bool> Connectar_ServidorAsync() { string DadosLidos; try { /** * Seta os parâmetros de inicialização */ //GetParamentrosIniciais(); ClientToServer = new TcpClient(); ClientToServer.Connect(IPServer); if (ClientToServer.Connected) { BarramentoComunicacao = ClientToServer.GetStream(); BarramentoEscrita = new StreamWriter(BarramentoComunicacao); BarramentoLeitura = new StreamReader(BarramentoComunicacao); Pacote_PingEcho Echo = new Pacote_PingEcho(); Echo.ObterTempo(); BarramentoEscrita.WriteLine(SerializarPacote(Echo)); BarramentoEscrita.Flush(); DadosLidos = await BarramentoLeitura.ReadLineAsync(); Pacote_PingReplay Replay = DeserializarPacote(DadosLidos); if (Replay.GetTipoPacote() != TipoPacote.Replay) { throw new Exception("Falha de comunicação inicial: Server"); } Pacote_Inicializacao Boot = new Pacote_Inicializacao(); Boot.EnderecoIP = IPServer.Address.ToString(); Boot.PORT = IPServer.Port; BarramentoEscrita.WriteLine(SerializarPacote(Boot)); BarramentoEscrita.Flush(); DadosLidos = await BarramentoLeitura.ReadLineAsync(); /*Verifica se os parametros foram recebidos pelo servidor com sucesso.*/ TratarParametrosInicializacao(DadosLidos); Authic.TEndPointClient = TEndPoint; Authic.DominioCliente = EDominio; BarramentoEscrita.WriteLine(SerializarPacote(Authic)); BarramentoEscrita.Flush(); DadosLidos = await BarramentoLeitura.ReadLineAsync(); Authic = DeserializarPacote(DadosLidos); if (Authic.Error) { return(false); } else { return(true); } } else { return(false); } } catch (Exception e) { TratadorErros(e, this.GetType().Name); FecharConexao(); return(false); } }
/** * Data: 27/02/2019 * Método que cria os barramentos de leitura e escrita, dá início ao diálogo inicial com os clientes e * e dá início à conversa contínua com os cliente. * Return: void */ private void Receber_Dados_Responder(object Dados) { StreamReader BarramentoLeitura; StreamWriter BarramentoEscrita; Pacote_Error P_Error; try { TcpClient Clients = (TcpClient)Dados; Func <string, bool> Falha = (G) => { if (G == null) { EndPoint Fl = Clients.Client.RemoteEndPoint; throw new Exception("Ocorreu uma falha no Servidor: " + Fl.ToString()); } else { return(true); } }; using (NetworkStream Brrm = Clients.GetStream()) { //Barramento de Leitura, após a abertura do socket BarramentoLeitura = new StreamReader(Brrm); //Obtém o Barramento de escrita com a cliente BarramentoEscrita = new StreamWriter(Brrm); string DadosLidos = BarramentoLeitura.ReadLine(); Falha(DadosLidos);//Verifica se o barramento é nulo, caracterizando uma falha na comunicação. Pacote_PingEcho Echo = DeserializarPacote(DadosLidos); /*Verifica se, cliente e servidor estão em sintonia, ocorreu algum erro*/ if (Echo.GetTipoPacote() != TipoPacote.Echo) { Pacote_PingReplay Replay = new Pacote_PingReplay(); Replay.Validado = false; Replay.ObterTempo(); /*Confirma o recebimento, do cliente, inicialização.*/ BarramentoEscrita.WriteLine(SerializarPacote(Replay)); BarramentoEscrita.Flush(); throw new Exception("Falha de comunicação inicial: Cliente"); } else { Pacote_PingReplay Replay = new Pacote_PingReplay(); Replay.Validado = true; Replay.ObterTempo(); /*Confirma o recebimento, do cliente, inicialização.*/ BarramentoEscrita.WriteLine(SerializarPacote(Replay)); BarramentoEscrita.Flush(); } DadosLidos = BarramentoLeitura.ReadLine(); Falha(DadosLidos);//Verifica se o barramento é nulo, caracterizando uma falha na comunicação. string EnviarDadosCliente = TratarInicializacao(DadosLidos); /*Informa ao cliente que os parâmetros de inicialização foram recebidos com sucesso.*/ BarramentoEscrita.WriteLine(EnviarDadosCliente); BarramentoEscrita.Flush(); /*Processo de leitura do pacote de autenticação.*/ DadosLidos = BarramentoLeitura.ReadLine(); Falha(DadosLidos); //Verifica se o barramento é nulo, caracterizando uma falha na comunicação. Pacote_Auth PTC = DeserializarPacote(DadosLidos); //Transforma string em um objeto da classe Pacote_Auth PTC.TEndPointServer = TEndPoint; PTC.DominioServidor = EDominio; Pacote_Auth _Autenticado = _Auth?.AutenticarUsuario(PTC); if (_Autenticado != null) { _GerenciadorCliente?.ConectarCliente(Clients.Client.RemoteEndPoint, _Autenticado); EnviarDadosCliente = SerializarPacote(_Autenticado); BarramentoEscrita.WriteLine(EnviarDadosCliente); BarramentoEscrita.Flush(); //Leitura do barramento de dados do próximo tipo de pacote DadosLidos = BarramentoLeitura.ReadLine(); Falha(DadosLidos);//Verifica se o barramento é nulo, caracterizando uma falha na comunicação. dynamic QTP = DeserializarPacote(DadosLidos); switch (Base.Pacote) { case TipoPacote.Comando: Pacote_Comando CMM = (Pacote_Comando)QTP; //Transforma string em um objeto da classe Pacote_Auth string Executar = _ResponderRequisicao(CMM); if (Excecao) { P_Error = new Pacote_Error(); P_Error.Error = Excecao; P_Error.Mensagem = DadosExcecao.Message; P_Error.Tracer = DadosExcecao.StackTrace; Executar = SerializarPacote(P_Error); Excecao = false; DadosExcecao = null; } Pacote_Comando PCT = new Pacote_Comando(); PCT.Resposta = Executar; string DadosPacote = SerializarPacote(PCT); //Obtém o Barramento de escrita com a cliente BarramentoEscrita.WriteLine(DadosPacote); BarramentoEscrita.Flush(); break; case TipoPacote.Echo: Pacote_PingReplay RPY = new Pacote_PingReplay(); DadosPacote = SerializarPacote(RPY); //Obtém o Barramento de escrita com a cliente BarramentoEscrita.WriteLine(DadosPacote); BarramentoEscrita.Flush(); break; case TipoPacote.File: Pacote_File FILE = (Pacote_File)QTP; string PathFile = FILE.Path; int ReceiveBufferClienteSize = FILE.ReceiveBufferCLiente; //Armazena o tamanho do buffer de recepção do cliente; int SendBufferClienteSize = FILE.SendBufferCliente; //Armazena o tamanho do buffer de envio do cliente; int ReceiveBufferServerSize = Clients.ReceiveBufferSize; //Armazena o tamanho do buffer de recepção do cliente; int SendBufferServerSize = Clients.SendBufferSize; //Armazena o tamanho do buffer de envio do cliente; //Enviando dados dos buffers do servidor FILE.ReceiveBufferServidor = ReceiveBufferServerSize; //Envia para o server a capacidade de recepção FILE.SendBufferServidor = SendBufferServerSize; //envia para o server capacidade o tamanho de envio; int BufferTransmissao = ReceiveBufferClienteSize > SendBufferServerSize ? SendBufferServerSize : ReceiveBufferClienteSize; FILE.Existe = File.Exists(PathFile); if (FILE.Existe) { using (FileStream EnviarArquivo = new FileStream(FILE.Path, FileMode.Open)) { long TamanhoArquivoEnviar = EnviarArquivo.Length; FILE.Lenght = TamanhoArquivoEnviar; DadosPacote = SerializarPacote(FILE); BarramentoEscrita.WriteLine(DadosPacote); BarramentoEscrita.Flush(); byte[] T = new byte[BufferTransmissao]; using (BinaryWriter EVFILE = new BinaryWriter(Brrm)) { int LoopEnvio = 0; do { int TotalEnviado = EnviarArquivo.Read(T, 0, BufferTransmissao); EVFILE.Write(T); LoopEnvio += TotalEnviado; } while (LoopEnvio <= TamanhoArquivoEnviar); EnviarArquivo.Close(); } } } else { } break; default: P_Error = new Pacote_Error(); P_Error.Error = true; P_Error.Mensagem = "Esse tipo de pacote não existe."; P_Error.Tracer = ""; BarramentoEscrita.WriteLine(SerializarPacote(P_Error)); BarramentoEscrita.Flush(); break; } } else { //Não existe mecanismo de autenticação. _Autenticado = new Pacote_Auth { Autenticado = false, Error = true, EMensagem = "O servidor não está configurado com nenhum processo de autenticação." }; EnviarDadosCliente = SerializarPacote(_Autenticado); BarramentoEscrita.WriteLine(EnviarDadosCliente); BarramentoEscrita.Flush(); } BarramentoLeitura.Close(); BarramentoEscrita.Close(); //Desconectar_Cliente("10.56.34.222","80"); Clients.Close(); } } catch (Exception e) { TratadorErros(e, this.GetType().Name);; } }