From c52c6d6f1d935a9293aa44ff1147e51d4770f99e Mon Sep 17 00:00:00 2001 From: anderson.peterle@previdencia.gov.br Date: Sun, 5 Apr 2009 19:47:51 +0000 Subject: [PATCH] Reuso de codigos da library generica, pequenas correcoes e faxina de codigo. --- CACIC_Library.pas | 131 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------------------------------ cacic2.dpr | 1 - col_moni/col_moni.dpr | 77 ++++++++++++++++++++++++++++++++++++++++++----------------------------------- col_patr/col_patr.dpr | 8 ++++---- col_patr/main_col_patr.pas | 157 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------------------------------------------------------- col_soft/col_soft.dpr | 69 +++++++++++++++++++++++++++++++++++++++------------------------------ col_undi/col_undi.dpr | 75 +++++++++++++++++++++++++++++++++++++++++---------------------------------- ger_cols/ger_cols.dpr | 297 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------------------------------------------------------------------------------------------------------ ini_cols/ini_cols.dpr | 215 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------------------------------------------------------------------------------------- main.pas | 197 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------------------------------------------------------------------------------------------------- mapa/main_mapa.pas | 2 ++ 11 files changed, 666 insertions(+), 563 deletions(-) diff --git a/CACIC_Library.pas b/CACIC_Library.pas index 7dd33bc..fa73266 100644 --- a/CACIC_Library.pas +++ b/CACIC_Library.pas @@ -132,17 +132,20 @@ type protected /// Mantem o caminho físico de instalação do agente cacic g_cacic_path: string; + g_boolCipher : boolean; public Windows : TCACIC_Windows; /// objeto de informacoes de windows Debug : TCACIC_Debug; /// objeto de tratamento de debug procedure setCacicPath(p_cacic_path: string); + procedure setBoolCipher(p_boolCipher : boolean); function deCrypt(p_Data : String) : String; function enCrypt(p_Data : String) : String; function explode(p_String, p_Separador : String) : TStrings; function implode(p_Array : TStrings ; p_Separador : String) : String; function getCacicPath() : String; function getCipherKey() : String; + function getBoolCipher() : boolean; function getIV() : String; function getKeySize() : integer; function getBlockSize() : integer; @@ -307,6 +310,26 @@ begin end; {*------------------------------------------------------------------------------ + Atribui valor booleano à variável indicadora do status da criptografia + + @param p_boolCipher Valor booleano para atribuição à variável para status da + criptografia. +-------------------------------------------------------------------------------} +procedure TCACIC.setBoolCipher(p_boolCipher : boolean); +Begin + Self.g_boolCipher := p_boolCipher; +End; +{*------------------------------------------------------------------------------ + Obtém o status da criptografia (TRUE -> Ligada / FALSE -> Desligada) + + @return boolean contendo o status para a criptografia +-------------------------------------------------------------------------------} +function TCACIC.getBoolCipher() : boolean; +Begin + Result := Self.g_boolCipher; +End; + +{*------------------------------------------------------------------------------ Atribui o caminho físico de instalação do agente cacic @param p_cacic_path Caminho físico de instalação do agente cacic @@ -756,29 +779,35 @@ var l_Data, l_Key, l_IV : string; begin Try - // Pad Key, IV and Data with zeros as appropriate - l_Key := PadWithZeros(CACIC_CIPHERKEY,CACIC_KEYSIZE); - l_IV := PadWithZeros(CACIC_IV,CACIC_BLOCKSIZE); - l_Data := PadWithZeros(p_Data,CACIC_BLOCKSIZE); - - // Create the cipher and initialise according to the key length - l_Cipher := TDCP_rijndael.Create(nil); - if Length(CACIC_CIPHERKEY) <= 16 then - l_Cipher.Init(l_Key[1],128,@l_IV[1]) - else if Length(CACIC_CIPHERKEY) <= 24 then - l_Cipher.Init(l_Key[1],192,@l_IV[1]) - else - l_Cipher.Init(l_Key[1],256,@l_IV[1]); - - // Encrypt the data - l_Cipher.EncryptCBC(l_Data[1],l_Data[1],Length(l_Data)); - - // Free the cipher and clear sensitive information - l_Cipher.Free; - FillChar(l_Key[1],Length(l_Key),0); - - // Return the Base64 encoded result - Result := Base64EncodeStr(l_Data); + if self.g_boolCipher then + Begin + // Pad Key, IV and Data with zeros as appropriate + l_Key := PadWithZeros(CACIC_CIPHERKEY,CACIC_KEYSIZE); + l_IV := PadWithZeros(CACIC_IV,CACIC_BLOCKSIZE); + l_Data := PadWithZeros(p_Data,CACIC_BLOCKSIZE); + + // Create the cipher and initialise according to the key length + l_Cipher := TDCP_rijndael.Create(nil); + if Length(CACIC_CIPHERKEY) <= 16 then + l_Cipher.Init(l_Key[1],128,@l_IV[1]) + else if Length(CACIC_CIPHERKEY) <= 24 then + l_Cipher.Init(l_Key[1],192,@l_IV[1]) + else + l_Cipher.Init(l_Key[1],256,@l_IV[1]); + + // Encrypt the data + l_Cipher.EncryptCBC(l_Data[1],l_Data[1],Length(l_Data)); + + // Free the cipher and clear sensitive information + l_Cipher.Free; + FillChar(l_Key[1],Length(l_Key),0); + + // Return the Base64 encoded result + Result := Base64EncodeStr(l_Data); + End + Else + // Return the original value + Result := p_Data; Except // LogDiario('Erro no Processo de Criptografia'); End; @@ -790,31 +819,37 @@ var l_Data, l_Key, l_IV : string; begin Try - // Pad Key and IV with zeros as appropriate - l_Key := PadWithZeros(CACIC_CIPHERKEY,CACIC_KEYSIZE); - l_IV := PadWithZeros(CACIC_IV,CACIC_BLOCKSIZE); - - // Decode the Base64 encoded string - l_Data := Base64DecodeStr(p_Data); - - // Create the cipher and initialise according to the key length - l_Cipher := TDCP_rijndael.Create(nil); - if Length(CACIC_CIPHERKEY) <= 16 then - l_Cipher.Init(l_Key[1],128,@l_IV[1]) - else if Length(CACIC_CIPHERKEY) <= 24 then - l_Cipher.Init(l_Key[1],192,@l_IV[1]) - else - l_Cipher.Init(l_Key[1],256,@l_IV[1]); - - // Decrypt the data - l_Cipher.DecryptCBC(l_Data[1],l_Data[1],Length(l_Data)); - - // Free the cipher and clear sensitive information - l_Cipher.Free; - FillChar(l_Key[1],Length(l_Key),0); - - // Return the result - Result := l_Data; + if self.g_boolCipher then + Begin + // Pad Key and IV with zeros as appropriate + l_Key := PadWithZeros(CACIC_CIPHERKEY,CACIC_KEYSIZE); + l_IV := PadWithZeros(CACIC_IV,CACIC_BLOCKSIZE); + + // Decode the Base64 encoded string + l_Data := Base64DecodeStr(p_Data); + + // Create the cipher and initialise according to the key length + l_Cipher := TDCP_rijndael.Create(nil); + if Length(CACIC_CIPHERKEY) <= 16 then + l_Cipher.Init(l_Key[1],128,@l_IV[1]) + else if Length(CACIC_CIPHERKEY) <= 24 then + l_Cipher.Init(l_Key[1],192,@l_IV[1]) + else + l_Cipher.Init(l_Key[1],256,@l_IV[1]); + + // Decrypt the data + l_Cipher.DecryptCBC(l_Data[1],l_Data[1],Length(l_Data)); + + // Free the cipher and clear sensitive information + l_Cipher.Free; + FillChar(l_Key[1],Length(l_Key),0); + + // Return the result (unCrypted) + Result := l_Data + End + Else + // Return the original value + Result := p_Data Except // LogDiario('Erro no Processo de Decriptografia'); End; diff --git a/cacic2.dpr b/cacic2.dpr index 4e6c6fd..e5b6ead 100755 --- a/cacic2.dpr +++ b/cacic2.dpr @@ -20,7 +20,6 @@ program cacic2; uses Forms, Windows, - Dialogs, main in 'main.pas' {FormularioGeral}, frmSenha in 'frmsenha.pas' {formSenha}, frmConfiguracoes in 'frmConfiguracoes.pas' {FormConfiguracoes}, diff --git a/col_moni/col_moni.dpr b/col_moni/col_moni.dpr index 70fff31..8f3538f 100755 --- a/col_moni/col_moni.dpr +++ b/col_moni/col_moni.dpr @@ -6,7 +6,7 @@ Este arquivo é parte do programa CACIC - Configurador Automático e Coletor de In O CACIC é um software livre; você pode redistribui-lo e/ou modifica-lo dentro dos termos da Licença Pública Geral GNU como publicada pela Fundação do Software Livre (FSF); na versão 2 da Licença, ou (na sua opinião) qualquer versão. - + Este programa é distribuido na esperança que possa ser util, mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU para maiores detalhes. @@ -28,7 +28,6 @@ uses CACIC_Library in '..\CACIC_Library.pas'; var - v_path_cacic, v_Res_Search, v_Drive, v_File, @@ -876,44 +875,52 @@ begin end; end; +var strAux : String; begin g_oCacic := TCACIC.Create(); + g_oCacic.setBoolCipher(true); + if( not g_oCacic.isAppRunning( CACIC_APP_NAME ) ) then if (ParamCount>0) then - Begin - //Pegarei o nível anterior do diretório, que deve ser, por exemplo \Cacic, para leitura do cacic2.ini - tstrTripa1 := g_oCacic.explode(ExtractFilePath(ParamStr(0)),'\'); - v_path_cacic := ''; - For intAux := 0 to tstrTripa1.Count -2 do - begin - v_path_cacic := v_path_cacic + tstrTripa1[intAux] + '\'; - end; - - g_oCacic.setCacicPath(v_path_cacic); - v_Debugs := false; - if DirectoryExists(g_oCacic.getCacicPath + 'Temp\Debugs') then - Begin - if (FormatDateTime('ddmmyyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs')) = FormatDateTime('ddmmyyyy', date)) then - Begin - v_Debugs := true; - log_diario('Pasta "' + g_oCacic.getCacicPath + 'Temp\Debugs" com data '+FormatDateTime('dd-mm-yyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs'))+' encontrada. DEBUG ativado.'); - End; - End; - - v_tstrCipherOpened := TStrings.Create; - v_tstrCipherOpened := CipherOpen(g_oCacic.getDatFileName); - - v_tstrCipherOpened1 := TStrings.Create; - v_tstrCipherOpened1 := CipherOpen(g_oCacic.getCacicPath + 'temp\col_moni.dat'); - - Try - Executa_Col_moni; - Except - SetValorDatMemoria('Col_Moni.nada', 'nada', v_tstrCipherOpened1); - CipherClose(g_oCacic.getCacicPath + 'temp\col_moni.dat', v_tstrCipherOpened1); - End; - End; + Begin + strAux := ''; + For intAux := 1 to ParamCount do + Begin + if LowerCase(Copy(ParamStr(intAux),1,11)) = '/cacicpath=' then + begin + strAux := Trim(Copy(ParamStr(intAux),12,Length((ParamStr(intAux))))); + log_DEBUG('Parâmetro /CacicPath recebido com valor="'+strAux+'"'); + end; + end; + + if (strAux <> '') then + Begin + g_oCacic.setCacicPath(strAux); + v_Debugs := false; + if DirectoryExists(g_oCacic.getCacicPath + 'Temp\Debugs') then + Begin + if (FormatDateTime('ddmmyyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs')) = FormatDateTime('ddmmyyyy', date)) then + Begin + v_Debugs := true; + log_diario('Pasta "' + g_oCacic.getCacicPath + 'Temp\Debugs" com data '+FormatDateTime('dd-mm-yyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs'))+' encontrada. DEBUG ativado.'); + End; + End; + + v_tstrCipherOpened := TStrings.Create; + v_tstrCipherOpened := CipherOpen(g_oCacic.getCacicPath + g_oCacic.getDatFileName); + + v_tstrCipherOpened1 := TStrings.Create; + v_tstrCipherOpened1 := CipherOpen(g_oCacic.getCacicPath + 'temp\col_moni.dat'); + + Try + Executa_Col_moni; + Except + SetValorDatMemoria('Col_Moni.nada', 'nada', v_tstrCipherOpened1); + CipherClose(g_oCacic.getCacicPath + 'temp\col_moni.dat', v_tstrCipherOpened1); + End; + End; + End; g_oCacic.Free(); diff --git a/col_patr/col_patr.dpr b/col_patr/col_patr.dpr index dacfdf2..2a4159e 100755 --- a/col_patr/col_patr.dpr +++ b/col_patr/col_patr.dpr @@ -32,12 +32,12 @@ const var hwind:HWND; - g_oCacic : TCACIC; + oCacic : TCACIC; begin - g_oCacic := TCACIC.Create(); + oCacic := TCACIC.Create(); - if( g_oCacic.isAppRunning( CACIC_APP_NAME ) ) + if( oCacic.isAppRunning( CACIC_APP_NAME ) ) then begin hwind := 0; repeat // The string 'My app' must match your App Title (below) @@ -55,6 +55,6 @@ begin Application.Run; end; - g_oCacic.Free(); + oCacic.Free(); end. diff --git a/col_patr/main_col_patr.pas b/col_patr/main_col_patr.pas index eb247dc..3f194f3 100755 --- a/col_patr/main_col_patr.pas +++ b/col_patr/main_col_patr.pas @@ -906,93 +906,96 @@ var boolColeta : boolean; tstrTripa1 : TStrings; i,intAux : integer; v_Aux, - v_path_cacic : String; + strAux : String; Begin g_oCacic := TCACIC.Create(); + g_oCacic.setBoolCipher(true); + if (ParamCount>0) then Begin FormPatrimonio.lbVersao.Caption := 'Versão: ' + GetVersionInfo(ParamStr(0)); - - v_option := 'system'; - For intAux := 1 to ParamCount do - Begin - if LowerCase(Copy(ParamStr(intAux),1,10)) = '/p_option=' then - v_option := Trim(Copy(ParamStr(intAux),11,Length((ParamStr(intAux))))); - End; - - tstrTripa1 := g_oCacic.explode(ExtractFilePath(Application.Exename),'\'); //Pegarei o nível anterior do diretório, que deve ser, por exemplo \Cacic - v_path_cacic := ''; - For i := 0 to tstrTripa1.Count -2 do - v_path_cacic := v_path_cacic + tstrTripa1[i] + '\'; - - g_oCacic.setCacicPath(v_path_cacic); - v_Debugs := false; - if DirectoryExists(g_oCacic.getCacicPath + 'Temp\Debugs') then Begin - if (FormatDateTime('ddmmyyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs')) = FormatDateTime('ddmmyyyy', date)) then + strAux := ''; + For intAux := 1 to ParamCount do Begin - v_Debugs := true; - log_DEBUG('Pasta "' + g_oCacic.getCacicPath + 'Temp\Debugs" com data '+FormatDateTime('dd-mm-yyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs'))+' encontrada. DEBUG ativado.'); - End; - End; - - v_tstrCipherOpened := TStrings.Create; - v_tstrCipherOpened := CipherOpen(g_oCacic.getCacicPath + 'cacic2.dat'); - - v_tstrCipherOpened1 := TStrings.Create; - v_tstrCipherOpened1 := CipherOpen(g_oCacic.getCacicPath + 'temp\col_patr.dat'); - - // Os valores possíveis serão 0-DESLIGADO 1-LIGADO 2-ESPERA PARA LIGAR (Será transformado em "1") 3-Ainda se comunicará com o Gerente WEB - l_cs_cipher := false; - v_Aux := GetValorDatMemoria('Configs.CS_CIPHER', v_tstrCipherOpened); - if (v_Aux='1')then - Begin - l_cs_cipher := true; - End; - - Try - boolColeta := false; - if (GetValorDatMemoria('Patrimonio.in_alteracao_fisica',v_tstrCipherOpened)= 'S') then - Begin - // Solicita o cadastramento de informações de patrimõnio caso seja detectado remanejamento para uma nova rede. - MessageDlg('Atenção: foi identificada uma alteração na localização física deste computador. Por favor, confirme as informações que serão apresentadas na tela que será exibida a seguir.', mtInformation, [mbOk], 0); - boolColeta := true; - End - Else if (GetValorDatMemoria('Patrimonio.in_renovacao_informacoes',v_tstrCipherOpened)= 'S') and (v_option='system') then - Begin - // Solicita o cadastramento de informações de patrimõnio caso tenha completado o prazo configurado para renovação de informações. - MessageDlg('Atenção: é necessário o preenchimento/atualização das informações de Patrimônio e Localização Física deste computador. Por favor, confirme as informações que serão apresentadas na tela que será exibida a seguir.', mtInformation, [mbOk], 0); - boolColeta := true; - end - Else if (GetValorDatMemoria('Patrimonio.dt_ultima_renovacao_patrim',v_tstrCipherOpened)= '') then - Begin - // Solicita o cadastramento de informações de patrimõnio caso ainda não tenha sido cadastrado. - boolColeta := true; - end; - - if boolColeta then + if LowerCase(Copy(ParamStr(intAux),1,11)) = '/cacicpath=' then + begin + strAux := Trim(Copy(ParamStr(intAux),12,Length((ParamStr(intAux))))); + log_DEBUG('Parâmetro /CacicPath recebido com valor="'+strAux+'"'); + end; + end; + + if (strAux <> '') then Begin - SetValorDatMemoria('Col_Patr.Inicio', FormatDateTime('hh:nn:ss', Now), v_tstrCipherOpened1); - log_diario('Coletando informações de Patrimônio e Localização Física.'); - v_configs := GetValorDatMemoria('Patrimonio.Configs',v_tstrCipherOpened); - log_DEBUG('Configurações obtidas: '+v_configs); - - MontaInterface; - MontaCombos; - RecuperaValoresAnteriores; - + g_oCacic.setCacicPath(strAux); + v_Debugs := false; + if DirectoryExists(g_oCacic.getCacicPath + 'Temp\Debugs') then + Begin + if (FormatDateTime('ddmmyyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs')) = FormatDateTime('ddmmyyyy', date)) then + Begin + v_Debugs := true; + log_DEBUG('Pasta "' + g_oCacic.getCacicPath + 'Temp\Debugs" com data '+FormatDateTime('dd-mm-yyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs'))+' encontrada. DEBUG ativado.'); + End; + End; + + v_tstrCipherOpened := TStrings.Create; + v_tstrCipherOpened := CipherOpen(g_oCacic.getCacicPath + g_oCacic.getDatFileName); + + v_tstrCipherOpened1 := TStrings.Create; + v_tstrCipherOpened1 := CipherOpen(g_oCacic.getCacicPath + 'temp\col_patr.dat'); + + // Os valores possíveis serão 0-DESLIGADO 1-LIGADO 2-ESPERA PARA LIGAR (Será transformado em "1") 3-Ainda se comunicará com o Gerente WEB + l_cs_cipher := false; + v_Aux := GetValorDatMemoria('Configs.CS_CIPHER', v_tstrCipherOpened); + if (v_Aux='1')then + Begin + l_cs_cipher := true; + End; + + Try + boolColeta := false; + if (GetValorDatMemoria('Patrimonio.in_alteracao_fisica',v_tstrCipherOpened)= 'S') then + Begin + // Solicita o cadastramento de informações de patrimõnio caso seja detectado remanejamento para uma nova rede. + MessageDlg('Atenção: foi identificada uma alteração na localização física deste computador. Por favor, confirme as informações que serão apresentadas na tela que será exibida a seguir.', mtInformation, [mbOk], 0); + boolColeta := true; + End + Else if (GetValorDatMemoria('Patrimonio.in_renovacao_informacoes',v_tstrCipherOpened)= 'S') and (v_option='system') then + Begin + // Solicita o cadastramento de informações de patrimõnio caso tenha completado o prazo configurado para renovação de informações. + MessageDlg('Atenção: é necessário o preenchimento/atualização das informações de Patrimônio e Localização Física deste computador. Por favor, confirme as informações que serão apresentadas na tela que será exibida a seguir.', mtInformation, [mbOk], 0); + boolColeta := true; + end + Else if (GetValorDatMemoria('Patrimonio.dt_ultima_renovacao_patrim',v_tstrCipherOpened)= '') then + Begin + // Solicita o cadastramento de informações de patrimõnio caso ainda não tenha sido cadastrado. + boolColeta := true; + end; + + if boolColeta then + Begin + SetValorDatMemoria('Col_Patr.Inicio', FormatDateTime('hh:nn:ss', Now), v_tstrCipherOpened1); + log_diario('Coletando informações de Patrimônio e Localização Física.'); + v_configs := GetValorDatMemoria('Patrimonio.Configs',v_tstrCipherOpened); + log_DEBUG('Configurações obtidas: '+v_configs); + + MontaInterface; + MontaCombos; + RecuperaValoresAnteriores; + + End; + Except + SetValorDatMemoria('Col_Patr.nada','nada', v_tstrCipherOpened1); + SetValorDatMemoria('Col_Patr.Fim', '99999999', v_tstrCipherOpened1); + CipherClose(g_oCacic.getCacicPath + 'temp\col_patr.dat', v_tstrCipherOpened1); + g_oCacic.Free(); + Application.Terminate; + End; End; - Except - SetValorDatMemoria('Col_Patr.nada','nada', v_tstrCipherOpened1); - SetValorDatMemoria('Col_Patr.Fim', '99999999', v_tstrCipherOpened1); - CipherClose(g_oCacic.getCacicPath + 'temp\col_patr.dat', v_tstrCipherOpened1); - g_oCacic.Free(); - Application.Terminate; - End; - End; -end; - + End; + end; +End; end. diff --git a/col_soft/col_soft.dpr b/col_soft/col_soft.dpr index dcb54c1..6b172d9 100755 --- a/col_soft/col_soft.dpr +++ b/col_soft/col_soft.dpr @@ -78,7 +78,6 @@ begin Append(HistoricoLog); Writeln(HistoricoLog,FormatDateTime('dd/mm hh:nn:ss : ', Now)+ '[Coletor SOFT] '+strMsg); {Grava a string Texto no arquivo texto} CloseFile(HistoricoLog); {Fecha o arquivo texto} - except log_diario('Erro na gravação do log!'); end; @@ -623,43 +622,53 @@ begin End; end; -var v_path_cacic : String; +var strAux : String; begin g_oCacic := TCACIC.Create(); + g_oCacic.setBoolCipher(true); + if( not g_oCacic.isAppRunning( CACIC_APP_NAME ) ) then if (ParamCount>0) then - Begin - //Pegarei o nível anterior do diretório, que deve ser, por exemplo \Cacic, para leitura do cacic2.ini - tstrTripa1 := g_oCacic.explode(ExtractFilePath(ParamStr(0)),'\'); - v_path_cacic := ''; - For intAux := 0 to tstrTripa1.Count -2 do - v_path_cacic := v_path_cacic + tstrTripa1[intAux] + '\'; - - v_tstrCipherOpened := TStrings.Create; - v_tstrCipherOpened := CipherOpen(g_oCacic.getDatFileName); - - v_tstrCipherOpened1 := TStrings.Create; - v_tstrCipherOpened1 := CipherOpen(g_oCacic.getCacicPath + 'temp\col_soft.dat'); - - Try - v_Debugs := false; + Begin + strAux := ''; + For intAux := 1 to ParamCount do + Begin + if LowerCase(Copy(ParamStr(intAux),1,11)) = '/cacicpath=' then + begin + strAux := Trim(Copy(ParamStr(intAux),12,Length((ParamStr(intAux))))); + end; + end; - if DirectoryExists(g_oCacic.getCacicPath + 'Temp\Debugs') then + if (strAux <> '') then Begin - if (FormatDateTime('ddmmyyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs')) = FormatDateTime('ddmmyyyy', date)) then - Begin - v_Debugs := true; - log_diario('Pasta "' + g_oCacic.getCacicPath + 'Temp\Debugs" com data '+FormatDateTime('dd-mm-yyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs'))+' encontrada. DEBUG ativado.'); - End; + g_oCacic.setCacicPath(strAux); + + v_tstrCipherOpened := TStrings.Create; + v_tstrCipherOpened := CipherOpen(g_oCacic.getCacicPath + g_oCacic.getDatFileName); + + v_tstrCipherOpened1 := TStrings.Create; + v_tstrCipherOpened1 := CipherOpen(g_oCacic.getCacicPath + 'temp\col_soft.dat'); + + Try + v_Debugs := false; + + if DirectoryExists(g_oCacic.getCacicPath + 'Temp\Debugs') then + Begin + if (FormatDateTime('ddmmyyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs')) = FormatDateTime('ddmmyyyy', date)) then + Begin + v_Debugs := true; + log_diario('Pasta "' + g_oCacic.getCacicPath + 'Temp\Debugs" com data '+FormatDateTime('dd-mm-yyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs'))+' encontrada. DEBUG ativado.'); + End; + End; + + Executa_Col_Soft; + Except + SetValorDatMemoria('Col_Soft.nada', 'nada', v_tstrCipherOpened1); + CipherClose(g_oCacic.getCacicPath + 'temp\col_soft.dat', v_tstrCipherOpened1); + End; End; - - Executa_Col_Soft; - Except - SetValorDatMemoria('Col_Soft.nada', 'nada', v_tstrCipherOpened1); - CipherClose(g_oCacic.getCacicPath + 'temp\col_soft.dat', v_tstrCipherOpened1); - End; - End; + End; g_oCacic.Free(); diff --git a/col_undi/col_undi.dpr b/col_undi/col_undi.dpr index cc33da3..a76440f 100755 --- a/col_undi/col_undi.dpr +++ b/col_undi/col_undi.dpr @@ -385,45 +385,52 @@ Begin End; end; -var v_path_cacic : String; +var strAux : String; begin g_oCacic := TCACIC.Create(); + g_oCacic.setBoolCipher(true); + if( not g_oCacic.isAppRunning( CACIC_APP_NAME ) ) then if (ParamCount>0) then - Begin - //Pegarei o nível anterior do diretório, que deve ser, por exemplo \Cacic, para leitura do cacic2.ini - tstrTripa1 := g_oCacic.explode(ExtractFilePath(ParamStr(0)),'\'); - v_path_cacic := ''; - For intAux := 0 to tstrTripa1.Count -2 do - begin - v_path_cacic := v_path_cacic + tstrTripa1[intAux] + '\'; - end; - - v_tstrCipherOpened := TStrings.Create; - v_tstrCipherOpened := CipherOpen(g_oCacic.getDatFileName); - - v_tstrCipherOpened1 := TStrings.Create; - v_tstrCipherOpened1 := CipherOpen(g_oCacic.getCacicPath + 'temp\col_undi.dat'); - - Try - v_Debugs := false; - if DirectoryExists(g_oCacic.getCacicPath + 'Temp\Debugs') then - Begin - if (FormatDateTime('ddmmyyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs')) = FormatDateTime('ddmmyyyy', date)) then - Begin - v_Debugs := true; - log_diario('Pasta "' + g_oCacic.getCacicPath + 'Temp\Debugs" com data '+FormatDateTime('dd-mm-yyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs'))+' encontrada. DEBUG ativado.'); - End; - End; - - Executa_Col_undi; - Except - SetValorDatMemoria('Col_Undi.nada', 'nada', v_tstrCipherOpened1); - CipherClose(g_oCacic.getCacicPath + 'temp\col_undi.dat', v_tstrCipherOpened1); - End; - End; - + Begin + strAux := ''; + For intAux := 1 to ParamCount do + Begin + if LowerCase(Copy(ParamStr(intAux),1,11)) = '/cacicpath=' then + begin + strAux := Trim(Copy(ParamStr(intAux),12,Length((ParamStr(intAux))))); + end; + end; + + if (strAux <> '') then + Begin + g_oCacic.setCacicPath(strAux); + + v_tstrCipherOpened := TStrings.Create; + v_tstrCipherOpened := CipherOpen(g_oCacic.getCacicPath + g_oCacic.getDatFileName); + + v_tstrCipherOpened1 := TStrings.Create; + v_tstrCipherOpened1 := CipherOpen(g_oCacic.getCacicPath + 'temp\col_undi.dat'); + + Try + v_Debugs := false; + if DirectoryExists(g_oCacic.getCacicPath + 'Temp\Debugs') then + Begin + if (FormatDateTime('ddmmyyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs')) = FormatDateTime('ddmmyyyy', date)) then + Begin + v_Debugs := true; + log_diario('Pasta "' + g_oCacic.getCacicPath + 'Temp\Debugs" com data '+FormatDateTime('dd-mm-yyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs'))+' encontrada. DEBUG ativado.'); + End; + End; + + Executa_Col_undi; + Except + SetValorDatMemoria('Col_Undi.nada', 'nada', v_tstrCipherOpened1); + CipherClose(g_oCacic.getCacicPath + 'temp\col_undi.dat', v_tstrCipherOpened1); + End; + End; + End; g_oCacic.Free(); end. diff --git a/ger_cols/ger_cols.dpr b/ger_cols/ger_cols.dpr index da07237..bf56e30 100755 --- a/ger_cols/ger_cols.dpr +++ b/ger_cols/ger_cols.dpr @@ -78,7 +78,6 @@ var var v_Debugs, - l_cs_cipher, l_cs_compress, v_CS_AUTO_UPDATE : boolean; @@ -132,6 +131,7 @@ var intLimite, strPalavra, strCaracter : String; begin + log_diario('Regerando palavra-chave...'); Randomize; strPalavra := ''; intLimite := RandomRange(10,30); // Gerarei uma palavra com tamanho mínimo 10 e máximo 30 @@ -350,13 +350,13 @@ begin v_strCipherOpenImploded := g_oCacic.implode(p_tstrCipherOpened,g_oCacic.getSeparatorKey); - v_cs_cipher := l_cs_cipher; - l_cs_cipher := true; - log_DEBUG('Rotina de Fechamento do cacic2.dat ATIVANDO criptografia.'); + v_cs_cipher := g_oCacic.getBoolCipher; + g_oCacic.setBoolCipher(true); + log_DEBUG('Rotina de Fechamento do ' + g_oCacic.getDatFileName + '. ATIVANDO criptografia.'); v_strCipherClosed := g_oCacic.enCrypt(v_strCipherOpenImploded); - l_cs_cipher := v_cs_cipher; - log_DEBUG('Rotina de Fechamento do cacic2.dat RESTAURANDO estado da criptografia.'); + g_oCacic.setBoolCipher(v_cs_cipher); + log_DEBUG('Rotina de Fechamento do ' + g_oCacic.getDatFileName + '. RESTAURANDO estado da criptografia.'); Writeln(v_DatFile,v_strCipherClosed); {Grava a string Texto no arquivo texto} if v_Debugs then Begin @@ -395,12 +395,12 @@ begin Readln(v_DatFile,v_strCipherClosed); while not EOF(v_DatFile) do Readln(v_DatFile,v_strCipherClosed); CloseFile(v_DatFile); - v_cs_cipher := l_cs_cipher; - l_cs_cipher := true; - log_DEBUG('Rotina de Abertura do cacic2.dat ATIVANDO criptografia.'); + v_cs_cipher := g_oCacic.getBoolCipher; + g_oCacic.setBoolCipher(true); + log_DEBUG('Rotina de Abertura do ' + g_oCacic.getDatFileName + '. ATIVANDO criptografia.'); v_strCipherOpened:= g_oCacic.deCrypt(v_strCipherClosed); - l_cs_cipher := v_cs_cipher; - log_DEBUG('Rotina de Abertura do cacic2.dat RESTAURANDO estado da criptografia.'); + g_oCacic.setBoolCipher(v_cs_cipher); + log_DEBUG('Rotina de Abertura do ' + g_oCacic.getDatFileName + '. RESTAURANDO estado da criptografia.'); end; if (trim(v_strCipherOpened)<>'') then Result := g_oCacic.explode(v_strCipherOpened,g_oCacic.getSeparatorKey) @@ -418,25 +418,24 @@ begin Matar(g_oCacic.getCacicPath + 'temp\','*.txt'); end; +procedure Sair; +Begin + g_oCacic.Free; + Halt(0); +End; + procedure Finalizar(p_pausa:boolean); Begin - CipherClose(g_oCacic.getDatFileName, v_tstrCipherOpened); + CipherClose(g_oCacic.getCacicPath + g_oCacic.getDatFileName, v_tstrCipherOpened); Apaga_Temps; if p_pausa then sleep(2000); // Pausa de 2 segundos para conclusão de operações de arquivos. End; -procedure Sair; -Begin - log_DEBUG('Liberando Memória - FreeMemory(0)'); - FreeMemory(0); - log_DEBUG('Suspendendo - Halt(0)'); - Halt(0); -End; -procedure Seta_l_cs_cipher(p_strRetorno : String); +procedure Seta_boolCipher(p_strRetorno : String); var v_Aux : string; Begin - l_cs_cipher := false; + g_oCacic.setBoolCipher(false); v_Aux := XML_RetornaValor('cs_cipher',p_strRetorno); if (p_strRetorno = '') or (v_Aux = '') then v_Aux := '3'; @@ -444,7 +443,7 @@ Begin if (v_Aux='1') then Begin log_DEBUG('ATIVANDO Criptografia!'); - l_cs_cipher := true; + g_oCacic.setBoolCipher(true); End else if (v_Aux='2') then Begin @@ -1558,7 +1557,7 @@ procedure Patrimnio1Click(Sender: TObject); begin SetValorDatMemoria('Patrimonio.dt_ultima_renovacao_patrim','', v_tstrCipherOpened); if ChecaAgente(g_oCacic.getCacicPath + 'modulos', 'ini_cols.exe') then - g_oCacic.createSampleProcess( g_oCacic.getCacicPath + 'modulos\ini_cols.exe /p_ModulosOpcoes=col_patr,wait,user#', CACIC_PROCESS_WAIT ); + g_oCacic.createSampleProcess( g_oCacic.getCacicPath + 'modulos\ini_cols.exe /CacicPath='+g_oCacic.getCacicPath+' /p_ModulosOpcoes=col_patr,wait,user#', CACIC_PROCESS_WAIT ); if (FileExists(g_oCacic.getCacicPath + 'Temp\col_patr.dat')) then Begin @@ -1627,11 +1626,11 @@ end; procedure ChecaCipher; begin // Os valores possíveis serão 0-DESLIGADO 1-LIGADO 2-ESPERA PARA LIGAR (Será transformado em "1") 3-Ainda se comunicará com o Gerente WEB - l_cs_cipher := false; + g_oCacic.setBoolCipher(false); v_Aux := GetValorDatMemoria('Configs.CS_CIPHER', v_tstrCipherOpened); if (v_Aux='1') or (v_Aux='2') then Begin - l_cs_cipher := true; + g_oCacic.setBoolCipher(true); SetValorDatMemoria('Configs.CS_CIPHER','1', v_tstrCipherOpened); End else @@ -1654,17 +1653,63 @@ begin end; procedure BuscaConfigs(p_mensagem_log : boolean); -var Request_SVG, v_array_campos, v_array_valores, v_Report : TStringList; - intAux1, intAux2, intAux3, intAux4, v_conta_EXCECOES, v_index_ethernet : integer; - strRetorno, strTripa, strAux3, ValorChaveRegistro, ValorRetornado, v_mensagem_log, - v_mascara,te_ip,te_mascara, te_gateway, te_serv_dhcp, te_dns_primario, te_dns_secundario, te_wins_primario, te_wins_secundario, te_nome_host, te_dominio_dns, te_dominio_windows, - v_mac_address,v_metodo_obtencao,v_nome_arquivo,IpConfigLINHA, v_enderecos_mac_invalidos, v_win_dir, v_dir_command, v_dir_ipcfg, v_win_dir_command, v_win_dir_ipcfg, v_te_serv_cacic : string; - tstrTripa1, tstrTripa2, tstrTripa3, tstrTripa4, tstrTripa5, tstrEXCECOES : TStrings; - IpConfigTXT, chksis_ini : textfile; - - v_oMachine : TMiTec_Machine; - v_TCPIP : TMiTeC_TCPIP; - v_NETWORK : TMiTeC_Network; +var + Request_SVG, + v_array_campos, + v_array_valores, + v_Report : TStringList; + + intAux1, + intAux2, + intAux3, + intAux4, + v_conta_EXCECOES, + v_index_ethernet : integer; + + strRetorno, + strTripa, + strAux3, + ValorChaveRegistro, + ValorRetornado, + v_mensagem_log, + v_mascara, + te_ip, + te_mascara, + te_gateway, + te_serv_dhcp, + te_dns_primario, + te_dns_secundario, + te_wins_primario, + te_wins_secundario, + te_nome_host, + te_dominio_dns, + te_dominio_windows, + v_mac_address, + v_metodo_obtencao, + v_nome_arquivo, + IpConfigLINHA, + v_enderecos_mac_invalidos, + v_win_dir, + v_dir_command, + v_dir_ipcfg, + v_win_dir_command, + v_win_dir_ipcfg, + v_te_serv_cacic : string; + + tstrTripa1, + tstrTripa2, + tstrTripa3, + tstrTripa4, + tstrTripa5, + tstrEXCECOES : TStrings; + + IpConfigTXT, + chksis_ini, + v_txtCookie : TextFile; + + v_oMachine : TMiTec_Machine; + v_TCPIP : TMiTeC_TCPIP; + v_NETWORK : TMiTeC_Network; Begin Try ChecaCipher; @@ -1755,12 +1800,12 @@ Begin SetValorDatMemoria('TcpIp.TE_IP',v_tcpip.Adapter[v_index_ethernet].IPAddress[intAux1], v_tstrCipherOpened); Try strRetorno := ComunicaServidor('get_config.php', Request_SVG, 'Testando comunicação com o Módulo Gerente WEB.'); - Seta_l_cs_cipher(strRetorno); + Seta_boolCipher(strRetorno); Seta_l_cs_compress(strRetorno); v_Aux := g_oCacic.deCrypt(XML_RetornaValor('te_serv_cacic', strRetorno)); if (v_te_serv_cacic <> v_Aux) and (v_Aux <> '') then - SetValorDatMemoria('Configs.EnderecoServidor',v_Aux, v_tstrCipherOpened); + SetValorDatMemoria('Configs.EnderecoServidor',Trim(v_Aux), v_tstrCipherOpened); if (strRetorno <> '0') and (g_oCacic.deCrypt(XML_RetornaValor('te_rede_ok', strRetorno))<>'N') Then Begin @@ -1783,12 +1828,12 @@ Begin Request_SVG.Values['in_teste'] := StringReplace(g_oCacic.enCrypt('OK'),'+','',[rfReplaceAll]); Try strRetorno := ComunicaServidor('get_config.php', Request_SVG, 'Teste de comunicação com o Módulo Gerente WEB.'); - Seta_l_cs_cipher(strRetorno); + Seta_boolCipher(strRetorno); Seta_l_cs_compress(strRetorno); v_Aux := g_oCacic.deCrypt(XML_RetornaValor('te_serv_cacic', strRetorno)); if (v_te_serv_cacic <> v_Aux) and (v_Aux <> '') then - SetValorDatMemoria('Configs.EnderecoServidor',v_Aux, v_tstrCipherOpened); + SetValorDatMemoria('Configs.EnderecoServidor',Trim(v_Aux), v_tstrCipherOpened); if (strRetorno <> '0') and (g_oCacic.deCrypt(XML_RetornaValor('te_rede_ok', strRetorno))<>'N') Then Begin @@ -1860,11 +1905,9 @@ Begin log_DEBUG(v_acao_gercols + ' Parâmetros: in_chkcacic="'+Request_SVG.Values['in_chkcacic']+'", te_fila_ftp="'+Request_SVG.Values['te_fila_ftp']+'" e id_ip_estacao="'+Request_SVG.Values['id_ip_estacao']+'"'); strRetorno := ComunicaServidor('get_config.php', Request_SVG, v_mensagem_log); - Seta_l_cs_cipher(strRetorno); + Seta_boolCipher(strRetorno); Seta_l_cs_compress(strRetorno); - - Request_SVG.Free; if (strRetorno <> '0') Then Begin @@ -1972,7 +2015,7 @@ Begin log_DEBUG('Executando "'+g_oCacic.getCacicPath + 'modulos\' + v_scripter + ' //b ' + g_oCacic.getCacicPath + 'temp\ipconfig.vbs"'); if ChecaAgente(g_oCacic.getCacicPath + 'modulos', v_scripter) then - WinExec(PChar(g_oCacic.getCacicPath + 'modulos\' + v_scripter + ' //b ' + g_oCacic.getCacicPath + 'temp\ipconfig.vbs'), SW_HIDE); + g_oCacic.createSampleProcess(g_oCacic.getCacicPath + 'modulos\' + v_scripter + ' //b ' + g_oCacic.getCacicPath + 'temp\ipconfig.vbs', false); Except Begin log_diario('Erro na geração do ipconfig.txt pelo ' + v_metodo_obtencao+'.'); @@ -2014,7 +2057,7 @@ Begin v_dir_ipcfg := '\'; End; - WinExec(PChar(v_win_dir + v_dir_command + '\cmd.exe /c ' + v_win_dir + v_dir_ipcfg + '\ipconfig.exe /all > ' + v_nome_arquivo), SW_MINIMIZE); + g_oCacic.createSampleProcess(v_win_dir + v_dir_command + '\cmd.exe /c ' + v_win_dir + v_dir_ipcfg + '\ipconfig.exe /all > ' + v_nome_arquivo, false); End else Begin @@ -2036,7 +2079,7 @@ Begin v_win_dir_ipcfg := LeftStr(v_win_dir_command,2); v_dir_ipcfg := '\'; End; - WinExec(PChar(v_win_dir + v_dir_command + '\command.com /c ' + v_win_dir + v_dir_ipcfg + '\winipcfg.exe /all /batch ' + v_nome_arquivo), SW_MINIMIZE); + g_oCacic.createSampleProcess(v_win_dir + v_dir_command + '\command.com /c ' + v_win_dir + v_dir_ipcfg + '\winipcfg.exe /all /batch ' + v_nome_arquivo, false); End; Except log_diario('Erro na geração do ipconfig.txt pelo ' + v_metodo_obtencao+'.'); End; @@ -2253,8 +2296,13 @@ Begin v_Aux := StringReplace(v_Aux ,'\' ,'' ,[rfReplaceAll]); v_Aux := StringReplace(g_oCacic.enCrypt(v_Aux) ,'+' ,'' ,[rfReplaceAll]); - log_DEBUG('Invocando "'+g_oCacic.getCacicPath + 'modulos\srcacicsrv.exe -update [' + v_Aux + ']' ); - WinExec(PChar(g_oCacic.getCacicPath + 'modulos\srcacicsrv.exe -update [' + v_Aux + ']'),SW_NORMAL); + log_DEBUG('Criando cookie para srCACICsrv com nova palavra-chave.'); + + AssignFile(v_txtCookie,g_oCacic.getCacicPath + 'temp\cacic_ck.txt'); + Rewrite(v_txtCookie); + Append(v_txtCookie); + Writeln(v_txtCookie,v_Aux); + CloseFile(v_txtCookie); End; @@ -2264,12 +2312,12 @@ Begin strRetorno := ComunicaServidor('get_config.php', Request_SVG, v_mensagem_log); // A versão com criptografia do Módulo Gerente WEB retornará o valor cs_cipher=1(Quando receber "1") ou cs_cipher=2(Quando receber "3") - Seta_l_cs_cipher(strRetorno); + Seta_boolCipher(strRetorno); // A versão com compressão do Módulo Gerente WEB retornará o valor cs_compress=1(Quando receber "1") ou cs_compress=2(Quando receber "3") Seta_l_cs_compress(strRetorno); - v_te_serv_cacic := g_oCacic.deCrypt(XML_RetornaValor('te_serv_cacic',strRetorno)); + v_te_serv_cacic := trim(g_oCacic.deCrypt(XML_RetornaValor('te_serv_cacic',strRetorno))); if (strRetorno <> '0') and (v_te_serv_cacic<>'') and @@ -2278,7 +2326,7 @@ Begin v_mensagem_log := 'Novo endereço para Gerente WEB: '+v_te_serv_cacic; SetValorDatMemoria('Configs.EnderecoServidor',v_te_serv_cacic, v_tstrCipherOpened); log_DEBUG('Setando Criptografia para 3. (Primeiro contato)'); - Seta_l_cs_cipher(''); + Seta_boolCipher(''); log_DEBUG('Refazendo comunicação'); // Passei a enviar sempre a versão do CACIC... @@ -2287,7 +2335,7 @@ Begin Request_SVG := TStringList.Create; Request_SVG.Values['te_tripa_perfis'] := StringReplace(g_oCacic.enCrypt(''),'+','',[rfReplaceAll]); strRetorno := ComunicaServidor('get_config.php', Request_SVG, v_mensagem_log); - Seta_l_cs_cipher(strRetorno); + Seta_boolCipher(strRetorno); Seta_l_cs_compress(strRetorno); End; @@ -2337,7 +2385,7 @@ Begin v_acao_gercols := 'Armazenando valores obtidos no DAT Memória.'; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - //Gravação no CACIC2.DAT dos valores de REDE, COMPUTADOR e EXECUÇÃO obtidos, para consulta pelos outros módulos... + //Gravação no DatFileName dos valores de REDE, COMPUTADOR e EXECUÇÃO obtidos, para consulta pelos outros módulos... ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// SetValorDatMemoria('Configs.CS_AUTO_UPDATE' ,UpperCase(g_oCacic.deCrypt(XML_RetornaValor('cs_auto_update' , strRetorno))), v_tstrCipherOpened); SetValorDatMemoria('Configs.CS_COLETA_HARDWARE' ,UpperCase(g_oCacic.deCrypt(XML_RetornaValor('cs_coleta_hardware' , strRetorno))), v_tstrCipherOpened); @@ -2489,7 +2537,7 @@ Begin Finalizar(false); if ChecaAgente(g_oCacic.getCacicPath, 'cacic2.exe') then - WinExec(PChar(g_oCacic.getCacicPath + 'cacic2.exe /atualizacao'), SW_MINIMIZE); + g_oCacic.createSampleProcess(g_oCacic.getCacicPath + 'cacic2.exe /atualizacao', false); Sair; end; @@ -2542,7 +2590,7 @@ Begin BuscaConfigs(false); Batchfile := TStringList.Create; Batchfile.Add('*** Simulação de cookie para cacic2.exe recarregar os valores de configurações ***'); - // A existência deste arquivo forçará o Cacic2.exe a recarregar valores das configurações obtidas e gravadas no Cacic2.DAT + // A existência deste arquivo forçará o Cacic2.exe a recarregar valores das configurações obtidas e gravadas no DatFileName Batchfile.SaveToFile(g_oCacic.getCacicPath + 'Temp\reset.txt'); BatchFile.Free; log_DEBUG('Configurações apanhadas no módulo Gerente WEB. Retornando ao Agente Principal...'); @@ -2799,7 +2847,7 @@ Begin Finalizar(false); Matar(g_oCacic.getCacicPath + 'temp\','*.dat'); CriaTXT(g_oCacic.getCacicPath+'temp','coletas'); - g_oCacic.createSampleProcess( g_oCacic.getCacicPath + 'modulos\ini_cols.exe /p_ModulosOpcoes=' + v_ModulosOpcoes, CACIC_PROCESS_WAIT ); + g_oCacic.createSampleProcess( g_oCacic.getCacicPath + 'modulos\ini_cols.exe /CacicPath='+g_oCacic.getCacicPath+' /p_ModulosOpcoes=' + v_ModulosOpcoes, CACIC_PROCESS_WAIT ); End; end @@ -3209,77 +3257,86 @@ Begin SetValorDatMemoria('Erro_Fatal_Descricao', v_acao_gercols, v_tstrCipherOpened); End; End; - + g_oCacic.Free; End; -var v_path_cacic : String; begin g_oCacic := TCACIC.Create(); - if( not g_oCacic.isAppRunning( CACIC_APP_NAME ) ) then begin - Try - // Pegarei o nível anterior do diretório, que deve ser, por exemplo \Cacic, para leitura do cacic2.DAT - tstrTripa1 := g_oCacic.explode(ExtractFilePath(ParamStr(0)),'\'); - v_path_cacic := ''; - For intAux := 0 to tstrTripa1.Count -2 do - v_path_cacic := v_path_cacic + tstrTripa1[intAux] + '\'; - - g_oCacic.setCacicPath(v_path_cacic); - v_Debugs := false; - if DirectoryExists(g_oCacic.getCacicPath + 'Temp\Debugs') then - if (FormatDateTime('ddmmyyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs')) = FormatDateTime('ddmmyyyy', date)) then - Begin - v_Debugs := true; - log_DEBUG('Pasta "' + g_oCacic.getCacicPath + 'Temp\Debugs" com data '+FormatDateTime('dd-mm-yyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs'))+' encontrada. DEBUG ativado.'); - End; - - g_oCacic.setCacicPath(g_oCacic.getCacicPath); - - - - // De acordo com a versão do OS, determina-se o ShellCommand para chamadas externas. - p_Shell_Command := 'cmd.exe /c '; //NT/2K/XP - if(g_oCacic.isWindows9xME()) then - p_Shell_Command := 'command.com /c '; - - if not DirectoryExists(g_oCacic.getCacicPath + 'Temp') then - ForceDirectories(g_oCacic.getCacicPath + 'Temp'); - - v_tstrCipherOpened := TStrings.Create; - v_tstrCipherOpened := CipherOpen(g_oCacic.getDatFileName); - - // Não tirar desta posição - SetValorDatMemoria('Configs.TE_SO',g_oCacic.getWindowsStrId(), v_tstrCipherOpened); - - log_DEBUG('Te_So obtido: "' + g_oCacic.getWindowsStrId() +'"'); - - v_scripter := 'wscript.exe'; - // A existência e bloqueio do arquivo abaixo evitará que Cacic2.exe chame o Ger_Cols quando este estiver em funcionamento - AssignFile(v_Aguarde,g_oCacic.getCacicPath + 'temp\aguarde_GER.txt'); {Associa o arquivo a uma variável do tipo TextFile} - {$IOChecks off} - Reset(v_Aguarde); {Abre o arquivo texto} - {$IOChecks on} - if (IOResult <> 0) then // Arquivo não existe, será recriado. - Rewrite (v_Aguarde); + if( not g_oCacic.isAppRunning( CACIC_APP_NAME ) ) then + begin + if ParamCount > 0 then + Begin + strAux := ''; + v_Debugs := true; - Append(v_Aguarde); - Writeln(v_Aguarde,'Apenas um pseudo-cookie para o Cacic2 esperar o término de Ger_Cols'); - Append(v_Aguarde); + For intAux := 1 to ParamCount do + Begin + if (LowerCase(Copy(ParamStr(intAux),1,11)) = '/cacicpath=') then + begin + v_acao_gercols := 'Configurando CacicPath.'; + strAux := Copy(ParamStr(intAux),12,StrLen(PChar(ParamStr(intAux)))); + end; + end; - ChecaCipher; - ChecaCompress; + if (strAux <> '') then + Begin + g_oCacic.setCacicPath(strAux); + log_DEBUG('Parâmetro /CacicPath recebido com valor="'+strAux+'"'); + Try + v_Debugs := false; + if DirectoryExists(g_oCacic.getCacicPath + 'Temp\Debugs') then + if (FormatDateTime('ddmmyyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs')) = FormatDateTime('ddmmyyyy', date)) then + Begin + v_Debugs := true; + log_DEBUG('Pasta "' + g_oCacic.getCacicPath + 'Temp\Debugs" com data '+FormatDateTime('dd-mm-yyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs'))+' encontrada. DEBUG ativado.'); + End; - Executa_Ger_Cols; - Finalizar(true); - Except - Begin - log_diario('PROBLEMAS EM EXECUTA_GER_COLS! Ação: ' + v_acao_gercols+'.'); - CriaTXT(g_oCacic.getCacicPath,'ger_erro'); - Finalizar(false); - SetValorDatMemoria('Erro_Fatal_Descricao', v_acao_gercols, v_tstrCipherOpened); - End; - End; + g_oCacic.setCacicPath(g_oCacic.getCacicPath); + + // De acordo com a versão do OS, determina-se o ShellCommand para chamadas externas. + p_Shell_Command := 'cmd.exe /c '; //NT/2K/XP + if(g_oCacic.isWindows9xME()) then + p_Shell_Command := 'command.com /c '; + + if not DirectoryExists(g_oCacic.getCacicPath + 'Temp') then + ForceDirectories(g_oCacic.getCacicPath + 'Temp'); + + v_tstrCipherOpened := TStrings.Create; + v_tstrCipherOpened := CipherOpen(g_oCacic.getCacicPath + g_oCacic.getDatFileName); + + // Não tirar desta posição + SetValorDatMemoria('Configs.TE_SO',g_oCacic.getWindowsStrId(), v_tstrCipherOpened); + + log_DEBUG('Te_So obtido: "' + g_oCacic.getWindowsStrId() +'"'); + + v_scripter := 'wscript.exe'; + // A existência e bloqueio do arquivo abaixo evitará que Cacic2.exe chame o Ger_Cols quando este estiver em funcionamento + AssignFile(v_Aguarde,g_oCacic.getCacicPath + 'temp\aguarde_GER.txt'); {Associa o arquivo a uma variável do tipo TextFile} + {$IOChecks off} + Reset(v_Aguarde); {Abre o arquivo texto} + {$IOChecks on} + if (IOResult <> 0) then // Arquivo não existe, será recriado. + Rewrite (v_Aguarde); + + Append(v_Aguarde); + Writeln(v_Aguarde,'Apenas um pseudo-cookie para o Cacic2 esperar o término de Ger_Cols'); + Append(v_Aguarde); + + ChecaCipher; + ChecaCompress; + + Executa_Ger_Cols; + Finalizar(true); + Except + Begin + log_diario('PROBLEMAS EM EXECUTA_GER_COLS! Ação: ' + v_acao_gercols+'.'); + CriaTXT(g_oCacic.getCacicPath,'ger_erro'); + Finalizar(false); + SetValorDatMemoria('Erro_Fatal_Descricao', v_acao_gercols, v_tstrCipherOpened); + End; + End; + End; + End; End; - - g_oCacic.Free(); end. diff --git a/ini_cols/ini_cols.dpr b/ini_cols/ini_cols.dpr index 59353dd..d0a64a1 100755 --- a/ini_cols/ini_cols.dpr +++ b/ini_cols/ini_cols.dpr @@ -27,20 +27,24 @@ uses PJVersionInfo, CACIC_Library in '..\CACIC_Library.pas'; -var v_te_senha_login_serv_updates, - v_versao : string; - v_array_path_cacic : TStrings; - intAux, - v_ContaTempo, - v_Tolerancia : integer; - v_ModulosOpcoes, - v_Aux : String; - v_Debugs : Boolean; - v_Aguarde : TextFile; - -var v_tstrCipherOpened, - v_tstrModulosOpcoes, - v_tstrModuloOpcao : TStrings; +var + v_te_senha_login_serv_updates, + v_versao, + v_ModulosOpcoes : String; + +var + v_tstrCipherOpened, + v_tstrModulosOpcoes, + v_tstrModuloOpcao : TStrings; + +var + intAux, + v_ContaTempo, + v_Tolerancia : integer; + +var + v_Debugs : Boolean; + v_Aguarde : TextFile; var g_oCacic : TCACIC; @@ -158,7 +162,6 @@ var v_DatFile : TextFile; v_strCipherClosed : string; oCacic : TCACIC; begin - oCacic := TCACIC.Create(); v_strCipherOpened := ''; if FileExists(p_DatFileName) then begin @@ -190,8 +193,6 @@ begin log_DEBUG('Vetor MemoryDAT com tamanho IMPAR... Ajustando.'); Result.Add(''); End; - - oCacic.Free(); end; Function FTP(p_Host : String; p_Port : String; p_Username : String; p_Password : String; p_PathServer : String; p_File : String; p_Dest : String) : Boolean; @@ -225,100 +226,108 @@ begin End; end; -var v_path_cacic : String; +var strAux : String; begin g_oCacic := TCACIC.Create(); + g_oCacic.setBoolCipher(true); + if( not g_oCacic.isAppRunning( CACIC_APP_NAME ) ) then - if (ParamCount>0) then // A passagem da chave EAS é mandatória... - Begin - //Pegarei o nível anterior do diretório, que deve ser, por exemplo \Cacic, para leitura do cacic2.dat - v_array_path_cacic := g_oCacic.explode(ExtractFilePath(ParamStr(0)),'\'); - v_path_cacic := ''; - For intAux := 0 to v_array_path_cacic.Count -2 do - v_path_cacic := v_path_cacic + v_array_path_cacic[intAux] + '\'; - - g_oCacic.setCacicPath(v_path_cacic); - v_Debugs := false; - if DirectoryExists(g_oCacic.getCacicPath + 'Temp\Debugs') then - Begin - if (FormatDateTime('ddmmyyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs')) = FormatDateTime('ddmmyyyy', date)) then - Begin - v_Debugs := true; - log_DEBUG('Pasta "' + g_oCacic.getCacicPath + 'Temp\Debugs" com data '+FormatDateTime('dd-mm-yyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs'))+' encontrada. DEBUG ativado.'); - End; - End; - - // A existência e bloqueio do arquivo abaixo evitará que Cacic2.exe chame o Ger_Cols quando a coleta ainda estiver sendo efetuada - AssignFile(v_Aguarde,g_oCacic.getCacicPath + 'temp\aguarde_INI.txt'); {Associa o arquivo a uma variável do tipo TextFile} - {$IOChecks off} - Reset(v_Aguarde); {Abre o arquivo texto} - {$IOChecks on} - if (IOResult <> 0) then // Arquivo não existe, será recriado. - Rewrite (v_Aguarde); - - Append(v_Aguarde); - Writeln(v_Aguarde,'Apenas um pseudo-cookie para o Cacic2 esperar o término de Ini_Cols'); - Append(v_Aguarde); - - Matar(g_oCacic.getCacicPath+'temp\','*.dat'); - Try - // Caso exista o Gerente de Coletas será verificada a versão... - // Devido a problemas na rotina de FTP na versão 2.0.1.2, - // que impossibilitava atualização de versões de todos os componentes, exceto INI_COLS - If (FileExists(g_oCacic.getCacicPath + 'modulos\ger_cols.exe')) Then + if ParamCount > 0 then + Begin + strAux := ''; + For intAux := 1 to ParamCount do + Begin + if LowerCase(Copy(ParamStr(intAux),1,11)) = '/cacicpath=' then + begin + strAux := Trim(Copy(ParamStr(intAux),12,Length((ParamStr(intAux))))); + log_DEBUG('Parâmetro /CacicPath recebido com valor="'+strAux+'"'); + end; + end; + + if (strAux <> '') then + Begin + g_oCacic.setCacicPath(strAux); + v_Debugs := false; + if DirectoryExists(g_oCacic.getCacicPath + 'Temp\Debugs') then Begin - v_versao := trim(GetVersionInfo(g_oCacic.getCacicPath + 'modulos\ger_cols.exe')); - if (v_versao = '0.0.0.0') then // Provavelmente arquivo corrompido ou versão muito antiga - Begin - Matar(g_oCacic.getCacicPath+'modulos\','ger_cols.exe'); - Sleep(5000); // Pausa 5 segundos para total exclusão de GER_COLS - CipherOpen(g_oCacic.getDatFileName); - v_te_senha_login_serv_updates := GetValorDatMemoria('Configs.te_senha_login_serv_updates'); - - FTP(GetValorDatMemoria('Configs.te_serv_updates'), - GetValorDatMemoria('Configs.nu_porta_serv_updates'), - GetValorDatMemoria('Configs.nm_usuario_login_serv_updates'), - v_te_senha_login_serv_updates, - GetValorDatMemoria('Configs.te_path_serv_updates'), - 'ger_cols.exe', - g_oCacic.getCacicPath + 'modulos'); - - // Pausa 5 segundos para total gravação de GER_COLS - Sleep(5000); + if (FormatDateTime('ddmmyyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs')) = FormatDateTime('ddmmyyyy', date)) then + Begin + v_Debugs := true; + log_DEBUG('Pasta "' + g_oCacic.getCacicPath + 'Temp\Debugs" com data '+FormatDateTime('dd-mm-yyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs'))+' encontrada. DEBUG ativado.'); + End; + End; + // A existência e bloqueio do arquivo abaixo evitará que Cacic2.exe chame o Ger_Cols quando a coleta ainda estiver sendo efetuada + AssignFile(v_Aguarde,g_oCacic.getCacicPath + 'temp\aguarde_INI.txt'); {Associa o arquivo a uma variável do tipo TextFile} + {$IOChecks off} + Reset(v_Aguarde); {Abre o arquivo texto} + {$IOChecks on} + if (IOResult <> 0) then // Arquivo não existe, será recriado. + Rewrite (v_Aguarde); + + Append(v_Aguarde); + Writeln(v_Aguarde,'Apenas um pseudo-cookie para o Cacic2 esperar o término de Ini_Cols'); + Append(v_Aguarde); + + Matar(g_oCacic.getCacicPath+'temp\','*.dat'); + Try + // Caso exista o Gerente de Coletas será verificada a versão... + // Devido a problemas na rotina de FTP na versão 2.0.1.2, + // que impossibilitava atualização de versões de todos os componentes, exceto INI_COLS + If (FileExists(g_oCacic.getCacicPath + 'modulos\ger_cols.exe')) Then + Begin + v_versao := trim(GetVersionInfo(g_oCacic.getCacicPath + 'modulos\ger_cols.exe')); + if (v_versao = '0.0.0.0') then // Provavelmente arquivo corrompido ou versão muito antiga + Begin + Matar(g_oCacic.getCacicPath+'modulos\','ger_cols.exe'); + Sleep(5000); // Pausa 5 segundos para total exclusão de GER_COLS + CipherOpen(g_oCacic.getCacicPath + g_oCacic.getDatFileName); + v_te_senha_login_serv_updates := GetValorDatMemoria('Configs.te_senha_login_serv_updates'); + + FTP(GetValorDatMemoria('Configs.te_serv_updates'), + GetValorDatMemoria('Configs.nu_porta_serv_updates'), + GetValorDatMemoria('Configs.nm_usuario_login_serv_updates'), + v_te_senha_login_serv_updates, + GetValorDatMemoria('Configs.te_path_serv_updates'), + 'ger_cols.exe', + g_oCacic.getCacicPath + 'modulos'); + + // Pausa 5 segundos para total gravação de GER_COLS + Sleep(5000); + + End; + End; + + // Procuro pelo parâmetro p_ModulosOpcoes que deverá ter sido passado pelo Gerente de Coletas + // Contendo a formação: coletor1,wait#coletor2,nowait#coletorN,nowait# + // Observações: + // 1) Os valores "wait/nowait" determinam se o Inicializador de Coletas estará sujeito à tolerância de tempo para as coletas. + // 2) No caso de Coletor de Patrimônio, este depende de digitação e deverá trazer a opção "wait"; + // 3) Ainda no caso de Coletor de Patrimônio, quando este for invocado através do menu, o Gerente de Coletas enviará a opção "user", ficando o parâmetro p_ModulosOpcoes = "col_patr,wait,user" + For intAux := 1 to ParamCount do + Begin + if LowerCase(Copy(ParamStr(intAux),1,17)) = '/p_modulosopcoes=' then + v_ModulosOpcoes := Trim(Copy(ParamStr(intAux),18,Length((ParamStr(intAux))))); End; - End; - // Procuro pelo parâmetro p_ModulosOpcoes que deverá ter sido passado pelo Gerente de Coletas - // Contendo a formação: coletor1,wait#coletor2,nowait#coletorN,nowait# - // Observações: - // 1) Os valores "wait/nowait" determinam se o Inicializador de Coletas estará sujeito à tolerância de tempo para as coletas. - // 2) No caso de Coletor de Patrimônio, este depende de digitação e deverá trazer a opção "wait"; - // 3) Ainda no caso de Coletor de Patrimônio, quando este for invocado através do menu, o Gerente de Coletas enviará a opção "user", ficando o parâmetro p_ModulosOpcoes = "col_patr,wait,user" - For intAux := 1 to ParamCount do - Begin - if LowerCase(Copy(ParamStr(intAux),1,17)) = '/p_modulosopcoes=' then - v_ModulosOpcoes := Trim(Copy(ParamStr(intAux),18,Length((ParamStr(intAux))))); - End; - - log_DEBUG('Parâmetro p_ModulosOpcoes recebido: '+v_ModulosOpcoes); - v_tstrModulosOpcoes := g_oCacic.explode(v_ModulosOpcoes,'#'); - - // Tempo de tolerância para as coletas - v_Tolerancia := 5; // (minutos) - - For intAux := 0 to v_tstrModulosOpcoes.Count -1 do - Begin - v_tstrModuloOpcao := g_oCacic.explode(v_tstrModulosOpcoes[intAux],','); - v_Aux := v_tstrModuloOpcao[0]+'.exe /p_Option='+v_tstrModuloOpcao[2]; - log_DEBUG('Chamando "' + v_tstrModuloOpcao[0]+'.exe " /p_Option='+v_tstrModuloOpcao[2]); - - g_oCacic.createSampleProcess( g_oCacic.getCacicPath + '\modulos\' + v_aux, CACIC_PROCESS_WAIT ); - - End; - except - end; + log_DEBUG('Parâmetro p_ModulosOpcoes recebido: '+v_ModulosOpcoes); + v_tstrModulosOpcoes := g_oCacic.explode(v_ModulosOpcoes,'#'); + + // Tempo de tolerância para as coletas + v_Tolerancia := 5; // (minutos) + + For intAux := 0 to v_tstrModulosOpcoes.Count -1 do + Begin + v_tstrModuloOpcao := g_oCacic.explode(v_tstrModulosOpcoes[intAux],','); + strAux := v_tstrModuloOpcao[0]+'.exe /CacicPath='+g_oCacic.getCacicPath+' /p_Option='+v_tstrModuloOpcao[2]; + log_DEBUG('Chamando "' + v_tstrModuloOpcao[0]+'.exe " /p_Option='+v_tstrModuloOpcao[2]); + + g_oCacic.createSampleProcess( g_oCacic.getCacicPath + '\modulos\' + strAux, CACIC_PROCESS_WAIT ); + End; + except + end; + End; End; g_oCacic.Free(); end. diff --git a/main.pas b/main.pas index 08879b3..76f8f98 100755 --- a/main.pas +++ b/main.pas @@ -19,45 +19,53 @@ unit main; interface -uses Windows, - Messages, - Forms, - Menus, - Classes, - SysUtils, - Controls, - StdCtrls, - ExtCtrls, - ShellAPI, - registry, - dialogs, - PJVersionInfo, - ComCtrls, - IdBaseComponent, - IdComponent, - Buttons, - CACIC_Library, - ImgList, - Graphics; - //IdTCPServer; - //IdFTPServer; - -const WM_MYMESSAGE = WM_USER+100; +uses + Windows, + Messages, + Forms, + Menus, + Classes, + SysUtils, + Controls, + StdCtrls, + ExtCtrls, + ShellAPI, + registry, + dialogs, + PJVersionInfo, + ComCtrls, + IdBaseComponent, + IdComponent, + Buttons, + CACIC_Library, + ImgList, + Graphics; + //IdTCPServer; + //IdFTPServer; + +const + WM_MYMESSAGE = WM_USER+100; // Declaração das variáveis globais. -var p_Shell_Command, - p_Shell_Path, - v_versao, - v_DataCacic2DAT, - v_Tamanho_Arquivo, - strConfigsPatrimonio : string; - BatchFile : TStringList; - v_tstrCipherOpened : TStrings; - boolCrypt, - boolDebugs : Boolean; +var + p_Shell_Command, + p_Shell_Path, + v_versao, + v_DataCacic2DAT, + v_Tamanho_Arquivo, + strConfigsPatrimonio : string; + +var + BatchFile : TStringList; + +var + v_tstrCipherOpened : TStrings; + +var + boolDebugs : Boolean; var - g_oCacic: TCACIC; + g_oCacic: TCACIC; type TFormularioGeral = class(TForm) @@ -218,7 +226,6 @@ type procedure WMMENUSELECT(var msg: TWMMENUSELECT); message WM_MENUSELECT; public Function Implode(p_Array : TStrings ; p_Separador : String) : String; - function HomeDrive : string; function GetFolderDate(Folder: string): TDateTime; Function CipherClose : String; Function CipherOpen : TStrings; @@ -516,14 +523,6 @@ Begin End; - -function TFormularioGeral.HomeDrive : string; -var -WinDir : array [0..144] of char; -begin -GetWindowsDirectory (WinDir, 144); -Result := StrPas (WinDir); -end; function TFormularioGeral.GetFolderDate(Folder: string): TDateTime; var Rec: TSearchRec; @@ -565,33 +564,33 @@ var v_DatFile : TextFile; v_strCipherClosed : string; begin - log_DEBUG('Fechando '+g_oCacic.getDatFileName); + log_DEBUG('Fechando '+g_oCacic.getCacicPath + g_oCacic.getDatFileName); if boolDebugs then for intAux := 0 to (v_tstrCipherOpened.Count-1) do log_DEBUG('Posição ['+inttostr(intAux)+']='+v_tstrCipherOpened[intAux]); try - FileSetAttr (g_oCacic.getDatFileName,0); // Retira os atributos do arquivo para evitar o erro FILE ACCESS DENIED em máquinas 2000 + FileSetAttr (g_oCacic.getCacicPath + g_oCacic.getDatFileName,0); // Retira os atributos do arquivo para evitar o erro FILE ACCESS DENIED em máquinas 2000 - log_DEBUG('Localizando arquivo: '+g_oCacic.getDatFileName); - AssignFile(v_DatFile,g_oCacic.getDatFileName); {Associa o arquivo a uma variável do tipo TextFile} + log_DEBUG('Localizando arquivo: '+g_oCacic.getCacicPath + g_oCacic.getDatFileName); + AssignFile(v_DatFile,g_oCacic.getCacicPath + g_oCacic.getDatFileName); {Associa o arquivo a uma variável do tipo TextFile} {$IOChecks off} - log_DEBUG('Abrindo arquivo: '+g_oCacic.getDatFileName); + log_DEBUG('Abrindo arquivo: '+g_oCacic.getCacicPath + g_oCacic.getDatFileName); ReWrite(v_DatFile); {Abre o arquivo texto} {$IOChecks on} - log_DEBUG('Append(2) no arquivo: '+g_oCacic.getDatFileName); + log_DEBUG('Append(2) no arquivo: '+g_oCacic.getCacicPath + g_oCacic.getDatFileName); Append(v_DatFile); log_DEBUG('Criando vetor para criptografia.'); v_strCipherOpenImploded := Implode(v_tstrCipherOpened,g_oCacic.getSeparatorKey); - log_DEBUG('Salvando a string "'+v_strCipherOpenImploded+'" em '+g_oCacic.getDatFileName); + log_DEBUG('Salvando a string "'+v_strCipherOpenImploded+'" em '+g_oCacic.getCacicPath + g_oCacic.getDatFileName); v_strCipherClosed := g_oCacic.enCrypt(v_strCipherOpenImploded); Writeln(v_DatFile,v_strCipherClosed); {Grava a string Texto no arquivo texto} CloseFile(v_DatFile); except - log_diario('ERRO NA GRAVAÇÃO DO ARQUIVO DE CONFIGURAÇÕES.('+g_oCacic.getDatFileName+')'); + log_diario('ERRO NA GRAVAÇÃO DO ARQUIVO DE CONFIGURAÇÕES.('+ g_oCacic.getCacicPath + g_oCacic.getDatFileName+')'); end; - log_DEBUG(g_oCacic.getDatFileName+' fechado com sucesso!'); + log_DEBUG(g_oCacic.getCacicPath + g_oCacic.getDatFileName+' fechado com sucesso!'); end; function TFormularioGeral.Get_File_Size(sFileToExamine: string; bInKBytes: Boolean): string; @@ -619,22 +618,22 @@ var v_DatFile : TextFile; v_strCipherClosed : string; begin - if (v_DataCacic2DAT = '') or (v_DataCacic2DAT <> FormatDateTime('ddmmyyyyhhnnsszzz', GetFolderDate(g_oCacic.getCacicPath + 'cacic2.dat'))) then + if (v_DataCacic2DAT = '') or (v_DataCacic2DAT <> FormatDateTime('ddmmyyyyhhnnsszzz', GetFolderDate(g_oCacic.getCacicPath + g_oCacic.getDatFileName))) then Begin - v_DataCacic2DAT := FormatDateTime('ddmmyyyyhhnnsszzz', GetFolderDate(g_oCacic.getCacicPath + 'cacic2.dat')); - log_DEBUG('Abrindo '+g_oCacic.getDatFileName +' - DateTime Cacic2.dat=> '+v_DataCacic2DAT); + v_DataCacic2DAT := FormatDateTime('ddmmyyyyhhnnsszzz', GetFolderDate(g_oCacic.getCacicPath + g_oCacic.getDatFileName)); + log_DEBUG('Abrindo '+g_oCacic.getCacicPath + g_oCacic.getDatFileName +' - DateTime '+g_oCacic.getCacicPath + g_oCacic.getDatFileName+' => '+v_DataCacic2DAT); v_strCipherOpened := ''; - v_Tamanho_Arquivo := Get_File_Size(g_oCacic.getDatFileName,true); + v_Tamanho_Arquivo := Get_File_Size(g_oCacic.getCacicPath + g_oCacic.getDatFileName,true); if (v_Tamanho_Arquivo = '0') or - (v_Tamanho_Arquivo = '-1') then FormularioGeral.Matar(g_oCacic.getCacicPath,'cacic2.dat'); + (v_Tamanho_Arquivo = '-1') then FormularioGeral.Matar(g_oCacic.getCacicPath,g_oCacic.getDatFileName); - if FileExists(g_oCacic.getDatFileName) then + if FileExists(g_oCacic.getCacicPath + g_oCacic.getDatFileName) then begin - log_DEBUG(g_oCacic.getDatFileName+' já existe!'); - AssignFile(v_DatFile,g_oCacic.getDatFileName); - log_DEBUG('Abrindo '+g_oCacic.getDatFileName); + log_DEBUG(g_oCacic.getCacicPath + g_oCacic.getDatFileName+' já existe!'); + AssignFile(v_DatFile,g_oCacic.getCacicPath + g_oCacic.getDatFileName); + log_DEBUG('Abrindo '+g_oCacic.getCacicPath + g_oCacic.getDatFileName); {$IOChecks off} Reset(v_DatFile); @@ -643,19 +642,19 @@ begin log_DEBUG('Verificação de Existência.'); if (IOResult <> 0)then // Arquivo não existe, será recriado. begin - log_DEBUG('Recriando "'+g_oCacic.getDatFileName+'"'); + log_DEBUG('Recriando "'+g_oCacic.getCacicPath + g_oCacic.getDatFileName+'"'); Rewrite (v_DatFile); log_DEBUG('Inserindo Primeira Linha.'); Append(v_DatFile); end; - log_DEBUG('Lendo '+g_oCacic.getDatFileName); + log_DEBUG('Lendo '+g_oCacic.getCacicPath + g_oCacic.getDatFileName); Readln(v_DatFile,v_strCipherClosed); log_DEBUG('Povoando Variável'); while not EOF(v_DatFile) do Readln(v_DatFile,v_strCipherClosed); - log_DEBUG('Fechando '+g_oCacic.getDatFileName); + log_DEBUG('Fechando '+g_oCacic.getCacicPath + g_oCacic.getDatFileName); CloseFile(v_DatFile); log_DEBUG('Chamando Criptografia de conteúdo'); v_strCipherOpened:= g_oCacic.deCrypt(v_strCipherClosed); @@ -666,7 +665,7 @@ begin Begin v_tstrCipherOpened := explode('Configs.ID_SO'+g_oCacic.getSeparatorKey+ g_oCacic.getWindowsStrId() +g_oCacic.getSeparatorKey+ 'Configs.Endereco_WS'+g_oCacic.getSeparatorKey+'/cacic2/ws/',g_oCacic.getSeparatorKey); - log_DEBUG(g_oCacic.getDatFileName+' Inexistente. Criado o DAT em memória.'); + log_DEBUG(g_oCacic.getCacicPath + g_oCacic.getDatFileName+' Inexistente. Criado o DAT em memória.'); End; Result := v_tstrCipherOpened; @@ -675,7 +674,7 @@ begin Result.Add(''); End - else log_DEBUG('Cacic2.dat ainda não alterado! Não foi necessário reabrí-lo.'); + else log_DEBUG(g_oCacic.getCacicPath + g_oCacic.getDatFileName + ' ainda não alterado! Não foi necessário reabrí-lo.'); end; Procedure TFormularioGeral.SetValorDatMemoria(p_Chave : string; p_Valor : String; p_tstrCipherOpened : TStrings); @@ -818,8 +817,8 @@ Begin InicializaTray; log_diario('Acionando recuperador de Módulo Gerente de Coletas.'); - log_DEBUG('Recuperador de Módulo Gerente de Coletas: '+HomeDrive + '\chksis.exe'); - WinExec(PChar(HomeDrive + '\chksis.exe'),SW_HIDE); + log_DEBUG('Recuperador de Módulo Gerente de Coletas: '+g_oCacic.getWinDir + 'chksis.exe'); + g_oCacic.createSampleProcess(g_oCacic.getWinDir + 'chksis.exe',false); sleep(30000); // 30 segundos de espera para download do ger_cols.exe v_Tamanho_Arquivo := Get_File_Size(g_oCacic.getCacicPath + 'modulos\ger_cols.exe',true); @@ -871,7 +870,7 @@ Begin // Verifico se o endereço do servidor do cacic foi configurado. if (GetValorDatMemoria('Configs.EnderecoServidor',v_tstrCipherOpened)='') then Begin - strAux := getValorChaveRegIni('Cacic2','ip_serv_cacic',HomeDrive + '\chksis.ini'); + strAux := getValorChaveRegIni('Cacic2','ip_serv_cacic',g_oCacic.getWinDir + 'chksis.ini'); if (strAux='') then begin @@ -1048,8 +1047,6 @@ End; procedure TFormularioGeral.FormCreate(Sender: TObject); var strAux, v_ip_serv_cacic, - v_cacic_dir, - v_windir, strFraseVersao : string; intAux : integer; v_Aguarde : TextFile; @@ -1058,33 +1055,15 @@ begin // Não mostrar o formulário... Application.ShowMainForm:=false; g_oCacic := TCACIC.Create; + + g_oCacic.setBoolCipher(true); + //g_oCacic.showTrayIcon(false); - boolCrypt := true; + Try - // De acordo com a versão do OS, determino o ShellCommand para chamadas externas. - if (g_oCacic.isWindowsNTPlataform()) then //Se NT/2K/XP... then - Begin - p_Shell_Path := HomeDrive + '\system32\'; //NT/2K/XP - p_Shell_Command := 'cmd.exe'; //NT/2K/XP - strAux := HomeDrive + '\'; //Ex.: c:\windows\ - End - else - Begin - v_windir := GetEnvironmentVariable('windir'); - if (trim(v_windir) <> '') then v_windir := v_windir + '\'; - p_Shell_Path := v_windir; - p_Shell_Command := 'command.com'; - strAux := GetEnvironmentVariable('windir') + '\'; //Ex.: c:\windows\ - End; - v_SystemDrive := explode(strAux,'\'); - v_cacic_dir := v_SystemDrive[0] + '\' + getValorChaveRegIni('Cacic2','cacic_dir',strAux + 'chksis.ini') + '\'; - // Caminho do aplicativo - if (v_cacic_dir <> '') then - g_oCacic.setCacicPath(v_cacic_dir) - else - g_oCacic.setCacicPath(ExtractFilePath(Application.Exename)) ; + g_oCacic.setCacicPath(getValorChaveRegIni('Cacic2','cacic_dir',g_oCacic.getWinDir + 'chksis.ini')) ; if not DirectoryExists(g_oCacic.getCacicPath + 'Temp') then begin @@ -1281,7 +1260,7 @@ begin begin DateTimeToString(strDataArqLocal, 'yyyymmdd', FileDateToDateTime(Fileage(g_oCacic.getCacicPath + 'cacic2.log'))); DateTimeToString(strDataAtual , 'yyyymmdd', Date); - if (strDataAtual <> strDataArqLocal) then // Se o arquivo INI não é da data atual... + if (strDataAtual <> strDataArqLocal) then // Se o arquivo LOG não é da data atual... begin Rewrite (HistoricoLog); //Cria/Recria o arquivo Append(HistoricoLog); @@ -1291,8 +1270,8 @@ begin Writeln(HistoricoLog,FormatDateTime('dd/mm hh:nn:ss : ', Now)+ '[Agente Principal] '+strMsg); {Grava a string Texto no arquivo texto} CloseFile(HistoricoLog); {Fecha o arquivo texto} end - else CloseFile(HistoricoLog);; - + else + CloseFile(HistoricoLog); except log_diario('PROBLEMAS NA CRIAÇÃO DO ARQUIVO LOG'); end; @@ -1307,7 +1286,7 @@ Begin Except log_diario('PROBLEMAS NA FINALIZAÇÃO'); End; - g_oCacic.Free(); + g_oCacic.Free; FreeMemory(0); Application.Terminate; End; @@ -1332,7 +1311,7 @@ begin CipherClose; log_diario('Invocando Gerente de Coletas com ação: "'+p_acao+'"'); Timer_Nu_Exec_Apos.Enabled := False; - WinExec(PChar(g_oCacic.getCacicPath + 'modulos\GER_COLS.EXE /'+p_acao+' /p_CipherKey='+g_oCacic.getCipherKey),SW_HIDE); + g_oCacic.createSampleProcess(g_oCacic.getCacicPath + 'modulos\GER_COLS.EXE /'+p_acao+' /CacicPath='+g_oCacic.getCacicPath,false); End else log_diario('Não foi possível invocar o Gerente de Coletas!'); @@ -2185,15 +2164,13 @@ begin if boolServerON then // Ordeno ao SrCACICsrv que auto-finalize Begin Log_Diario('Desativando Suporte Remoto Seguro.'); - WinExec(PChar(g_oCacic.getCacicPath + 'modulos\srcacicsrv.exe -kill'),SW_HIDE); + g_oCacic.createSampleProcess(g_oCacic.getCacicPath + 'modulos\srcacicsrv.exe -kill',false); boolServerON := false; End else Begin log_DEBUG('Invocando "'+g_oCacic.getCacicPath + 'modulos\srcacicsrv.exe"...'); Log_Diario('Ativando Suporte Remoto Seguro.'); - boolAux := boolCrypt; - boolCrypt := true; // Alguns cuidados necessários ao tráfego e recepção de valores pelo Gerente WEB // Some cares about send and receive at Gerente WEB @@ -2236,15 +2213,13 @@ begin CloseFile(fileAguarde); Finally End; + g_oCacic.createSampleProcess(g_oCacic.getCacicPath + 'modulos\srcacicsrv.exe -start [' + g_oCacic.enCrypt(FormularioGeral.getValorDatMemoria('Configs.EnderecoServidor', v_tstrCipherOpened)) + ']' + + '[' + g_oCacic.enCrypt(FormularioGeral.getValorDatMemoria('Configs.Endereco_WS' , v_tstrCipherOpened)) + ']' + + '[' + strTeSO + ']' + + '[' + strTeNodeAddress + ']' + + '[' + strPalavraChave + ']' + + '[' + g_oCacic.getCacicPath + 'Temp\' + ']',false); - WinExec(PChar(g_oCacic.getCacicPath + 'modulos\srcacicsrv.exe -start [' + g_oCacic.enCrypt(FormularioGeral.getValorDatMemoria('Configs.EnderecoServidor', v_tstrCipherOpened)) + ']' + - '[' + g_oCacic.enCrypt(FormularioGeral.getValorDatMemoria('Configs.Endereco_WS' , v_tstrCipherOpened)) + ']' + - '[' + strTeSO + ']' + - '[' + strTeNodeAddress + ']' + - '[' + strPalavraChave + ']' + - '[' + g_oCacic.getCacicPath + 'Temp\aguarde_srCACIC.txt' + ']'),SW_NORMAL); - - boolCrypt := boolAux; BoolServerON := true; End; diff --git a/mapa/main_mapa.pas b/mapa/main_mapa.pas index daf86e7..2a672dd 100755 --- a/mapa/main_mapa.pas +++ b/mapa/main_mapa.pas @@ -1467,6 +1467,8 @@ var intAux : integer; Request_mapa : TStringList; begin g_oCacic := TCACIC.Create(); + + g_oCacic.setBoolCipher(true); frmMapaCacic.lbVersao.Caption := 'Versão: ' + frmMapaCacic.GetVersionInfo(ParamStr(0)); log_DEBUG('Versão do MapaCacic: '+frmMapaCacic.lbVersao.Caption); if (g_oCacic.isWindowsNTPlataform()) and (not g_oCacic.isWindowsAdmin()) then -- libgit2 0.21.2