From 4c2a85c754b2216e0640f11337510c142ed8255f Mon Sep 17 00:00:00 2001 From: anderson.peterle@previdencia.gov.br Date: Fri, 3 Apr 2009 16:55:47 +0000 Subject: [PATCH] Adequacoes ao uso de library unica, pequenas correcoes e faxina de codigo. --- cacicservice/CACICsvc.dpr | 4 ++-- cacicservice/CACICsvcMain.pas | 77 +++++++++++++++++++++++------------------------------------------------------ chkcacic/chkcacic.dpr | 8 ++++---- chkcacic/main.pas | 514 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- chksis/chksis.dpr | 285 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ col_anvi/col_anvi.dpr | 241 +++++++++++++++++++++++++++++++++++++++++++------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ col_comp/col_comp.dpr | 235 ++++++++++++++++++++++++++++++++++++------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- col_hard/col_hard.dpr | 389 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 8 files changed, 420 insertions(+), 1333 deletions(-) diff --git a/cacicservice/CACICsvc.dpr b/cacicservice/CACICsvc.dpr index 7849787..d1abc1e 100755 --- a/cacicservice/CACICsvc.dpr +++ b/cacicservice/CACICsvc.dpr @@ -18,8 +18,8 @@ program CACICsvc; uses SvcMgr, - CACICsvcMain in 'CACICsvcMain.pas' {CACICservice: TService}; - + CACICsvcMain in 'CACICsvcMain.pas' {CACICservice: TService}, + CACIC_Library in '..\CACIC_Library.pas'; {$R *.RES} begin diff --git a/cacicservice/CACICsvcMain.pas b/cacicservice/CACICsvcMain.pas index 00c69ae..7e4c21e 100755 --- a/cacicservice/CACICsvcMain.pas +++ b/cacicservice/CACICsvcMain.pas @@ -18,17 +18,19 @@ unit CACICsvcMain; interface -uses Windows, - Messages, - SysUtils, - Classes, - SvcMgr, - strUtils, - ExtCtrls; - -var strHomeDrive, - strCacicDir : String; - boolStarted : boolean; +uses + Windows, + Messages, + SysUtils, + Classes, + SvcMgr, + strUtils, + ExtCtrls, + CACIC_Library; + +var + boolStarted : boolean; + g_oCacic : TCACIC; type TCACICservice = class(TService) @@ -41,9 +43,7 @@ type private { Internal Start & Stop methods } - function HomeDrive : string; function GetValorChaveRegIni(p_Secao, p_Chave, p_File : String): String; - function GetAppPath: String; procedure doSaveLog(Msg : String); Procedure WMEndSession(var Msg : TWMEndSession) ; message WM_ENDSESSION; procedure ExecutaCACIC; @@ -66,6 +66,7 @@ begin inherited; Application.Free; end; + // Funções Auxiliares function TCACICservice.GetValorChaveRegIni(p_Secao, p_Chave, p_File : String): String; //Para buscar do Arquivo INI... @@ -105,40 +106,11 @@ var end; end; -function TCACICservice.GetAppPath: String; -Var - Test : String; - Res : Longint; - CurSize : Longint; -begin - CurSize := 1024; - SetLength(Test, CurSize); - Res := GetModuleFilename(GetModuleHandle(nil), PChar(test), CurSize); - If (res > curSize) then - begin - CurSize := res + 10; - SetLength(Test, CurSize); - Res := GetModuleFilename(GetModuleHandle(nil), PChar(test), CurSize); - end; - Setlength(Test, Res); - test := ExtractFileDir(Test); - if (test[Length(test)] = '\') or (test[Length(test)]='/') then - SetLength(Test, Length(test) - 1); - Result := test; -end; - -function TCACICservice.HomeDrive : string; -var WinDir : array [0..144] of char; -begin - GetWindowsDirectory (WinDir, 144); - Result := StrPas (WinDir); -end; - procedure TCACICservice.doSaveLog(Msg : String); var fLog: textfile; begin - AssignFile(fLog, HomeDrive + '\CACICsvc.log'); - if FileExists(HomeDrive + '\CACICsvc.log') then + AssignFile(fLog, g_oCacic.Windows.getWinDir + 'CACICsvc.log'); + if FileExists(g_oCacic.Windows.getWinDir + 'CACICsvc.log') then Append(fLog) else Rewrite(fLog); @@ -172,6 +144,7 @@ end; procedure TCACICservice.ServiceStart(Sender: TService; var Started: Boolean); begin + g_oCacic := TCACIC.Create; Started := true; @@ -182,36 +155,32 @@ begin While not Terminated do Sleep(250); - - end; procedure TCACICservice.ExecutaCACIC; Begin + g_oCacic.setCacicPath(g_oCacic.getHomeDrive + GetValorChaveRegIni('Cacic2', 'cacic_dir', g_oCacic.getWinDir + 'chksis.ini') + '\'); - strHomeDrive := MidStr(HomeDrive,1,3); //x:\ - strCacicDir := strHomeDrive + GetValorChaveRegIni('Cacic2', 'cacic_dir', GetAppPath + '\chksis.ini'); - - DeleteFile(strCacicDir + '\aguarde_CACIC.txt'); + DeleteFile(g_oCacic.getCacicPath + 'aguarde_CACIC.txt'); Sleep(3000); // Se o arquivo indicador de execução não existir... - if not (FileExists(strCacicDir + '\aguarde_CACIC.txt')) then + if not (FileExists(g_oCacic.getCacicPath + 'aguarde_CACIC.txt')) then Begin // Executo o CHKsis, verificando a estrutura do sistema Try - WinEXEC(PChar(HomeDrive + '\chksis.exe'),sw_HIDE); + WinEXEC(PChar(g_oCacic.getWinDir + 'chksis.exe'),sw_HIDE); Except End; - While not (FileExists(strCacicDir + '\cacic2.exe')) do + While not (FileExists(g_oCacic.getCacicPath + 'cacic2.exe')) do Sleep(5000); // Espero 5 segundos... End; // Executo o Agente Principal do CACIC Try - WinEXEC(PChar(strCacicDir + '\cacic2.exe'),sw_hide); + WinEXEC(PChar(g_oCacic.getCacicPath + 'cacic2.exe'),sw_hide); Except End; End; diff --git a/chkcacic/chkcacic.dpr b/chkcacic/chkcacic.dpr index 04be977..23277bf 100755 --- a/chkcacic/chkcacic.dpr +++ b/chkcacic/chkcacic.dpr @@ -27,18 +27,18 @@ const CACIC_APP_NAME = 'chkcacic'; var - oCacic : TCACIC; + g_oCacic : TCACIC; begin - oCacic := TCACIC.Create(); + g_oCacic := TCACIC.Create(); - if( not oCacic.isAppRunning( CACIC_APP_NAME ) ) + if( not g_oCacic.isAppRunning( CACIC_APP_NAME ) ) then begin Application.Initialize; Application.CreateForm(TForm1, Form1); Application.Run; end; - oCacic.Free(); + g_oCacic.Free(); end. diff --git a/chkcacic/main.pas b/chkcacic/main.pas index bf77fda..a99789d 100644 --- a/chkcacic/main.pas +++ b/chkcacic/main.pas @@ -56,71 +56,56 @@ unit main; interface -uses Windows, - strUtils, - SysUtils, - Classes, - Forms, - Registry, - Inifiles, - idFTPCommon, - XML, - LibXmlParser, - IdHTTP, - PJVersionInfo, - Controls, - StdCtrls, - IdBaseComponent, - IdComponent, - IdTCPConnection, - IdTCPClient, - variants, - DCPcrypt2, - DCPrijndael, - DCPbase64, - NTFileSecurity, - IdFTP, - Tlhelp32, - ExtCtrls, - CACIC_Library, - WinSvc, - dialogs; - -var v_ip_serv_cacic, - v_cacic_dir, - v_te_instala_frase_sucesso, - v_te_instala_frase_insucesso, - v_te_instala_informacoes_extras, - v_exibe_informacoes, - v_versao_local, - v_versao_remota, - v_CipherKey, - v_SeparatorKey, - v_IV, - v_strCipherClosed, - v_strCipherOpened, - v_DatFileName, - v_retorno, - v_versao_REM, - v_versao_LOC, - v_te_so : String; - - v_Debugs : boolean; - -var v_tstrCipherOpened : TStrings; +uses + Windows, + strUtils, + SysUtils, + Classes, + Forms, + Registry, + Inifiles, + idFTPCommon, + XML, + LibXmlParser, + idHTTP, + PJVersionInfo, + Controls, + StdCtrls, + IdBaseComponent, + IdComponent, + IdTCPConnection, + IdTCPClient, + variants, + NTFileSecurity, + IdFTP, + Tlhelp32, + ExtCtrls, + CACIC_Library, + WinSvc, + dialogs; var - g_oCacic: TCACIC; /// Biblioteca CACIC_Library + v_ip_serv_cacic, + v_te_instala_frase_sucesso, + v_te_instala_frase_insucesso, + v_te_instala_informacoes_extras, + v_exibe_informacoes, + v_versao_local, + v_versao_remota, + v_strCipherClosed, + v_strCipherOpened, + v_retorno, + v_versao_REM, + v_versao_LOC : String; -// Constantes a serem usadas pela função IsAdmin... -const constSECURITY_NT_AUTHORITY: TSIDIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 5)); - constSECURITY_BUILTIN_DOMAIN_RID = $00000020; - constDOMAIN_ALIAS_RID_ADMINS = $00000220; +var + v_Debugs : boolean; -// Some constants that are dependant on the cipher being used -// Assuming MCRYPT_RIJNDAEL_128 (i.e., 128bit blocksize, 256bit keysize) -const KeySize = 32; // 32 bytes = 256 bits - BlockSize = 16; // 16 bytes = 128 bits +var + v_tstrCipherOpened : TStrings; + +var + g_oCacic: TCACIC; /// Biblioteca CACIC_Library Procedure chkcacic; procedure ComunicaInsucesso(strIndicador : String); //2.2.0.32 @@ -135,7 +120,6 @@ procedure Matar(v_dir,v_files: string); // 2.2.0.16 Procedure MostraFormConfigura; Function ChecaVersoesAgentes(p_strNomeAgente : String) : integer; // 2.2.0.16 -Function Explode(Texto, Separador : String) : TStrings; Function FindWindowByTitle(WindowTitle: string): Hwnd; Function FTP(p_Host : String; p_Port : String; p_Username : String; p_Password : String; p_PathServer : String; p_File : String; p_Dest : String) : Boolean; function GetFolderDate(Folder: string): TDateTime; @@ -144,7 +128,6 @@ Function GetRootKey(strRootKey: String): HKEY; Function GetValorChaveRegEdit(Chave: String): Variant; Function GetValorChaveRegIni(p_Secao, p_Chave, p_File : String): String; Function GetVersionInfo(p_File: string):string; -Function HomeDrive : string; Function KillTask(ExeFileName: string): Integer; Function ListFileDir(Path: string):string; function Posso_Rodar_CACIC : boolean; @@ -167,8 +150,7 @@ type var Form1: TForm1; - Dir, ENDERECO_SERV_CACIC, - v_home_drive : string; + ENDERECO_SERV_CACIC : string; implementation uses FormConfig; @@ -315,52 +297,12 @@ begin StrDispose(temp); end; -function IsAdmin: Boolean; -var hAccessToken: THandle; - ptgGroups: PTokenGroups; - dwInfoBufferSize: DWORD; - psidAdministrators: PSID; - x: Integer; - bSuccess: BOOL; -begin - Result := False; - bSuccess := OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True, hAccessToken); - if not bSuccess then - begin - if GetLastError = ERROR_NO_TOKEN then - bSuccess := OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, hAccessToken); - end; - if bSuccess then - begin - GetMem(ptgGroups, 1024); - bSuccess := GetTokenInformation(hAccessToken, TokenGroups, ptgGroups, 1024, dwInfoBufferSize); - CloseHandle(hAccessToken); - if bSuccess then - begin - AllocateAndInitializeSid(constSECURITY_NT_AUTHORITY, 2, - constSECURITY_BUILTIN_DOMAIN_RID, - constDOMAIN_ALIAS_RID_ADMINS, - 0, 0, 0, 0, 0, 0, psidAdministrators); - {$R-} - for x := 0 to ptgGroups.GroupCount - 1 do - if EqualSid(psidAdministrators, ptgGroups.Groups[x].Sid) then - begin - Result := True; - Break; - end; - {$R+} - FreeSid(psidAdministrators); - end; - FreeMem(ptgGroups); - end; -end; - procedure ComunicaInsucesso(strIndicador : String); var IdHTTP2: TIdHTTP; Request_Config : TStringList; Response_Config : TStringStream; begin - + // Envio notificação de insucesso para o Módulo Gerente Centralizado Request_Config := TStringList.Create; Request_Config.Values['cs_indicador'] := strIndicador; @@ -390,8 +332,8 @@ var HistoricoLog : TextFile; begin try - FileSetAttr (v_home_drive + 'chkcacic.log',0); // Retira os atributos do arquivo para evitar o erro FILE ACCESS DENIED em máquinas 2000 - AssignFile(HistoricoLog,v_home_drive + 'chkcacic.log'); {Associa o arquivo a uma variável do tipo TextFile} + FileSetAttr (g_oCacic.getHomeDrive + 'chkcacic.log',0); // Retira os atributos do arquivo para evitar o erro FILE ACCESS DENIED em máquinas 2000 + AssignFile(HistoricoLog,g_oCacic.getHomeDrive + 'chkcacic.log'); {Associa o arquivo a uma variável do tipo TextFile} {$IOChecks off} Reset(HistoricoLog); {Abre o arquivo texto} @@ -423,107 +365,6 @@ Begin End; End; -// Pad a string with zeros so that it is a multiple of size -function PadWithZeros(const str : string; size : integer) : string; -var - origsize, i : integer; -begin - Result := str; - origsize := Length(Result); - if ((origsize mod size) <> 0) or (origsize = 0) then - begin - SetLength(Result,((origsize div size)+1)*size); - for i := origsize+1 to Length(Result) do - Result[i] := #0; - end; -end; - - -// Encrypt a string and return the Base64 encoded result -function EnCrypt(p_Data : String) : String; -var - l_Cipher : TDCP_rijndael; - l_Data, l_Key, l_IV : string; -begin - Try - // Pad Key, IV and Data with zeros as appropriate - l_Key := PadWithZeros(v_CipherKey,KeySize); - l_IV := PadWithZeros(v_IV,BlockSize); - l_Data := PadWithZeros(p_Data,BlockSize); - - // Create the cipher and initialise according to the key length - l_Cipher := TDCP_rijndael.Create(nil); - if Length(v_CipherKey) <= 16 then - l_Cipher.Init(l_Key[1],128,@l_IV[1]) - else if Length(v_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); - Except - LogDiario('Erro no Processo de Criptografia'); - End; -end; - -function DeCrypt(p_Data : String) : String; -var - l_Cipher : TDCP_rijndael; - l_Data, l_Key, l_IV : string; -begin - Try - // Pad Key and IV with zeros as appropriate - l_Key := PadWithZeros(v_CipherKey,KeySize); - l_IV := PadWithZeros(v_IV,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(v_CipherKey) <= 16 then - l_Cipher.Init(l_Key[1],128,@l_IV[1]) - else if Length(v_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; - Except - LogDiario('Erro no Processo de Decriptografia'); - End; -end; - - -Function Implode(p_Array : TStrings ; p_Separador : String) : String; -var intAux : integer; - strAux : string; -Begin - strAux := ''; - For intAux := 0 To p_Array.Count -1 do - Begin - if (strAux<>'') then strAux := strAux + p_Separador; - strAux := strAux + p_Array[intAux]; - End; - Implode := strAux; -end; - Function CipherClose(p_DatFileName : string) : String; var v_strCipherOpenImploded : string; v_DatFile : TextFile; @@ -536,8 +377,8 @@ begin Rewrite (v_DatFile); Append(v_DatFile); - v_strCipherOpenImploded := Implode(v_tstrCipherOpened,v_SeparatorKey); - v_strCipherClosed := EnCrypt(v_strCipherOpenImploded); + v_strCipherOpenImploded := g_oCacic.implode(v_tstrCipherOpened,g_oCacic.getSeparatorKey); + v_strCipherClosed := g_oCacic.enCrypt(v_strCipherOpenImploded); Writeln(v_DatFile,v_strCipherClosed); {Grava a string Texto no arquivo texto} @@ -567,12 +408,12 @@ begin Readln(v_DatFile,v_strCipherClosed); while not EOF(v_DatFile) do Readln(v_DatFile,v_strCipherClosed); CloseFile(v_DatFile); - v_strCipherOpened:= DeCrypt(v_strCipherClosed); + v_strCipherOpened:= g_oCacic.deCrypt(v_strCipherClosed); end; if (trim(v_strCipherOpened)<>'') then - Result := explode(v_strCipherOpened,v_SeparatorKey) + Result := g_oCacic.explode(v_strCipherOpened,g_oCacic.getSeparatorKey) else - Result := explode('Configs.ID_SO'+v_SeparatorKey+ g_oCacic.getWindowsStrId() +v_SeparatorKey+'Configs.Endereco_WS'+v_SeparatorKey+'/cacic2/ws/',v_SeparatorKey); + Result := g_oCacic.explode('Configs.ID_SO'+g_oCacic.getSeparatorKey+ g_oCacic.getWindowsStrId() +g_oCacic.getSeparatorKey+'Configs.Endereco_WS'+g_oCacic.getSeparatorKey+'/cacic2/ws/',g_oCacic.getSeparatorKey); if Result.Count mod 2 <> 0 then @@ -635,7 +476,7 @@ var RegEditSet: TRegistry; ListaAuxSet : TStrings; I : Integer; begin - ListaAuxSet := Explode(Chave, '\'); + ListaAuxSet := g_oCacic.explode(Chave, '\'); strRootKey := ListaAuxSet[0]; For I := 1 To ListaAuxSet.Count - 2 do strKey := strKey + ListaAuxSet[I] + '\'; @@ -695,7 +536,7 @@ var RegEditGet: TRegistry; DataSize, Len, I : Integer; begin try - ListaAuxGet := Explode(Chave, '\'); + ListaAuxGet := g_oCacic.Explode(Chave, '\'); strRootKey := ListaAuxGet[0]; For I := 1 To ListaAuxGet.Count - 2 Do strKey := strKey + ListaAuxGet[I] + '\'; @@ -788,7 +629,7 @@ var RegDelValorReg: TRegistry; ListaAuxDel : TStrings; I : Integer; begin - ListaAuxDel := Explode(Chave, '\'); + ListaAuxDel := g_oCacic.explode(Chave, '\'); strRootKey := ListaAuxDel[0]; For I := 1 To ListaAuxDel.Count - 2 Do strKey := strKey + ListaAuxDel[I] + '\'; strValue := ListaAuxDel[ListaAuxDel.Count - 1]; @@ -906,18 +747,12 @@ begin End; end; -function HomeDrive : string; -var -WinDir : array [0..144] of char; -begin -GetWindowsDirectory (WinDir, 144); -Result := StrPas (WinDir); -end; - procedure GravaConfiguracoes; var chkcacic_ini : TextFile; begin try + g_oCacic.setCacicPath(Configs.Edit_cacic_dir.text+'\'); + FileSetAttr (ExtractFilePath(Application.Exename) + '\chkcacic.ini',0); // Retira os atributos do arquivo para evitar o erro FILE ACCESS DENIED em máquinas 2000 AssignFile(chkcacic_ini,ExtractFilePath(Application.Exename) + '\chkcacic.ini'); {Associa o arquivo a uma variável do tipo TextFile} Rewrite (chkcacic_ini); // Recria o arquivo... @@ -1000,18 +835,17 @@ begin Writeln(chkcacic_ini,'[Cacic2]'); // Atribuição dos valores do form FormConfig às variáveis... - v_ip_serv_cacic := Configs.Edit_ip_serv_cacic.text; - v_cacic_dir := Configs.Edit_cacic_dir.text; if Configs.ckboxExibeInformacoes.Checked then v_exibe_informacoes := 'S' else v_exibe_informacoes := 'N'; + v_ip_serv_cacic := Configs.Edit_ip_serv_cacic.text; v_te_instala_informacoes_extras := Configs.Memo_te_instala_informacoes_extras.Text; // Escrita dos parâmetros obrigatórios Writeln(chkcacic_ini,'ip_serv_cacic='+v_ip_serv_cacic); - Writeln(chkcacic_ini,'cacic_dir='+v_cacic_dir); + Writeln(chkcacic_ini,'cacic_dir='+Configs.Edit_cacic_dir.text); Writeln(chkcacic_ini,'exibe_informacoes='+v_exibe_informacoes); // Escrita dos valores opcionais quando existirem @@ -1033,7 +867,7 @@ begin Writeln(iniFile,''); Writeln(iniFile,'[Cacic2]'); Writeln(iniFile,'ip_serv_cacic='+v_ip_serv_cacic); - Writeln(iniFile,'cacic_dir='+v_cacic_dir); + Writeln(iniFile,'cacic_dir='+g_oCacic.getCacicPath); CloseFile(iniFile); {Fecha o arquivo texto} except end; @@ -1159,7 +993,7 @@ Begin result := false; // Se eu conseguir matar o arquivo abaixo é porque não há outra sessão deste agente aberta... (POG? Nããão! :) ) - Matar(v_cacic_dir,'aguarde_CACIC.txt'); + Matar(g_oCacic.getCacicPath,'aguarde_CACIC.txt'); // Se o aguarde_CACIC.txt existir é porque refere-se a uma versão mais atual: 2.2.0.20 ou maior if not (FileExists(g_oCacic.getCacicPath() + '\aguarde_CACIC.txt')) then @@ -1247,6 +1081,7 @@ var bool_configura, bool_ArquivoINI, bool_CommandLine : boolean; + v_cacic_dir, v_te_serv_updates, v_nu_porta_serv_updates, v_nm_usuario_login_serv_updates, @@ -1280,7 +1115,6 @@ begin bool_ArquivoINI := FileExists(ExtractFilePath(Application.Exename) + '\chkcacic.ini'); Try - v_home_drive := MidStr(HomeDrive,1,3); //x:\ // 2.2.0.17 - Tratamento de opções passadas em linha de comando // Grande dica do grande Cláudio Filho (OpenOffice.org) @@ -1332,16 +1166,14 @@ begin End; g_oCacic := TCACIC.Create(); - g_oCacic.setCacicPath(v_home_drive + v_cacic_dir); - - Dir := v_home_drive + v_cacic_dir; // Ex.: c:\cacic\ + g_oCacic.setCacicPath(g_oCacic.getHomeDrive + v_cacic_dir + '\'); - if DirectoryExists(Dir + '\Temp\Debugs') then + if DirectoryExists(g_oCacic.getCacicPath + 'Temp\Debugs') then Begin - if (FormatDateTime('ddmmyyyy', GetFolderDate(Dir + '\Temp\Debugs')) = FormatDateTime('ddmmyyyy', date)) then + if (FormatDateTime('ddmmyyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs')) = FormatDateTime('ddmmyyyy', date)) then Begin v_Debugs := true; - LogDebug('Pasta "' + Dir + '\Temp\Debugs" com data '+FormatDateTime('dd-mm-yyyy', GetFolderDate(Dir + '\Temp\Debugs'))+' encontrada. DEBUG ativado.'); + LogDebug('Pasta "' + g_oCacic.getCacicPath + 'Temp\Debugs" com data '+FormatDateTime('dd-mm-yyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs'))+' encontrada. DEBUG ativado.'); End; End; @@ -1393,18 +1225,14 @@ begin LogDebug(':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::'); LogDebug(':::::::::::::: OBTENDO VALORES DO "chkcacic.ini" ::::::::::::::'); LogDebug(':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::'); - LogDebug('Drive de instalação......................: '+v_home_drive); - LogDebug('Pasta para instalação....................: '+Dir); + LogDebug('Drive de instalação......................: '+g_oCacic.getHomeDrive); + LogDebug('Pasta para instalação....................: '+g_oCacic.getCacicPath); LogDebug('IP do servidor...........................: '+v_ip_serv_cacic); LogDebug(':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::'); bool_configura := false; //chave AES. Recomenda-se que cada empresa/órgão altere a sua chave. - v_CipherKey := 'CacicBrasil'; - v_IV := 'abcdefghijklmnop'; - v_SeparatorKey := '=CacicIsFree='; // Usada apenas para o cacic2.dat - v_DatFileName := Dir + '\cacic2.dat'; - v_tstrCipherOpened := CipherOpen(v_DatFileName); + v_tstrCipherOpened := CipherOpen(g_oCacic.getCacicPath + '\' + g_oCacic.getDatFileName); if (g_oCacic.isWindowsGEXP()) then // Se >= Maior ou Igual ao WinXP... Begin @@ -1415,24 +1243,24 @@ begin Try Begin // Liberando as conexões de Saída para o FTP - SetValorChaveRegEdit('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules\FTP-Out-TCP','v2.0|Action=Allow|Active=TRUE|Dir=Out|Protocol=6|Profile=Private|App='+HomeDrive+'\system32\\ftp.exe|Name=Programa de transferência de arquivos|Desc=Programa de transferência de arquivos|Edge=FALSE|'); - SetValorChaveRegEdit('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules\FTP-Out-UDP','v2.0|Action=Allow|Active=TRUE|Dir=Out|Protocol=17|Profile=Private|App='+HomeDrive+'\system32\\ftp.exe|Name=Programa de transferência de arquivos|Desc=Programa de transferência de arquivos|Edge=FALSE|'); + SetValorChaveRegEdit('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules\FTP-Out-TCP','v2.0|Action=Allow|Active=TRUE|Dir=Out|Protocol=6|Profile=Private|App='+g_oCacic.getHomeDrive+'system32\\ftp.exe|Name=Programa de transferência de arquivos|Desc=Programa de transferência de arquivos|Edge=FALSE|'); + SetValorChaveRegEdit('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules\FTP-Out-UDP','v2.0|Action=Allow|Active=TRUE|Dir=Out|Protocol=17|Profile=Private|App='+g_oCacic.getHomeDrive+'system32\\ftp.exe|Name=Programa de transferência de arquivos|Desc=Programa de transferência de arquivos|Edge=FALSE|'); // Liberando as conexões de Saída para o Ger_Cols - SetValorChaveRegEdit('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules\CACIC-GERCOLS-Out-TCP','v2.0|Action=Allow|Active=TRUE|Dir=Out|Protocol=6|Profile=Private|App='+Dir+'\modulos\\ger_cols.exe|Name=Módulo Gerente de Coletas do Sistema CACIC|Desc=Módulo Gerente de Coletas do Sistema CACIC|Edge=FALSE|'); - SetValorChaveRegEdit('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules\CACIC-GERCOLS-Out-UDP','v2.0|Action=Allow|Active=TRUE|Dir=Out|Protocol=17|Profile=Private|App='+Dir+'\modulos\\ger_cols.exe|Name=Módulo Gerente de Coletas do Sistema CACIC|Desc=Módulo Gerente de Coletas do Sistema CACIC|Edge=FALSE|'); + SetValorChaveRegEdit('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules\CACIC-GERCOLS-Out-TCP','v2.0|Action=Allow|Active=TRUE|Dir=Out|Protocol=6|Profile=Private|App='+g_oCacic.getCacicPath+'modulos\\ger_cols.exe|Name=Módulo Gerente de Coletas do Sistema CACIC|Desc=Módulo Gerente de Coletas do Sistema CACIC|Edge=FALSE|'); + SetValorChaveRegEdit('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules\CACIC-GERCOLS-Out-UDP','v2.0|Action=Allow|Active=TRUE|Dir=Out|Protocol=17|Profile=Private|App='+g_oCacic.getCacicPath+'modulos\\ger_cols.exe|Name=Módulo Gerente de Coletas do Sistema CACIC|Desc=Módulo Gerente de Coletas do Sistema CACIC|Edge=FALSE|'); // Liberando as conexões de Saída para o SrCACICsrv - SetValorChaveRegEdit('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules\CACIC-SRCACICSRV-Out-TCP','v2.0|Action=Allow|Active=TRUE|Dir=Out|Protocol=6|Profile=Private|App='+Dir+'\modulos\\srcacicsrv.exe|Name=Módulo Suporte Remoto Seguro do Sistema CACIC|Desc=Módulo Suporte Remoto Seguro do Sistema CACIC|Edge=FALSE|'); - SetValorChaveRegEdit('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules\CACIC-SRCACICSRV-Out-UDP','v2.0|Action=Allow|Active=TRUE|Dir=Out|Protocol=17|Profile=Private|App='+Dir+'\modulos\\srcacicsrv.exe|Name=Módulo Suporte Remoto Seguro do Sistema CACIC|Desc=Módulo Suporte Remoto Seguro do Sistema CACIC|Edge=FALSE|'); + SetValorChaveRegEdit('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules\CACIC-SRCACICSRV-Out-TCP','v2.0|Action=Allow|Active=TRUE|Dir=Out|Protocol=6|Profile=Private|App='+g_oCacic.getCacicPath+'modulos\\srcacicsrv.exe|Name=Módulo Suporte Remoto Seguro do Sistema CACIC|Desc=Módulo Suporte Remoto Seguro do Sistema CACIC|Edge=FALSE|'); + SetValorChaveRegEdit('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules\CACIC-SRCACICSRV-Out-UDP','v2.0|Action=Allow|Active=TRUE|Dir=Out|Protocol=17|Profile=Private|App='+g_oCacic.getCacicPath+'modulos\\srcacicsrv.exe|Name=Módulo Suporte Remoto Seguro do Sistema CACIC|Desc=Módulo Suporte Remoto Seguro do Sistema CACIC|Edge=FALSE|'); // Liberando as conexões de Saída para o ChkCacic SetValorChaveRegEdit('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules\CACIC-CHKCACIC-Out-TCP','v2.0|Action=Allow|Active=TRUE|Dir=Out|Protocol=6|Profile=Private|App='+ExtractFilePath(Application.Exename) + '\chkcacic.exe|Name=chkcacic.exe|Desc=chkcacic.exe|Edge=FALSE|'); SetValorChaveRegEdit('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules\CACIC-CHKCACIC-Out-UDP','v2.0|Action=Allow|Active=TRUE|Dir=Out|Protocol=17|Profile=Private|App='+ExtractFilePath(Application.Exename) + '\chkcacic.exe|Name=chkcacic.exe|Desc=chkcacic.exe|Edge=FALSE|'); // Liberando as conexões de Saída para o ChkSis - SetValorChaveRegEdit('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules\CACIC-CHKSIS-Out-TCP','v2.0|Action=Allow|Active=TRUE|Dir=Out|Protocol=6|Profile=Private|App='+HomeDrive + '\chksis.exe|Name=Módulo Verificador de Integridade do Sistema CACIC|Desc=Módulo Verificador de Integridade do Sistema CACIC|Edge=FALSE|'); - SetValorChaveRegEdit('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules\CACIC-CHKSIS-Out-UDP','v2.0|Action=Allow|Active=TRUE|Dir=Out|Protocol=17|Profile=Private|App='+HomeDrive + '\chksis.exe|Name=Módulo Verificador de Integridade do Sistema CACIC|Desc=Módulo Verificador de Integridade do Sistema CACIC|Edge=FALSE|'); + SetValorChaveRegEdit('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules\CACIC-CHKSIS-Out-TCP','v2.0|Action=Allow|Active=TRUE|Dir=Out|Protocol=6|Profile=Private|App='+g_oCacic.getWinDir + 'chksis.exe|Name=Módulo Verificador de Integridade do Sistema CACIC|Desc=Módulo Verificador de Integridade do Sistema CACIC|Edge=FALSE|'); + SetValorChaveRegEdit('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules\CACIC-CHKSIS-Out-UDP','v2.0|Action=Allow|Active=TRUE|Dir=Out|Protocol=17|Profile=Private|App='+g_oCacic.getWinDir + 'chksis.exe|Name=Módulo Verificador de Integridade do Sistema CACIC|Desc=Módulo Verificador de Integridade do Sistema CACIC|Edge=FALSE|'); End Except LogDebug('Problema Liberando Policies de FireWall!'); @@ -1477,25 +1305,25 @@ begin end; // Verifico a existência do diretório configurado para o Cacic, normalmente CACIC - if not DirectoryExists(Dir) then + if not DirectoryExists(g_oCacic.getCacicPath) then begin - LogDiario('Criando pasta '+Dir); - ForceDirectories(Dir); + LogDiario('Criando pasta '+g_oCacic.getCacicPath); + ForceDirectories(g_oCacic.getCacicPath); end; // Para eliminar versão 20014 e anteriores que provavelmente não fazem corretamente o AutoUpdate - if not DirectoryExists(Dir+'\modulos') then + if not DirectoryExists(g_oCacic.getCacicPath+'modulos') then begin - Matar(Dir, '\cacic2.exe'); - ForceDirectories(Dir + '\modulos'); - LogDiario('Criando pasta '+Dir+'\modulos'); + Matar(g_oCacic.getCacicPath, 'cacic2.exe'); + ForceDirectories(g_oCacic.getCacicPath + 'modulos'); + LogDiario('Criando pasta '+g_oCacic.getCacicPath+'modulos'); end; // Crio o SubDiretório TEMP, caso não exista - if not DirectoryExists(Dir+'\temp') then + if not DirectoryExists(g_oCacic.getCacicPath+'temp') then begin - ForceDirectories(Dir + '\temp'); - LogDiario('Criando pasta '+Dir+'\temp'); + ForceDirectories(g_oCacic.getCacicPath + 'temp'); + LogDiario('Criando pasta '+g_oCacic.getCacicPath+'temp'); end; @@ -1573,101 +1401,101 @@ begin LogDebug(':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::'); // Atribuição de acesso ao módulo principal e pastas - Form1.FS_SetSecurity(Dir); - Form1.FS_SetSecurity(Dir + '\cacic2.exe'); - Form1.FS_SetSecurity(Dir + '\cacic2.dat'); - Form1.FS_SetSecurity(Dir + '\cacic2.log'); - Form1.FS_SetSecurity(Dir + '\modulos'); - Form1.FS_SetSecurity(Dir + '\temp'); + Form1.FS_SetSecurity(g_oCacic.getCacicPath); + Form1.FS_SetSecurity(g_oCacic.getCacicPath + 'cacic2.exe'); + Form1.FS_SetSecurity(g_oCacic.getCacicPath + 'cacic2.dat'); + Form1.FS_SetSecurity(g_oCacic.getCacicPath + 'cacic2.log'); + Form1.FS_SetSecurity(g_oCacic.getCacicPath + 'modulos'); + Form1.FS_SetSecurity(g_oCacic.getCacicPath + 'temp'); // Atribuição de acesso aos módulos de gerenciamento de coletas e coletas para permissão de atualizações de versões - Form1.FS_SetSecurity(Dir + '\modulos\ger_cols.exe'); - Form1.FS_SetSecurity(Dir + '\modulos\srcacicsrv.exe'); - Form1.FS_SetSecurity(Dir + '\modulos\col_anvi.exe'); - Form1.FS_SetSecurity(Dir + '\modulos\col_comp.exe'); - Form1.FS_SetSecurity(Dir + '\modulos\col_hard.exe'); - Form1.FS_SetSecurity(Dir + '\modulos\col_moni.exe'); - Form1.FS_SetSecurity(Dir + '\modulos\col_patr.exe'); - Form1.FS_SetSecurity(Dir + '\modulos\col_soft.exe'); - Form1.FS_SetSecurity(Dir + '\modulos\col_undi.exe'); - Form1.FS_SetSecurity(Dir + '\modulos\ini_cols.exe'); - Form1.FS_SetSecurity(Dir + '\modulos\wscript.exe'); + Form1.FS_SetSecurity(g_oCacic.getCacicPath + 'modulos\ger_cols.exe'); + Form1.FS_SetSecurity(g_oCacic.getCacicPath + 'modulos\srcacicsrv.exe'); + Form1.FS_SetSecurity(g_oCacic.getCacicPath + 'modulos\col_anvi.exe'); + Form1.FS_SetSecurity(g_oCacic.getCacicPath + 'modulos\col_comp.exe'); + Form1.FS_SetSecurity(g_oCacic.getCacicPath + 'modulos\col_hard.exe'); + Form1.FS_SetSecurity(g_oCacic.getCacicPath + 'modulos\col_moni.exe'); + Form1.FS_SetSecurity(g_oCacic.getCacicPath + 'modulos\col_patr.exe'); + Form1.FS_SetSecurity(g_oCacic.getCacicPath + 'modulos\col_soft.exe'); + Form1.FS_SetSecurity(g_oCacic.getCacicPath + 'modulos\col_undi.exe'); + Form1.FS_SetSecurity(g_oCacic.getCacicPath + 'modulos\ini_cols.exe'); + Form1.FS_SetSecurity(g_oCacic.getCacicPath + 'modulos\wscript.exe'); // Atribuição de acesso para atualização do módulo verificador de integridade do sistema e seus arquivos - Form1.FS_SetSecurity(HomeDrive + '\chksis.exe'); - Form1.FS_SetSecurity(HomeDrive + '\chksis.log'); - Form1.FS_SetSecurity(HomeDrive + '\chksis.dat'); + Form1.FS_SetSecurity(g_oCacic.getWinDir + 'chksis.exe'); + Form1.FS_SetSecurity(g_oCacic.getWinDir + 'chksis.log'); + Form1.FS_SetSecurity(g_oCacic.getWinDir + 'chksis.dat'); // Atribuição de acesso para atualização/exclusão de log do instalador - Form1.FS_SetSecurity(v_home_drive + 'chkcacic.log'); + Form1.FS_SetSecurity(g_oCacic.getHomeDrive + 'chkcacic.log'); LogDebug(':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::'); End; // Verificação de versão do cacic2.exe e exclusão em caso de versão antiga/diferente da atual - If (FileExists(Dir + '\cacic2.exe')) Then + If (FileExists(g_oCacic.getCacicPath + 'cacic2.exe')) Then Begin // Pego as informações de dia/mês/ano/horas/minutos/segundos/milésimos que identificam o agente Cacic2 - strDataHoraCACIC2_INI := FormatDateTime('ddmmyyyyhhnnsszzz', GetFolderDate(Dir + '\cacic2.exe')); + strDataHoraCACIC2_INI := FormatDateTime('ddmmyyyyhhnnsszzz', GetFolderDate(g_oCacic.getCacicPath + 'cacic2.exe')); - intAux := ChecaVersoesAgentes(Dir + '\cacic2.exe'); + intAux := ChecaVersoesAgentes(g_oCacic.getCacicPath + 'cacic2.exe'); // 0 => Arquivo de versões ou informação inexistente // 1 => Versões iguais // 2 => Versões diferentes if (intAux = 0) then Begin - v_versao_local := StringReplace(trim(GetVersionInfo(Dir + '\cacic2.exe')),'.','',[rfReplaceAll]); + v_versao_local := StringReplace(trim(GetVersionInfo(g_oCacic.getCacicPath + 'cacic2.exe')),'.','',[rfReplaceAll]); v_versao_remota := StringReplace(XML_RetornaValor('CACIC2' , v_retorno),'0103','',[rfReplaceAll]); End; if (intAux = 2) or // Caso haja diferença na comparação de versões com "versoes_agentes.ini"... (v_versao_local ='0000') or // Provavelmente versão muito antiga ou corrompida (v_versao_local ='2208') then - Matar(Dir, '\cacic2.exe'); + Matar(g_oCacic.getCacicPath, 'cacic2.exe'); End; // Verificação de versão do ger_cols.exe e exclusão em caso de versão antiga/diferente da atual - If (FileExists(Dir + '\modulos\ger_cols.exe')) Then + If (FileExists(g_oCacic.getCacicPath + 'modulos\ger_cols.exe')) Then Begin // Pego as informações de dia/mês/ano/horas/minutos/segundos/milésimos que identificam o agente Ger_Cols - strDataHoraGERCOLS_INI := FormatDateTime('ddmmyyyyhhnnsszzz', GetFolderDate(Dir + '\modulos\ger_cols.exe')); + strDataHoraGERCOLS_INI := FormatDateTime('ddmmyyyyhhnnsszzz', GetFolderDate(g_oCacic.getCacicPath + 'modulos\ger_cols.exe')); - intAux := ChecaVersoesAgentes(Dir + '\modulos\ger_cols.exe'); + intAux := ChecaVersoesAgentes(g_oCacic.getCacicPath + 'modulos\ger_cols.exe'); // 0 => Arquivo de versões ou informação inexistente // 1 => Versões iguais // 2 => Versões diferentes if (intAux = 0) then Begin - v_versao_local := StringReplace(trim(GetVersionInfo(Dir + '\modulos\ger_cols.exe')),'.','',[rfReplaceAll]); + v_versao_local := StringReplace(trim(GetVersionInfo(g_oCacic.getCacicPath + 'modulos\ger_cols.exe')),'.','',[rfReplaceAll]); v_versao_remota := StringReplace(XML_RetornaValor('GER_COLS' , v_retorno),'0103','',[rfReplaceAll]); End; if (intAux = 2) or // Caso haja diferença na comparação de versões com "versoes_agentes.ini"... (v_versao_local ='0000') then // Provavelmente versão muito antiga ou corrompida - Matar(Dir + '\modulos\', 'ger_cols.exe'); + Matar(g_oCacic.getCacicPath + 'modulos\', 'ger_cols.exe'); End; // Verificação de versão do chksis.exe e exclusão em caso de versão antiga/diferente da atual - If (FileExists(HomeDrive + '\chksis.exe')) Then + If (FileExists(g_oCacic.getWinDir + 'chksis.exe')) Then Begin - intAux := ChecaVersoesAgentes(HomeDrive + '\chksis.exe'); + intAux := ChecaVersoesAgentes(g_oCacic.getWinDir + 'chksis.exe'); // 0 => Arquivo de versões ou informação inexistente // 1 => Versões iguais // 2 => Versões diferentes if (intAux = 0) then Begin - v_versao_local := StringReplace(trim(GetVersionInfo(HomeDrive + '\chksis.exe')),'.','',[rfReplaceAll]); + v_versao_local := StringReplace(trim(GetVersionInfo(g_oCacic.getWinDir + 'chksis.exe')),'.','',[rfReplaceAll]); v_versao_remota := StringReplace(XML_RetornaValor('CHKSIS' , v_retorno),'0103','',[rfReplaceAll]); End; if (intAux = 2) or // Caso haja diferença na comparação de versões com "versoes_agentes.ini"... (v_versao_local ='0000') then // Provavelmente versão muito antiga ou corrompida - Matar(HomeDrive,'chksis.exe'); + Matar(g_oCacic.getWinDir,'chksis.exe'); End; // Tento detectar o ChkSis.EXE e copio ou faço FTP caso não exista verifyAndGet('chksis.exe', XML_RetornaValor('CHKSIS_HASH', v_retorno), - HomeDrive, + g_oCacic.getWinDir, v_te_serv_updates, v_nu_porta_serv_updates, v_nm_usuario_login_serv_updates, @@ -1676,11 +1504,11 @@ begin v_exibe_informacoes); // Tento detectar o ChkSis.INI e crio-o caso necessário - If not FileExists(HomeDrive + '\chksis.ini') Then + If not FileExists(g_oCacic.getWinDir + 'chksis.ini') Then begin - LogDebug('Criando '+HomeDrive + '\chksis.ini'); - GravaIni(HomeDrive + '\chksis.ini'); - FileSetAttr ( PChar(HomeDrive + '\chksis.ini'),0); // Retira os atributos do arquivo para evitar o erro FILE ACCESS DENIED em máquinas 2000 + LogDebug('Criando '+g_oCacic.getWinDir + 'chksis.ini'); + GravaIni(g_oCacic.getWinDir + 'chksis.ini'); + FileSetAttr ( PChar(g_oCacic.getWinDir + 'chksis.ini'),0); // Retira os atributos do arquivo para evitar o erro FILE ACCESS DENIED em máquinas 2000 end; @@ -1689,8 +1517,8 @@ begin Begin // Tento detectar o CACICsvc.EXE e copio ou faço FTP caso não exista verifyAndGet('cacicsvc.exe', - XML_RetornaValor('CACICSVC_HASH', v_retorno), - HomeDrive, + XML_RetornaValor('CACICSVC_HASH', v_retorno), + g_oCacic.getWinDir, v_te_serv_updates, v_nu_porta_serv_updates, v_nm_usuario_login_serv_updates, @@ -1699,16 +1527,13 @@ begin v_exibe_informacoes); // O CACICsvc usará o arquivo de configurações \Windows\chksis.ini - - //LogDebug('reCriando '+HomeDrive + '\cacicsvc.ini'); - //GravaIni(HomeDrive + '\cacicsvc.ini'); End; // Tento detectar o cacic2.INI e crio-o caso necessário - If not FileExists(Dir + '\cacic2.ini') Then + If not FileExists(g_oCacic.getCacicPath + 'cacic2.ini') Then begin - LogDebug('Criando/Recriando '+Dir + '\cacic2.ini'); - GravaIni(Dir + '\cacic2.ini'); + LogDebug('Criando/Recriando '+g_oCacic.getCacicPath + 'cacic2.ini'); + GravaIni(g_oCacic.getCacicPath + 'cacic2.ini'); end; // Verifico se existe a pasta "modulos" @@ -1717,8 +1542,8 @@ begin // Tento detectar o Agente Principal e copio ou faço FTP caso não exista verifyAndGet('cacic2.exe', - XML_RetornaValor('CACIC2_HASH', v_retorno), - Dir, + XML_RetornaValor('CACIC2_HASH', v_retorno), + g_oCacic.getCacicPath, v_te_serv_updates, v_nu_porta_serv_updates, v_nm_usuario_login_serv_updates, @@ -1728,7 +1553,7 @@ begin verifyAndGet('ger_cols.exe', XML_RetornaValor('GER_COLS_HASH', v_retorno), - Dir + '\modulos', + g_oCacic.getCacicPath + 'modulos', v_te_serv_updates, v_nu_porta_serv_updates, v_nm_usuario_login_serv_updates, @@ -1747,8 +1572,8 @@ begin (v_array_modulos[intAux]<>'chksis.exe') then Begin LogDiario('Copiando '+v_array_modulos[intAux]+' de '+ExtractFilePath(Application.Exename)+'modulos\'); - CopyFile(PChar(ExtractFilePath(Application.Exename) + 'modulos\'+v_array_modulos[intAux]), PChar(Dir + '\modulos\'+v_array_modulos[intAux]),false); - FileSetAttr (PChar(Dir + '\modulos\'+v_array_modulos[intAux]),0); // Retira os atributos do arquivo para evitar o erro FILE ACCESS DENIED em máquinas 2000 + CopyFile(PChar(ExtractFilePath(Application.Exename) + 'modulos\'+v_array_modulos[intAux]), PChar(g_oCacic.getCacicPath + 'modulos\'+v_array_modulos[intAux]),false); + FileSetAttr (PChar(g_oCacic.getCacicPath + 'modulos\'+v_array_modulos[intAux]),0); // Retira os atributos do arquivo para evitar o erro FILE ACCESS DENIED em máquinas 2000 End; End; End; @@ -1760,7 +1585,7 @@ begin // Tento detectar (de novo) o ChkSis.EXE e copio ou faço FTP caso não exista verifyAndGet('chksis.exe', XML_RetornaValor('CHKSIS_HASH', v_retorno), - HomeDrive, + g_oCacic.getWinDir, v_te_serv_updates, v_nu_porta_serv_updates, v_nm_usuario_login_serv_updates, @@ -1771,7 +1596,7 @@ begin // Tento detectar (de novo) o Agente Principal e copio ou faço FTP caso não exista verifyAndGet('cacic2.exe', XML_RetornaValor('CACIC2_HASH', v_retorno), - Dir, + g_oCacic.getCacicPath, v_te_serv_updates, v_nu_porta_serv_updates, v_nm_usuario_login_serv_updates, @@ -1781,7 +1606,7 @@ begin verifyAndGet('ger_cols.exe', XML_RetornaValor('GER_COLS_HASH', v_retorno), - Dir + '\modulos', + g_oCacic.getCacicPath + 'modulos', v_te_serv_updates, v_nu_porta_serv_updates, v_nm_usuario_login_serv_updates, @@ -1789,28 +1614,22 @@ begin v_te_path_serv_updates, v_exibe_informacoes); - - { - if ((intWinVer <> 0) and (intWinVer >= 8)) or - (abstraiCSD(v_te_so) >= 250) then // Se >= WinXP... - } - if (g_oCacic.isWindowsNTPlataform) then Begin Try // Acrescento o Ger_Cols e srCacicSrv às exceções do FireWall nativo... {chksis} - LogDebug('Inserindo "'+HomeDrive + '\chksis" nas exceções do FireWall!'); - LiberaFireWall(HomeDrive + '\chksis'); + LogDebug('Inserindo "'+g_oCacic.getWinDir + 'chksis" nas exceções do FireWall!'); + LiberaFireWall(g_oCacic.getWinDir + 'chksis'); {ger_cols} - LogDebug('Inserindo "'+Dir + '\modulos\ger_cols" nas exceções do FireWall!'); - LiberaFireWall(Dir + '\modulos\ger_cols'); + LogDebug('Inserindo "'+g_oCacic.getCacicPath + 'modulos\ger_cols" nas exceções do FireWall!'); + LiberaFireWall(g_oCacic.getCacicPath + 'modulos\ger_cols'); {srcacicsrv} - LogDebug('Inserindo "'+Dir + '\modulos\srcacicsrv" nas exceções do FireWall!'); - LiberaFireWall(Dir + '\modulos\srcacicsrv'); + LogDebug('Inserindo "'+g_oCacic.getCacicPath + 'modulos\srcacicsrv" nas exceções do FireWall!'); + LiberaFireWall(g_oCacic.getCacicPath + 'modulos\srcacicsrv'); Except End; @@ -1823,13 +1642,13 @@ begin Begin // Crio a chave/valor cacic2 para autoexecução do Cacic, caso não exista esta chave/valor // Crio a chave/valor chksis para autoexecução do ChkSIS, caso não exista esta chave/valor - SetValorChaveRegEdit('HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run\CheckSystemRoutine', HomeDrive + '\chksis.exe'); + SetValorChaveRegEdit('HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run\CheckSystemRoutine', g_oCacic.getWinDir + 'chksis.exe'); bool_ExistsAutoRun := false; - if (GetValorChaveRegEdit('HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run\cacic2')=Dir + '\cacic2.exe') then + if (GetValorChaveRegEdit('HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run\cacic2')=g_oCacic.getCacicPath + 'cacic2.exe') then bool_ExistsAutoRun := true else - SetValorChaveRegEdit('HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run\cacic2', Dir + '\cacic2.exe'); + SetValorChaveRegEdit('HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run\cacic2', g_oCacic.getCacicPath + 'cacic2.exe'); End else Begin @@ -1840,24 +1659,24 @@ begin // Igualo as chaves ip_serv_cacic dos arquivos chksis.ini e cacic2.ini! SetValorDatMemoria('Configs.EnderecoServidor', v_ip_serv_cacic); LogDebug('Fechando Arquivo de Configurações do Cacic'); - CipherClose(v_DatFileName); + CipherClose(g_oCacic.getDatFileName); LogDebug('Abrindo Arquivo de Configurações do ChkSis'); - CipherOpen(HomeDrive + '\chksis.dat'); + CipherOpen(g_oCacic.getWinDir + 'chksis.dat'); SetValorDatMemoria('Cacic2.ip_serv_cacic', v_ip_serv_cacic); - CipherClose(HomeDrive + '\chksis.dat'); + CipherClose(g_oCacic.getWinDir + 'chksis.dat'); // Volto a gravar o chksis.ini para o difícil caso de leitura por versões antigas - SetValorChaveRegIni('Cacic2', 'ip_serv_cacic', v_ip_serv_cacic, HomeDrive + '\chksis.ini'); + SetValorChaveRegIni('Cacic2', 'ip_serv_cacic', v_ip_serv_cacic, g_oCacic.getWinDir + 'chksis.ini'); LogDebug('Fechando Arquivo de Configurações do ChkSis'); LogDebug('Resgatando informações para identificação de alteração do agente CACIC2'); // Pego as informações de dia/mês/ano/horas/minutos/segundos/milésimos que identificam os agentes - strDataHoraCACIC2_FIM := FormatDateTime('ddmmyyyyhhnnsszzz', GetFolderDate(Dir + '\cacic2.exe')); + strDataHoraCACIC2_FIM := FormatDateTime('ddmmyyyyhhnnsszzz', GetFolderDate(g_oCacic.getCacicPath + 'cacic2.exe')); LogDebug('Inicial => "' + strDataHoraCACIC2_INI + '" Final => "' + strDataHoraCACIC2_FIM + '"'); LogDebug('Resgatando informações para identificação de alteração do agente GER_COLS'); - strDataHoraGERCOLS_FIM := FormatDateTime('ddmmyyyyhhnnsszzz', GetFolderDate(Dir + '\modulos\ger_cols.exe')); + strDataHoraGERCOLS_FIM := FormatDateTime('ddmmyyyyhhnnsszzz', GetFolderDate(g_oCacic.getCacicPath + 'modulos\ger_cols.exe')); LogDebug('Inicial => "' + strDataHoraGERCOLS_INI + '" Final => "' + strDataHoraGERCOLS_FIM + '"'); // Caso o Cacic tenha sido baixado executo-o com parâmetro de configuração de servidor @@ -1866,7 +1685,7 @@ begin Begin v_te_texto_janela_instalacao := v_te_instala_informacoes_extras; - if (GetValorChaveRegEdit('HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run\cacic2')=Dir + '\cacic2.exe') and + if (GetValorChaveRegEdit('HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run\cacic2')=g_oCacic.getCacicPath + 'cacic2.exe') and (not g_oCacic.isWindowsNTPlataform()) or (g_oCacic.isWindowsNTPlataform()) then Begin @@ -1888,11 +1707,11 @@ begin // Se não for plataforma NT executo o agente principal if not (g_oCacic.isWindowsNTPlataform()) then Begin - LogDebug('Executando '+Dir + '\cacic2.exe /ip_serv_cacic=' + v_ip_serv_cacic); + LogDebug('Executando '+g_oCacic.getCacicPath + 'cacic2.exe /ip_serv_cacic=' + v_ip_serv_cacic); if (strDataHoraCACIC2_INI <> strDataHoraCACIC2_FIM) then - WinExec(PChar(Dir + '\cacic2.exe /ip_serv_cacic=' + v_ip_serv_cacic+ ' /execute'), SW_HIDE) + WinExec(PChar(g_oCacic.getCacicPath + 'cacic2.exe /ip_serv_cacic=' + v_ip_serv_cacic+ ' /execute'), SW_HIDE) else - WinExec(PChar(Dir + '\cacic2.exe /ip_serv_cacic=' + v_ip_serv_cacic ), SW_HIDE); + WinExec(PChar(g_oCacic.getCacicPath + 'cacic2.exe /ip_serv_cacic=' + v_ip_serv_cacic ), SW_HIDE); End else Begin @@ -1911,13 +1730,13 @@ begin Begin // Instalo e Habilito o serviço LogDiario('Instalando CACICservice...'); - WinExec(PChar(HomeDrive + '\cacicsvc.exe -install'), SW_NORMAL); + WinExec(PChar(g_oCacic.getWinDir + 'cacicsvc.exe -install'), SW_NORMAL); End else if ((wordServiceStatus < 4) or (wordServiceStatus > 4)) then Begin LogDiario('Iniciando CACICservice'); - WinExec(PChar(HomeDrive + '\cacicsvc.exe -start'), SW_NORMAL); + WinExec(PChar(g_oCacic.getWinDir + 'cacicsvc.exe -start'), SW_NORMAL); End else LogDiario('Não instalei o CACICservice. Já está rodando...'); @@ -1937,14 +1756,11 @@ begin LogDiario('Falha na Instalação/Atualização'); End; - Application.Terminate; - { - Considerando-se que o objeto se libera ao fim da aplicação try g_oCacic.Free(); except end; - } + Application.Terminate; end; function ServiceRunning(sMachine, sService: PChar): Boolean; diff --git a/chksis/chksis.dpr b/chksis/chksis.dpr index eef3feb..242bb04 100755 --- a/chksis/chksis.dpr +++ b/chksis/chksis.dpr @@ -37,63 +37,22 @@ uses IdTCPClient, PJVersionInfo, Winsock, - DCPcrypt2, - DCPrijndael, - DCPbase64, Tlhelp32, CACIC_Library in '..\CACIC_Library.pas'; -var PJVersionInfo1: TPJVersionInfo; - Dir, - v_CipherKey, - v_IV, - v_SeparatorKey, - v_strCipherClosed, - v_DatFileName, - v_versao_local, - v_versao_remota, - v_retorno, - v_te_so : String; - v_Debugs : Boolean; -var v_tstrCipherOpened : TStrings; - -var g_oCacic : TCACIC; - -// Some constants that are dependant on the cipher being used -// Assuming MCRYPT_RIJNDAEL_128 (i.e., 128bit blocksize, 256bit keysize) -const KeySize = 32; // 32 bytes = 256 bits - BlockSize = 16; // 16 bytes = 128 bits - -Function Explode(Texto, Separador : String) : TStrings; var - strItem : String; - ListaAuxUTILS : TStrings; - NumCaracteres, - TamanhoSeparador, - I : Integer; -Begin - ListaAuxUTILS := TStringList.Create; - strItem := ''; - NumCaracteres := Length(Texto); - TamanhoSeparador := Length(Separador); - I := 1; - While I <= NumCaracteres Do - Begin - If (Copy(Texto,I,TamanhoSeparador) = Separador) or (I = NumCaracteres) Then - Begin - if (I = NumCaracteres) then strItem := strItem + Texto[I]; - ListaAuxUTILS.Add(trim(strItem)); - strItem := ''; - I := I + (TamanhoSeparador-1); - end - Else - strItem := strItem + Texto[I]; - - I := I + 1; - End; - Explode := ListaAuxUTILS; -end; + PJVersionInfo1: TPJVersionInfo; + v_strCipherClosed, + v_versao_local, + v_versao_remota, + v_retorno : String; + v_Debugs : Boolean; +var + v_tstrCipherOpened : TStrings; + +var + g_oCacic : TCACIC; function VerFmt(const MS, LS: DWORD): string; // Format the version number from the given DWORDs containing the info @@ -102,31 +61,17 @@ begin [HiWord(MS), LoWord(MS), HiWord(LS), LoWord(LS)]) end; -{ TMainForm } -Function Implode(p_Array : TStrings ; p_Separador : String) : String; -var intAux : integer; - strAux : string; -Begin - strAux := ''; - For intAux := 0 To p_Array.Count -1 do - Begin - if (strAux<>'') then strAux := strAux + p_Separador; - strAux := strAux + p_Array[intAux]; - End; - Implode := strAux; -end; - procedure log_diario(strMsg : String); var HistoricoLog : TextFile; strDataArqLocal, strDataAtual, - p_path : string; + v_path : string; begin try - p_path := Dir + '\chksis.log'; - FileSetAttr (p_path,0); // Retira os atributos do arquivo para evitar o erro FILE ACCESS DENIED em máquinas 2000 - AssignFile(HistoricoLog,p_path); {Associa o arquivo a uma variável do tipo TextFile} + v_path := g_oCacic.getWinDir + 'chksis.log'; + FileSetAttr (v_path,0); // Retira os atributos do arquivo para evitar o erro FILE ACCESS DENIED em máquinas 2000 + AssignFile(HistoricoLog,v_path); {Associa o arquivo a uma variável do tipo TextFile} {$IOChecks off} Reset(HistoricoLog); {Abre o arquivo texto} {$IOChecks on} @@ -136,7 +81,7 @@ begin Append(HistoricoLog); Writeln(HistoricoLog,FormatDateTime('dd/mm hh:nn:ss : ', Now) + '======================> Iniciando o Log <======================='); end; - DateTimeToString(strDataArqLocal, 'yyyymmdd', FileDateToDateTime(Fileage(p_path))); + DateTimeToString(strDataArqLocal, 'yyyymmdd', FileDateToDateTime(Fileage(v_path))); DateTimeToString(strDataAtual , 'yyyymmdd', Date); if (strDataAtual <> strDataArqLocal) then // Se o arquivo INI não é da data atual... begin @@ -163,93 +108,6 @@ Begin if v_Debugs then log_diario('(v.'+getVersionInfo(ParamStr(0))+') DEBUG - '+p_msg); End; -// Pad a string with zeros so that it is a multiple of size -function PadWithZeros(const str : string; size : integer) : string; -var - origsize, i : integer; -begin - Result := str; - origsize := Length(Result); - if ((origsize mod size) <> 0) or (origsize = 0) then - begin - SetLength(Result,((origsize div size)+1)*size); - for i := origsize+1 to Length(Result) do - Result[i] := #0; - end; -end; - - -// Encrypt a string and return the Base64 encoded result -function EnCrypt(p_Data : String) : String; -var - l_Cipher : TDCP_rijndael; - l_Data, l_Key, l_IV : string; -begin - Try - // Pad Key, IV and Data with zeros as appropriate - l_Key := PadWithZeros(v_CipherKey,KeySize); - l_IV := PadWithZeros(v_IV,BlockSize); - l_Data := PadWithZeros(p_Data,BlockSize); - - // Create the cipher and initialise according to the key length - l_Cipher := TDCP_rijndael.Create(nil); - if Length(v_CipherKey) <= 16 then - l_Cipher.Init(l_Key[1],128,@l_IV[1]) - else if Length(v_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); - Except - log_diario('Erro no Processo de Criptografia'); - End; -end; - -function DeCrypt(p_Data : String) : String; -var - l_Cipher : TDCP_rijndael; - l_Data, l_Key, l_IV : string; -begin - Try - // Pad Key and IV with zeros as appropriate - l_Key := PadWithZeros(v_CipherKey,KeySize); - l_IV := PadWithZeros(v_IV,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(v_CipherKey) <= 16 then - l_Cipher.Init(l_Key[1],128,@l_IV[1]) - else if Length(v_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; - Except - log_diario('Erro no Processo de Decriptografia'); - End; -end; - Function CipherClose(p_DatFileName : string) : String; var v_strCipherOpenImploded : string; v_DatFile : TextFile; @@ -270,8 +128,8 @@ begin Append(v_DatFile); End; - v_strCipherOpenImploded := Implode(v_tstrCipherOpened,v_SeparatorKey); - v_strCipherClosed := EnCrypt(v_strCipherOpenImploded); + v_strCipherOpenImploded := g_oCacic.implode(v_tstrCipherOpened,g_oCacic.getSeparatorKey); + v_strCipherClosed := g_oCacic.enCrypt(v_strCipherOpenImploded); Writeln(v_DatFile,v_strCipherClosed); {Grava a string Texto no arquivo texto} @@ -302,12 +160,12 @@ begin Readln(v_DatFile,v_strCipherClosed); while not EOF(v_DatFile) do Readln(v_DatFile,v_strCipherClosed); CloseFile(v_DatFile); - v_strCipherOpened:= DeCrypt(v_strCipherClosed); + v_strCipherOpened:= g_oCacic.deCrypt(v_strCipherClosed); end; if (trim(v_strCipherOpened)<>'') then - Result := explode(v_strCipherOpened,v_SeparatorKey) + Result := g_oCacic.explode(v_strCipherOpened,g_oCacic.getSeparatorKey) else - Result := explode('Configs.ID_SO' + v_SeparatorKey + g_oCacic.getWindowsStrId() +v_SeparatorKey+'Configs.Endereco_WS'+v_SeparatorKey+'/cacic2/ws/',v_SeparatorKey); + Result := g_oCacic.explode('Configs.ID_SO' + g_oCacic.getSeparatorKey + g_oCacic.getWindowsStrId() + g_oCacic.getSeparatorKey + 'Configs.Endereco_WS' + g_oCacic.getSeparatorKey + '/cacic2/ws/',g_oCacic.getSeparatorKey); if Result.Count mod 2 <> 0 then Result.Add(''); @@ -344,7 +202,7 @@ var RegEditSet: TRegistry; ListaAuxSet : TStrings; I : Integer; begin - ListaAuxSet := Explode(Chave, '\'); + ListaAuxSet := g_oCacic.explode(Chave, '\'); strRootKey := ListaAuxSet[0]; For I := 1 To ListaAuxSet.Count - 2 Do strKey := strKey + ListaAuxSet[I] + '\'; strValue := ListaAuxSet[ListaAuxSet.Count - 1]; @@ -402,7 +260,7 @@ var RegEditGet: TRegistry; DataSize, Len, I : Integer; begin try - ListaAuxGet := Explode(Chave, '\'); + ListaAuxGet := g_oCacic.explode(Chave, '\'); strRootKey := ListaAuxGet[0]; For I := 1 To ListaAuxGet.Count - 2 Do strKey := strKey + ListaAuxGet[I] + '\'; @@ -484,7 +342,7 @@ var RegDelValorReg: TRegistry; ListaAuxDel : TStrings; I : Integer; begin - ListaAuxDel := Explode(Chave, '\'); + ListaAuxDel := g_oCacic.explode(Chave, '\'); strRootKey := ListaAuxDel[0]; For I := 1 To ListaAuxDel.Count - 2 Do strKey := strKey + ListaAuxDel[I] + '\'; strValue := ListaAuxDel[ListaAuxDel.Count - 1]; @@ -521,8 +379,6 @@ begin Result := IntToStr(I1); 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; var IdFTP : TIdFTP; msg_error : string; @@ -565,15 +421,6 @@ begin End; end; - -function HomeDrive : string; -var -WinDir : array [0..144] of char; -begin -GetWindowsDirectory (WinDir, 144); -Result := StrPas (WinDir); -end; - function GetIP: string; var ipwsa:TWSAData; p:PHostEnt; s:array[0..128] of char; c:pchar; begin @@ -704,11 +551,11 @@ Begin result := false; // Se o aguarde_CACIC.txt existir é porque refere-se a uma versão mais atual: 2.2.0.20 ou maior - if (FileExists(Dir + '\aguarde_CACIC.txt')) then + if (FileExists(g_oCacic.getCacicPath + 'aguarde_CACIC.txt')) then Begin // Se eu conseguir matar o arquivo abaixo é porque não há outra sessão deste agente aberta... (POG? Nããão! :) ) - Matar(Dir,'aguarde_CACIC.txt'); - if (not (FileExists(Dir + '\aguarde_CACIC.txt'))) then + Matar(g_oCacic.getCacicPath,'aguarde_CACIC.txt'); + if (not (FileExists(g_oCacic.getCacicPath + 'aguarde_CACIC.txt'))) then result := true; End; End; @@ -720,7 +567,7 @@ var v_versao_REM, v_array_NomeAgente : TStrings; intAux : integer; Begin - v_array_NomeAgente := explode(p_strNomeAgente,'\'); + v_array_NomeAgente := g_oCacic.explode(p_strNomeAgente,'\'); v_versao_REM := XML_RetornaValor(StringReplace(StrUpper(PChar(v_array_NomeAgente[v_array_NomeAgente.count-1])),'.EXE','',[rfReplaceAll]), v_retorno); v_versao_LOC := GetVersionInfo(p_strNomeAgente); @@ -779,7 +626,7 @@ procedure executa_chksis; var bool_download_CACIC2, bool_ExistsAutoRun : boolean; - v_home_drive, v_ip_serv_cacic, v_cacic_dir, v_rem_cacic_v0x, + v_ip_serv_cacic, v_cacic_dir, v_rem_cacic_v0x, v_te_serv_updates, v_nu_porta_serv_updates, v_nm_usuario_login_serv_updates, v_te_senha_login_serv_updates, v_te_path_serv_updates : String; Request_Config : TStringList; @@ -789,19 +636,19 @@ var begin bool_download_CACIC2 := false; - v_home_drive := MidStr(HomeDrive,1,3); //x:\ v_ip_serv_cacic := GetValorChaveRegIni('Cacic2', 'ip_serv_cacic', ExtractFilePath(ParamStr(0)) + 'chksis.ini'); - v_cacic_dir := GetValorChaveRegIni('Cacic2', 'cacic_dir', ExtractFilePath(ParamStr(0)) + 'chksis.ini'); + v_cacic_dir := GetValorChaveRegIni('Cacic2', 'cacic_dir' , ExtractFilePath(ParamStr(0)) + 'chksis.ini'); v_rem_cacic_v0x := GetValorChaveRegIni('Cacic2', 'rem_cacic_v0x', ExtractFilePath(ParamStr(0)) + 'chksis.ini'); - Dir := v_home_drive + v_cacic_dir; + + g_oCacic.setCacicPath(g_oCacic.getHomeDrive + v_cacic_dir +'\'); v_Debugs := false; - if DirectoryExists(v_cacic_dir + '\Temp\Debugs') then + if DirectoryExists(g_oCacic.getCacicPath + 'Temp\Debugs') then Begin - if (FormatDateTime('ddmmyyyy', GetFolderDate(v_cacic_dir + '\Temp\Debugs')) = FormatDateTime('ddmmyyyy', date)) then + if (FormatDateTime('ddmmyyyy', GetFolderDate(g_oCacic.getCacicPath + 'Temp\Debugs')) = FormatDateTime('ddmmyyyy', date)) then Begin v_Debugs := true; - log_DEBUG('Pasta "' + v_cacic_dir + '\Temp\Debugs" com data '+FormatDateTime('dd-mm-yyyy', GetFolderDate(v_cacic_dir + '\Temp\Debugs'))+' encontrada. DEBUG ativado.'); + 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; @@ -813,36 +660,30 @@ begin end; // Verifico a existência do diretório configurado para o Cacic, normalmente CACIC - if not DirectoryExists(Dir) then + if not DirectoryExists(g_oCacic.getCacicPath) then begin //log_diario('Criando diretório ' + Dir,ExtractFilePath(ParamStr(0))); - ForceDirectories(Dir); + ForceDirectories(g_oCacic.getCacicPath); end; // Para eliminar versão 20014 e anteriores que provavelmente não fazem corretamente o AutoUpdate - if not DirectoryExists(Dir+'\modulos') then + if not DirectoryExists(g_oCacic.getCacicPath+'modulos') then begin - log_diario('Excluindo '+ Dir + '\cacic2.exe'); - Matar(Dir,'\cacic2.exe'); - log_diario('Criando diretório ' + Dir + '\modulos'); - ForceDirectories(Dir + '\modulos'); + log_diario('Excluindo '+ g_oCacic.getCacicPath + 'cacic2.exe'); + Matar(g_oCacic.getCacicPath,'cacic2.exe'); + log_diario('Criando diretório ' + g_oCacic.getCacicPath + 'modulos'); + ForceDirectories(g_oCacic.getCacicPath + 'modulos'); end; // Crio o SubDiretório TEMP, caso não exista - if not DirectoryExists(Dir+'\temp') then + if not DirectoryExists(g_oCacic.getCacicPath+'temp') then begin - log_diario('Criando diretório ' + Dir + '\temp'); - ForceDirectories(Dir + '\temp'); + log_diario('Criando diretório ' + g_oCacic.getCacicPath + 'temp'); + ForceDirectories(g_oCacic.getCacicPath + 'temp'); end; - //chave AES. Recomenda-se que cada empresa altere a sua chave. - v_CipherKey := 'CacicBrasil'; - v_IV := 'abcdefghijklmnop'; - v_SeparatorKey := '=CacicIsFree='; - v_DatFileName := Dir + '\cacic2.dat'; - // Verifico existência dos dois principais objetos - If (not FileExists(Dir + '\cacic2.exe')) or (not FileExists(Dir + '\modulos\ger_cols.exe')) Then + If (not FileExists(g_oCacic.getCacicPath + 'cacic2.exe')) or (not FileExists(g_oCacic.getCacicPath + 'modulos\ger_cols.exe')) Then Begin // Busco as configurações para acesso ao ambiente FTP - Updates Request_Config := TStringList.Create; @@ -886,68 +727,68 @@ begin Response_Config.Free; // Verificação de versão do cacic2.exe e exclusão em caso de versão antiga - If (FileExists(Dir + '\cacic2.exe')) Then + If (FileExists(g_oCacic.getCacicPath + 'cacic2.exe')) Then Begin - intAux := ChecaVersoesAgentes(Dir + '\cacic2.exe'); + intAux := ChecaVersoesAgentes(g_oCacic.getCacicPath + 'cacic2.exe'); // 0 => Arquivo de versões ou informação inexistente // 1 => Versões iguais // 2 => Versões diferentes if (intAux = 0) then Begin - v_versao_local := StringReplace(trim(GetVersionInfo(Dir + '\cacic2.exe')),'.','',[rfReplaceAll]); + v_versao_local := StringReplace(trim(GetVersionInfo(g_oCacic.getCacicPath + 'cacic2.exe')),'.','',[rfReplaceAll]); v_versao_remota := StringReplace(XML_RetornaValor('CACIC2' , v_retorno),'0103','',[rfReplaceAll]); End; if (intAux = 2) or // Caso haja diferença na comparação de versões com "versoes_agentes.ini"... (v_versao_local ='0000') or // Provavelmente versão muito antiga ou corrompida (v_versao_local ='2208') then - Matar(Dir, '\cacic2.exe'); + Matar(g_oCacic.getCacicPath, 'cacic2.exe'); End; // Verificação de versão do ger_cols.exe e exclusão em caso de versão antiga - If (FileExists(Dir + '\modulos\ger_cols.exe')) Then + If (FileExists(g_oCacic.getCacicPath + 'modulos\ger_cols.exe')) Then Begin - intAux := ChecaVersoesAgentes(Dir + '\modulos\ger_cols.exe'); + intAux := ChecaVersoesAgentes(g_oCacic.getCacicPath + 'modulos\ger_cols.exe'); // 0 => Arquivo de versões ou informação inexistente // 1 => Versões iguais // 2 => Versões diferentes if (intAux = 0) then Begin - v_versao_local := StringReplace(trim(GetVersionInfo(Dir + '\modulos\ger_cols.exe')),'.','',[rfReplaceAll]); + v_versao_local := StringReplace(trim(GetVersionInfo(g_oCacic.getCacicPath + 'modulos\ger_cols.exe')),'.','',[rfReplaceAll]); v_versao_remota := StringReplace(XML_RetornaValor('GER_COLS' , v_retorno),'0103','',[rfReplaceAll]); End; if (intAux = 2) or // Caso haja diferença na comparação de versões com "versoes_agentes.ini"... (v_versao_local ='0000') then // Provavelmente versão muito antiga ou corrompida - Matar(Dir + '\modulos\', 'ger_cols.exe'); + Matar(g_oCacic.getCacicPath + 'modulos\', 'ger_cols.exe'); End; // Tento detectar o Agente Principal e faço FTP caso não exista - If not FileExists(Dir + '\cacic2.exe') Then + If not FileExists(g_oCacic.getCacicPath + 'cacic2.exe') Then begin log_diario('Fazendo FTP de cacic2.exe a partir de ' + v_te_serv_updates + '/' + v_nu_porta_serv_updates+'/'+ v_nm_usuario_login_serv_updates + '/' + - v_te_path_serv_updates + ' para a pasta ' + Dir); + v_te_path_serv_updates + ' para a pasta ' + g_oCacic.getCacicPath); FTP(v_te_serv_updates, v_nu_porta_serv_updates, v_nm_usuario_login_serv_updates, v_te_senha_login_serv_updates, v_te_path_serv_updates, 'cacic2.exe', - Dir); + g_oCacic.getCacicPath); bool_download_CACIC2 := true; end; // Tento detectar o Gerente de Coletas e faço FTP caso não exista - If (not FileExists(Dir + '\modulos\ger_cols.exe')) Then + If (not FileExists(g_oCacic.getCacicPath + 'modulos\ger_cols.exe')) Then begin log_diario('Fazendo FTP de ger_cols.exe a partir de ' + v_te_serv_updates + '/' + v_nu_porta_serv_updates+'/'+ v_nm_usuario_login_serv_updates + '/' + - v_te_path_serv_updates + ' para a pasta ' + Dir + '\modulos'); + v_te_path_serv_updates + ' para a pasta ' + g_oCacic.getCacicPath + 'modulos'); FTP(v_te_serv_updates, v_nu_porta_serv_updates, @@ -955,7 +796,7 @@ begin v_te_senha_login_serv_updates, v_te_path_serv_updates, 'ger_cols.exe', - Dir + '\modulos'); + g_oCacic.getCacicPath + 'modulos'); end; @@ -988,13 +829,13 @@ begin // Caso o Cacic tenha sido baixado executo-o com parâmetro de configuração de servidor if Posso_Rodar_CACIC or not bool_ExistsAutoRun then Begin - log_diario('Executando '+Dir + '\cacic2.exe /ip_serv_cacic=' + v_ip_serv_cacic); + log_diario('Executando '+g_oCacic.getCacicPath + 'cacic2.exe /ip_serv_cacic=' + v_ip_serv_cacic); // Caso tenha havido download de agentes principais, executar coletas imediatamente... if (bool_download_CACIC2) then - WinExec(PChar(Dir + '\cacic2.exe /ip_serv_cacic=' + v_ip_serv_cacic+ ' /execute'), SW_HIDE) + WinExec(PChar(g_oCacic.getCacicPath + 'cacic2.exe /ip_serv_cacic=' + v_ip_serv_cacic+ ' /execute'), SW_HIDE) else - WinExec(PChar(Dir + '\cacic2.exe /ip_serv_cacic=' + v_ip_serv_cacic ), SW_HIDE); + WinExec(PChar(g_oCacic.getCacicPath + 'cacic2.exe /ip_serv_cacic=' + v_ip_serv_cacic ), SW_HIDE); End; end; diff --git a/col_anvi/col_anvi.dpr b/col_anvi/col_anvi.dpr index 9ecb205..8ed667f 100755 --- a/col_anvi/col_anvi.dpr +++ b/col_anvi/col_anvi.dpr @@ -26,16 +26,9 @@ uses TLHELP32, ShellAPI, PJVersionInfo, - DCPcrypt2, - DCPrijndael, - DCPbase64, CACIC_Library in '..\CACIC_Library.pas'; -var p_path_cacic, - v_CipherKey, - v_IV, - v_strCipherClosed, - v_DatFileName : String; +var v_strCipherClosed : String; var v_Debugs : boolean; @@ -45,11 +38,6 @@ var v_tstrCipherOpened, var g_oCacic : TCACIC; -// Some constants that are dependant on the cipher being used -// Assuming MCRYPT_RIJNDAEL_128 (i.e., 128bit blocksize, 256bit keysize) -const KeySize = 32; // 32 bytes = 256 bits - BlockSize = 16; // 16 bytes = 128 bits - function VerFmt(const MS, LS: DWORD): string; // Format the version number from the given DWORDs containing the info begin @@ -57,24 +45,14 @@ begin [HiWord(MS), LoWord(MS), HiWord(LS), LoWord(LS)]) end; -{ TMainForm } -{ TMainForm } -function HomeDrive : string; -var -WinDir : array [0..144] of char; -begin -GetWindowsDirectory (WinDir, 144); -Result := StrPas (WinDir); -end; - procedure log_diario(strMsg : String); var HistoricoLog : TextFile; strDataArqLocal, strDataAtual : string; begin try - FileSetAttr (p_path_cacic + 'cacic2.log',0); // Retira os atributos do arquivo para evitar o erro FILE ACCESS DENIED em máquinas 2000 - AssignFile(HistoricoLog,p_path_cacic + 'cacic2.log'); {Associa o arquivo a uma variável do tipo TextFile} + FileSetAttr (g_oCacic.getCacicPath + '\cacic2.log',0); // Retira os atributos do arquivo para evitar o erro FILE ACCESS DENIED em máquinas 2000 + AssignFile(HistoricoLog,g_oCacic.getCacicPath + '\cacic2.log'); {Associa o arquivo a uma variável do tipo TextFile} {$IOChecks off} Reset(HistoricoLog); {Abre o arquivo texto} {$IOChecks on} @@ -84,7 +62,7 @@ begin Append(HistoricoLog); Writeln(HistoricoLog,FormatDateTime('dd/mm hh:nn:ss : ', Now) + '======================> Iniciando o Log do CACIC <======================='); end; - DateTimeToString(strDataArqLocal, 'yyyymmdd', FileDateToDateTime(Fileage(p_path_cacic + 'cacic2.log'))); + 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... begin @@ -127,92 +105,6 @@ begin end; end; - -// Encrypt a string and return the Base64 encoded result -function EnCrypt(p_Data : String) : String; -var - l_Cipher : TDCP_rijndael; - l_Data, l_Key, l_IV : string; -begin - Try - // Pad Key, IV and Data with zeros as appropriate - l_Key := PadWithZeros(v_CipherKey,KeySize); - l_IV := PadWithZeros(v_IV,BlockSize); - l_Data := PadWithZeros(p_Data,BlockSize); - - // Create the cipher and initialise according to the key length - l_Cipher := TDCP_rijndael.Create(nil); - if Length(v_CipherKey) <= 16 then - l_Cipher.Init(l_Key[1],128,@l_IV[1]) - else if Length(v_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); - Except - log_diario('Erro no Processo de Criptografia'); - End; -end; - -function DeCrypt(p_Data : String) : String; -var - l_Cipher : TDCP_rijndael; - l_Data, l_Key, l_IV : string; -begin - Try - // Pad Key and IV with zeros as appropriate - l_Key := PadWithZeros(v_CipherKey,KeySize); - l_IV := PadWithZeros(v_IV,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(v_CipherKey) <= 16 then - l_Cipher.Init(l_Key[1],128,@l_IV[1]) - else if Length(v_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; - Except - log_diario('Erro no Processo de Decriptografia'); - End; -end; - -Function Implode(p_Array : TStrings ; p_Separador : String) : String; -var intAux : integer; - strAux : string; -Begin -//log_diario('IMPLODE - Tamanho de p_Array='+inttostr(p_array.Count)); - strAux := ''; - For intAux := 0 To p_Array.Count -1 do - Begin - if (strAux<>'') then strAux := strAux + p_Separador; - strAux := strAux + p_Array[intAux]; - End; - Result := strAux; -end; - Procedure CipherClose(p_DatFileName : string; p_tstrCipherOpened : TStrings); var v_strCipherOpenImploded : string; v_DatFile : TextFile; @@ -225,50 +117,14 @@ begin Rewrite (v_DatFile); Append(v_DatFile); - //v_Cipher := TDCP_rijndael.Create(nil); - //v_Cipher.InitStr(v_CipherKey,TDCP_md5); - v_strCipherOpenImploded := Implode(p_tstrCipherOpened,'=CacicIsFree='); -// v_strCipherClosed := v_Cipher.EncryptString(v_strCipherOpenImploded); - v_strCipherClosed := EnCrypt(v_strCipherOpenImploded); -// v_Cipher.Burn; -// v_Cipher.Free; + v_strCipherOpenImploded := g_oCacic.implode(p_tstrCipherOpened,g_oCacic.getSeparatorKey); + v_strCipherClosed := g_oCacic.enCrypt(v_strCipherOpenImploded); Writeln(v_DatFile,v_strCipherClosed); {Grava a string Texto no arquivo texto} CloseFile(v_DatFile); except end; end; -Function Explode(Texto, Separador : String) : TStrings; -var - strItem : String; - ListaAuxUTILS : TStrings; - NumCaracteres, - TamanhoSeparador, - I : Integer; -Begin - ListaAuxUTILS := TStringList.Create; - strItem := ''; - NumCaracteres := Length(Texto); - TamanhoSeparador := Length(Separador); - I := 1; - While I <= NumCaracteres Do - Begin - If (Copy(Texto,I,TamanhoSeparador) = Separador) or (I = NumCaracteres) Then - Begin - if (I = NumCaracteres) then strItem := strItem + Texto[I]; - ListaAuxUTILS.Add(trim(strItem)); - strItem := ''; - I := I + (TamanhoSeparador-1); - end - Else - strItem := strItem + Texto[I]; - - I := I + 1; - End; - Explode := ListaAuxUTILS; -end; - - Function CipherOpen(p_DatFileName : string) : TStrings; var v_DatFile : TextFile; v_strCipherOpened, @@ -290,12 +146,12 @@ begin Readln(v_DatFile,v_strCipherClosed); while not EOF(v_DatFile) do Readln(v_DatFile,v_strCipherClosed); CloseFile(v_DatFile); - v_strCipherOpened:= DeCrypt(v_strCipherClosed); + v_strCipherOpened:= g_oCacic.deCrypt(v_strCipherClosed); end; if (trim(v_strCipherOpened)<>'') then - Result := explode(v_strCipherOpened,'=CacicIsFree=') + Result := g_oCacic.explode(v_strCipherOpened,g_oCacic.getSeparatorKey) else - Result := explode('Configs.ID_SO=CacicIsFree='+ g_oCacic.getWindowsStrId() +'=CacicIsFree=Configs.Endereco_WS=CacicIsFree=/cacic2/ws/','=CacicIsFree='); + Result := g_oCacic.explode('Configs.ID_SO'+g_oCacic.getSeparatorKey+ g_oCacic.getWindowsStrId() + g_oCacic.getSeparatorKey + 'Configs.Endereco_WS'+g_oCacic.getSeparatorKey+'/cacic2/ws/',g_oCacic.getSeparatorKey); if Result.Count mod 2 <> 0 then Result.Add(''); @@ -349,7 +205,7 @@ var RegEditGet: TRegistry; begin try Result := ''; - ListaAuxGet := Explode(Chave, '\'); + ListaAuxGet := g_oCacic.explode(Chave, '\'); strRootKey := ListaAuxGet[0]; For I := 1 To ListaAuxGet.Count - 2 Do strKey := strKey + ListaAuxGet[I] + '\'; @@ -454,7 +310,7 @@ begin If FileExists(strDirTrend + '\filter32.vxd') Then Begin // Em máquinas Windows 9X a versão do engine e do pattern não são gravadas no registro. Tenho que pegar direto dos arquivos. - Lista2_RCO := Explode(getVersionInfo(strDirTrend + 'filter32.vxd'), '.'); // Pego só os dois primeiros dígitos. Por exemplo: 6.640.0.1001 vira 6.640. + Lista2_RCO := g_oCacic.explode(getVersionInfo(strDirTrend + 'filter32.vxd'), '.'); // Pego só os dois primeiros dígitos. Por exemplo: 6.640.0.1001 vira 6.640. nu_versao_engine := Lista2_RCO[0] + '.' + Lista2_RCO[1]; Lista2_RCO.Free; end @@ -517,24 +373,25 @@ begin SetValorDatMemoria('Col_Anvi.te_servidor' , te_servidor , v_tstrCipherOpened1); SetValorDatMemoria('Col_Anvi.in_ativo' , in_ativo , v_tstrCipherOpened1); SetValorDatMemoria('Col_Anvi.UVC' , UVC , v_tstrCipherOpened1); - CipherClose(p_path_cacic + 'temp\col_anvi.dat' , v_tstrCipherOpened1); + CipherClose(g_oCacic.getCacicPath + '\temp\col_anvi.dat' , v_tstrCipherOpened1); end else Begin SetValorDatMemoria('Col_Anvi.nada', 'nada', v_tstrCipherOpened1); - CipherClose(p_path_cacic + 'temp\col_anvi.dat', v_tstrCipherOpened1); + CipherClose(g_oCacic.getCacicPath + '\temp\col_anvi.dat', v_tstrCipherOpened1); End; Except Begin SetValorDatMemoria('Col_Anvi.nada', 'nada', v_tstrCipherOpened1); SetValorDatMemoria('Col_Anvi.Fim', '99999999', v_tstrCipherOpened1); - CipherClose(p_path_cacic + 'temp\col_anvi.dat', v_tstrCipherOpened1); + CipherClose(g_oCacic.getCacicPath + '\temp\col_anvi.dat', v_tstrCipherOpened1); End; End; end; var tstrTripa1 : TStrings; intAux : integer; + v_path_cacic : String; const CACIC_APP_NAME = 'col_anvi'; @@ -544,50 +401,38 @@ begin if( not g_oCacic.isAppRunning( CACIC_APP_NAME ) ) then if (ParamCount>0) then Begin - For intAux := 1 to ParamCount do - Begin - if LowerCase(Copy(ParamStr(intAux),1,13)) = '/p_cipherkey=' then - v_CipherKey := Trim(Copy(ParamStr(intAux),14,Length((ParamStr(intAux))))); + //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] + '\'; + + 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); - if (trim(v_CipherKey)<>'') then + v_tstrCipherOpened1 := TStrings.Create; + v_tstrCipherOpened1 := CipherOpen(g_oCacic.getCacicPath + 'temp\col_anvi.dat'); + + Try + Executa_Col_Anvi; + Except Begin - //Pegarei o nível anterior do diretório, que deve ser, por exemplo \Cacic, para leitura do cacic2.ini - tstrTripa1 := explode(ExtractFilePath(ParamStr(0)),'\'); - p_path_cacic := ''; - For intAux := 0 to tstrTripa1.Count -2 do - begin - p_path_cacic := p_path_cacic + tstrTripa1[intAux] + '\'; - end; - - v_Debugs := false; - if DirectoryExists(p_path_cacic + 'Temp\Debugs') then - Begin - if (FormatDateTime('ddmmyyyy', GetFolderDate(p_path_cacic + 'Temp\Debugs')) = FormatDateTime('ddmmyyyy', date)) then - Begin - v_Debugs := true; - log_diario('Pasta "' + p_path_cacic + 'Temp\Debugs" com data '+FormatDateTime('dd-mm-yyyy', GetFolderDate(p_path_cacic + 'Temp\Debugs'))+' encontrada. DEBUG ativado.'); - End; - End; - - // A chave AES foi obtida no parâmetro p_CipherKey. Recomenda-se que cada empresa altere a sua chave. - v_IV := 'abcdefghijklmnop'; - v_DatFileName := p_path_cacic + 'cacic2.dat'; - v_tstrCipherOpened := TStrings.Create; - v_tstrCipherOpened := CipherOpen(v_DatFileName); - - v_tstrCipherOpened1 := TStrings.Create; - v_tstrCipherOpened1 := CipherOpen(p_path_cacic + 'temp\col_anvi.dat'); - - Try - Executa_Col_Anvi; - Except - Begin - SetValorDatMemoria('Col_Anvi.nada', 'nada', v_tstrCipherOpened1); - CipherClose(p_path_cacic + 'temp\col_anvi.dat', v_tstrCipherOpened1); - End; - End; + SetValorDatMemoria('Col_Anvi.nada', 'nada', v_tstrCipherOpened1); + CipherClose(g_oCacic.getCacicPath + 'temp\col_anvi.dat', v_tstrCipherOpened1); End; + End; End; g_oCacic.Free(); end. diff --git a/col_comp/col_comp.dpr b/col_comp/col_comp.dpr index ba585a2..740802d 100755 --- a/col_comp/col_comp.dpr +++ b/col_comp/col_comp.dpr @@ -23,56 +23,23 @@ uses SysUtils, Classes, Registry, - DCPcrypt2, - DCPrijndael, - DCPbase64, CACIC_Library in '..\CACIC_Library.pas'; -var p_path_cacic : string; - v_CipherKey, - v_IV, - v_strCipherClosed, - v_DatFileName : String; +var v_strCipherClosed : String; var v_tstrCipherOpened, v_tstrCipherOpened1 : TStrings; var g_oCacic : TCACIC; -// Some constants that are dependant on the cipher being used -// Assuming MCRYPT_RIJNDAEL_128 (i.e., 128bit blocksize, 256bit keysize) -const KeySize = 32; // 32 bytes = 256 bits - BlockSize = 16; // 16 bytes = 128 bits - -function HomeDrive : string; -var -WinDir : array [0..144] of char; -begin -GetWindowsDirectory (WinDir, 144); -Result := StrPas (WinDir); -end; - -Function Implode(p_Array : TStrings ; p_Separador : String) : String; -var intAux : integer; - strAux : string; -Begin - strAux := ''; - For intAux := 0 To p_Array.Count -1 do - Begin - if (strAux<>'') then strAux := strAux + p_Separador; - strAux := strAux + p_Array[intAux]; - End; - Implode := strAux; -end; - procedure log_diario(strMsg : String); var HistoricoLog : TextFile; strDataArqLocal, strDataAtual : string; begin try - FileSetAttr (p_path_cacic + 'cacic2.log',0); // Retira os atributos do arquivo para evitar o erro FILE ACCESS DENIED em máquinas 2000 - AssignFile(HistoricoLog,p_path_cacic + 'cacic2.log'); {Associa o arquivo a uma variável do tipo TextFile} + FileSetAttr (g_oCacic.getCacicPath + 'cacic2.log',0); // Retira os atributos do arquivo para evitar o erro FILE ACCESS DENIED em máquinas 2000 + AssignFile(HistoricoLog,g_oCacic.getCacicPath + 'cacic2.log'); {Associa o arquivo a uma variável do tipo TextFile} {$IOChecks off} Reset(HistoricoLog); {Abre o arquivo texto} {$IOChecks on} @@ -82,7 +49,7 @@ begin Append(HistoricoLog); Writeln(HistoricoLog,FormatDateTime('dd/mm hh:nn:ss : ', Now) + '======================> Iniciando o Log do CACIC <======================='); end; - DateTimeToString(strDataArqLocal, 'yyyymmdd', FileDateToDateTime(Fileage(p_path_cacic + 'cacic2.log'))); + 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... begin @@ -98,92 +65,6 @@ begin log_diario('Erro na gravação do log!'); end; end; -// Pad a string with zeros so that it is a multiple of size -function PadWithZeros(const str : string; size : integer) : string; -var - origsize, i : integer; -begin - Result := str; - origsize := Length(Result); - if ((origsize mod size) <> 0) or (origsize = 0) then - begin - SetLength(Result,((origsize div size)+1)*size); - for i := origsize+1 to Length(Result) do - Result[i] := #0; - end; -end; - - -// Encrypt a string and return the Base64 encoded result -function EnCrypt(p_Data : String) : String; -var - l_Cipher : TDCP_rijndael; - l_Data, l_Key, l_IV : string; -begin - Try - // Pad Key, IV and Data with zeros as appropriate - l_Key := PadWithZeros(v_CipherKey,KeySize); - l_IV := PadWithZeros(v_IV,BlockSize); - l_Data := PadWithZeros(p_Data,BlockSize); - - // Create the cipher and initialise according to the key length - l_Cipher := TDCP_rijndael.Create(nil); - if Length(v_CipherKey) <= 16 then - l_Cipher.Init(l_Key[1],128,@l_IV[1]) - else if Length(v_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); - Except - log_diario('Erro no Processo de Criptografia'); - End; -end; - -function DeCrypt(p_Data : String) : String; -var - l_Cipher : TDCP_rijndael; - l_Data, l_Key, l_IV : string; -begin - Try - // Pad Key and IV with zeros as appropriate - l_Key := PadWithZeros(v_CipherKey,KeySize); - l_IV := PadWithZeros(v_IV,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(v_CipherKey) <= 16 then - l_Cipher.Init(l_Key[1],128,@l_IV[1]) - else if Length(v_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; - Except - log_diario('Erro no Processo de Decriptografia'); - End; -end; Function CipherClose(p_DatFileName : string; p_tstrCipherOpened : TStrings) : String; var v_strCipherOpenImploded : string; @@ -197,45 +78,14 @@ begin Rewrite (v_DatFile); Append(v_DatFile); - v_strCipherOpenImploded := Implode(p_tstrCipherOpened,'=CacicIsFree='); - v_strCipherClosed := EnCrypt(v_strCipherOpenImploded); + v_strCipherOpenImploded := g_oCacic.implode(p_tstrCipherOpened,g_oCacic.getSeparatorKey); + v_strCipherClosed := g_oCacic.enCrypt(v_strCipherOpenImploded); Writeln(v_DatFile,v_strCipherClosed); {Grava a string Texto no arquivo texto} CloseFile(v_DatFile); except end; end; -Function Explode(Texto, Separador : String) : TStrings; -var - strItem : String; - ListaAuxUTILS : TStrings; - NumCaracteres, - TamanhoSeparador, - I : Integer; -Begin - ListaAuxUTILS := TStringList.Create; - strItem := ''; - NumCaracteres := Length(Texto); - TamanhoSeparador := Length(Separador); - I := 1; - While I <= NumCaracteres Do - Begin - If (Copy(Texto,I,TamanhoSeparador) = Separador) or (I = NumCaracteres) Then - Begin - if (I = NumCaracteres) then strItem := strItem + Texto[I]; - ListaAuxUTILS.Add(trim(strItem)); - strItem := ''; - I := I + (TamanhoSeparador-1); - end - Else - strItem := strItem + Texto[I]; - - I := I + 1; - End; - Explode := ListaAuxUTILS; -end; - - Function CipherOpen(p_DatFileName : string) : TStrings; var v_DatFile : TextFile; v_strCipherOpened, @@ -257,12 +107,12 @@ begin Readln(v_DatFile,v_strCipherClosed); while not EOF(v_DatFile) do Readln(v_DatFile,v_strCipherClosed); CloseFile(v_DatFile); - v_strCipherOpened:= DeCrypt(v_strCipherClosed); + v_strCipherOpened:= g_oCacic.deCrypt(v_strCipherClosed); end; if (trim(v_strCipherOpened)<>'') then - Result := explode(v_strCipherOpened,'=CacicIsFree=') + Result := g_oCacic.explode(v_strCipherOpened,g_oCacic.getSeparatorKey) else - Result := explode('Configs.ID_SO=CacicIsFree='+ g_oCacic.getWindowsStrId() +'=CacicIsFree=Configs.Endereco_WS=CacicIsFree=/cacic2/ws/','=CacicIsFree='); + Result := g_oCacic.explode('Configs.ID_SO'+g_oCacic.getSeparatorKey+g_oCacic.getWindowsStrId() +g_oCacic.getSeparatorKey+'Configs.Endereco_WS'+g_oCacic.getSeparatorKey+'/cacic2/ws/',g_oCacic.getSeparatorKey); if Result.Count mod 2 <> 0 then @@ -322,7 +172,7 @@ var RegEditGet: TRegistry; begin try Result := ''; - ListaAuxGet := Explode(Chave, '\'); + ListaAuxGet := g_oCacic.explode(Chave, '\'); strRootKey := ListaAuxGet[0]; For I := 1 To ListaAuxGet.Count - 2 Do strKey := strKey + ListaAuxGet[I] + '\'; @@ -475,68 +325,55 @@ Begin (strTripaDados <> '') Then Begin SetValorDatMemoria('Col_Comp.UVC', strTripaDados, v_tstrCipherOpened1); - CipherClose(p_path_cacic + 'temp\col_comp.dat', v_tstrCipherOpened1); + CipherClose(g_oCacic.getCacicPath + 'temp\col_comp.dat', v_tstrCipherOpened1); End else SetValorDatMemoria('Col_Comp.nada', 'nada', v_tstrCipherOpened1); - CipherClose(p_path_cacic + 'temp\col_comp.dat', v_tstrCipherOpened1); + CipherClose(g_oCacic.getCacicPath + 'temp\col_comp.dat', v_tstrCipherOpened1); End; Except Begin SetValorDatMemoria('Col_Comp.nada', 'nada', v_tstrCipherOpened1); SetValorDatMemoria('Col_Comp.Fim', '99999999', v_tstrCipherOpened1); - CipherClose(p_path_cacic + 'temp\col_comp.dat', v_tstrCipherOpened1); + CipherClose(g_oCacic.getCacicPath + 'temp\col_comp.dat', v_tstrCipherOpened1); End; End; end; var tstrTripa1 : TStrings; intAux : integer; + v_path_cacic : String; + const CACIC_APP_NAME = 'col_comp'; -var - hwind:HWND; - begin g_oCacic := TCACIC.Create(); if( not g_oCacic.isAppRunning( CACIC_APP_NAME ) ) then if (ParamCount>0) then Begin - For intAux := 1 to ParamCount do - Begin - if LowerCase(Copy(ParamStr(intAux),1,13)) = '/p_cipherkey=' then - v_CipherKey := Trim(Copy(ParamStr(intAux),14,Length((ParamStr(intAux))))); - End; - - if (trim(v_CipherKey)<>'') then - Begin - //Pegarei o nível anterior do diretório, que deve ser, por exemplo \Cacic, para leitura do cacic2.ini - tstrTripa1 := explode(ExtractFilePath(ParamStr(0)),'\'); - p_path_cacic := ''; - For intAux := 0 to tstrTripa1.Count -2 do - begin - p_path_cacic := p_path_cacic + tstrTripa1[intAux] + '\'; - end; - - // A chave AES foi obtida no parâmetro p_CipherKey. Recomenda-se que cada empresa altere a sua chave. - v_IV := 'abcdefghijklmnop'; - v_DatFileName := p_path_cacic + 'cacic2.dat'; - v_tstrCipherOpened := TStrings.Create; - v_tstrCipherOpened := CipherOpen(v_DatFileName); - - v_tstrCipherOpened1 := TStrings.Create; - v_tstrCipherOpened1 := CipherOpen(p_path_cacic + 'temp\col_comp.dat'); - - Try - Executa_Col_comp; - Except - SetValorDatMemoria('Col_Comp.nada', 'nada', v_tstrCipherOpened1); - CipherClose(p_path_cacic + 'temp\col_comp.dat', v_tstrCipherOpened1); - End; - Halt(0); - End; + //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] + '\'; + + g_oCacic.setCacicPath(v_path_cacic); + + v_tstrCipherOpened := TStrings.Create; + v_tstrCipherOpened := CipherOpen(g_oCacic.getDatFileName); + + v_tstrCipherOpened1 := TStrings.Create; + v_tstrCipherOpened1 := CipherOpen(g_oCacic.getCacicPath + 'temp\col_comp.dat'); + + Try + Executa_Col_comp; + Except + SetValorDatMemoria('Col_Comp.nada', 'nada', v_tstrCipherOpened1); + CipherClose(g_oCacic.getCacicPath + 'temp\col_comp.dat', v_tstrCipherOpened1); + End; + Halt(0); End; g_oCacic.Free(); end. diff --git a/col_hard/col_hard.dpr b/col_hard/col_hard.dpr index 08e7e3d..7e19c8f 100644 --- a/col_hard/col_hard.dpr +++ b/col_hard/col_hard.dpr @@ -35,26 +35,22 @@ uses MSI_MEDIA, MSI_NETWORK, MSI_XML_Reports, - DCPcrypt2, - DCPrijndael, - DCPbase64, PJVersionInfo, CACIC_Library in '..\CACIC_Library.pas'; -var p_path_cacic, v_mensagem : string; - v_debugs : boolean; - v_CipherKey, - v_IV, - v_strCipherClosed, - v_DatFileName : String; - -var v_tstrCipherOpened, - v_tstrCipherOpened1 : TStrings; +var + v_path_cacic, + v_mensagem, + v_strCipherClosed : String; + v_debugs : boolean; + v_tstrCipherOpened, + v_tstrCipherOpened1, + tstrTripa1 : TStrings; + intAux : integer; + g_oCacic : TCACIC; -// Some constants that are dependant on the cipher being used -// Assuming MCRYPT_RIJNDAEL_128 (i.e., 128bit blocksize, 256bit keysize) -const KeySize = 32; // 32 bytes = 256 bits - BlockSize = 16; // 16 bytes = 128 bits +const + CACIC_APP_NAME = 'col_hard'; // Dica baixada de http://www.marcosdellantonio.net/2007/06/14/operador-if-ternario-em-delphi-e-c/ // Fiz isso para não ter que acrescentar o componente Math ao USES! @@ -65,50 +61,15 @@ function iif(condicao : boolean; resTrue, resFalse : Variant) : Variant; else Result := resFalse; End; - -function HomeDrive : string; -var -WinDir : array [0..144] of char; -begin -GetWindowsDirectory (WinDir, 144); -Result := StrPas (WinDir); -end; - -Function Implode(p_Array : TStrings ; p_Separador : String) : String; -var intAux : integer; - strAux : string; -Begin - strAux := ''; - For intAux := 0 To p_Array.Count -1 do - Begin - if (strAux<>'') then strAux := strAux + p_Separador; - strAux := strAux + p_Array[intAux]; - End; - Implode := strAux; -end; -// Pad a string with zeros so that it is a multiple of size -function PadWithZeros(const str : string; size : integer) : string; -var - origsize, i : integer; -begin - Result := str; - origsize := Length(Result); - if ((origsize mod size) <> 0) or (origsize = 0) then - begin - SetLength(Result,((origsize div size)+1)*size); - for i := origsize+1 to Length(Result) do - Result[i] := #0; - end; -end; procedure log_diario(strMsg : String); var HistoricoLog : TextFile; strDataArqLocal, strDataAtual : string; begin try - FileSetAttr (p_path_cacic + 'cacic2.log',0); // Retira os atributos do arquivo para evitar o erro FILE ACCESS DENIED em máquinas 2000 - AssignFile(HistoricoLog,p_path_cacic + 'cacic2.log'); {Associa o arquivo a uma variável do tipo TextFile} + FileSetAttr (g_oCacic.getCacicPath + 'cacic2.log',0); // Retira os atributos do arquivo para evitar o erro FILE ACCESS DENIED em máquinas 2000 + AssignFile(HistoricoLog,g_oCacic.getCacicPath + 'cacic2.log'); {Associa o arquivo a uma variável do tipo TextFile} {$IOChecks off} Reset(HistoricoLog); {Abre o arquivo texto} {$IOChecks on} @@ -118,7 +79,7 @@ begin Append(HistoricoLog); Writeln(HistoricoLog,FormatDateTime('dd/mm hh:nn:ss : ', Now) + '======================> Iniciando o Log <======================='); end; - DateTimeToString(strDataArqLocal, 'yyyymmdd', FileDateToDateTime(Fileage(p_path_cacic + 'cacic2.log'))); + 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... begin @@ -137,76 +98,6 @@ begin end; -// Encrypt a string and return the Base64 encoded result -function EnCrypt(p_Data : String) : String; -var - l_Cipher : TDCP_rijndael; - l_Data, l_Key, l_IV : string; -begin - Try - // Pad Key, IV and Data with zeros as appropriate - l_Key := PadWithZeros(v_CipherKey,KeySize); - l_IV := PadWithZeros(v_IV,BlockSize); - l_Data := PadWithZeros(p_Data,BlockSize); - - // Create the cipher and initialise according to the key length - l_Cipher := TDCP_rijndael.Create(nil); - if Length(v_CipherKey) <= 16 then - l_Cipher.Init(l_Key[1],128,@l_IV[1]) - else if Length(v_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); - Except - log_diario('Erro no Processo de Criptografia'); - End; -end; - -function DeCrypt(p_Data : String) : String; -var - l_Cipher : TDCP_rijndael; - l_Data, l_Key, l_IV : string; -begin - Try - // Pad Key and IV with zeros as appropriate - l_Key := PadWithZeros(v_CipherKey,KeySize); - l_IV := PadWithZeros(v_IV,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(v_CipherKey) <= 16 then - l_Cipher.Init(l_Key[1],128,@l_IV[1]) - else if Length(v_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; - Except - log_diario('Erro no Processo de Decriptografia'); - End; -end; Function CipherClose(p_DatFileName : string; p_tstrCipherOpened : TStrings) : String; var v_strCipherOpenImploded : string; @@ -220,13 +111,8 @@ begin Rewrite (v_DatFile); Append(v_DatFile); - //v_Cipher := TDCP_rijndael.Create(nil); - //v_Cipher.InitStr(v_CipherKey,TDCP_md5); - v_strCipherOpenImploded := Implode(p_tstrCipherOpened,'=CacicIsFree='); - v_strCipherClosed := EnCrypt(v_strCipherOpenImploded); - //v_strCipherClosed := v_Cipher.EncryptString(v_strCipherOpenImploded); - //v_Cipher.Burn; - //v_Cipher.Free; + v_strCipherOpenImploded := g_oCacic.implode(p_tstrCipherOpened,g_oCacic.getSeparatorKey); + v_strCipherClosed := g_oCacic.enCrypt(v_strCipherOpenImploded); Writeln(v_DatFile,v_strCipherClosed); {Grava a string Texto no arquivo texto} @@ -234,94 +120,6 @@ begin except end; end; -function GetWinVer: Integer; -const - { operating system (OS)constants } - cOsUnknown = 0; - cOsWin95 = 1; - cOsWin95OSR2 = 2; // Não implementado. - cOsWin98 = 3; - cOsWin98SE = 4; - cOsWinME = 5; - cOsWinNT = 6; - cOsWin2000 = 7; - cOsXP = 8; -var - osVerInfo: TOSVersionInfo; - majorVer, minorVer: Integer; -begin - Result := cOsUnknown; - { set operating system type flag } - osVerInfo.dwOSVersionInfoSize := SizeOf(TOSVersionInfo); - if GetVersionEx(osVerInfo) then - begin - majorVer := osVerInfo.dwMajorVersion; - minorVer := osVerInfo.dwMinorVersion; - case osVerInfo.dwPlatformId of - VER_PLATFORM_WIN32_NT: { Windows NT/2000 } - begin - if majorVer <= 4 then - Result := cOsWinNT - else if (majorVer = 5) and (minorVer = 0) then - Result := cOsWin2000 - else if (majorVer = 5) and (minorVer = 1) then - Result := cOsXP - else - Result := cOsUnknown; - end; - VER_PLATFORM_WIN32_WINDOWS: { Windows 9x/ME } - begin - if (majorVer = 4) and (minorVer = 0) then - Result := cOsWin95 - else if (majorVer = 4) and (minorVer = 10) then - begin - if osVerInfo.szCSDVersion[1] = 'A' then - Result := cOsWin98SE - else - Result := cOsWin98; - end - else if (majorVer = 4) and (minorVer = 90) then - Result := cOsWinME - else - Result := cOsUnknown; - end; - else - Result := cOsUnknown; - end; - end - else - Result := cOsUnknown; -end; -Function Explode(Texto, Separador : String) : TStrings; -var - strItem : String; - ListaAuxUTILS : TStrings; - NumCaracteres, - TamanhoSeparador, - I : Integer; -Begin - ListaAuxUTILS := TStringList.Create; - strItem := ''; - NumCaracteres := Length(Texto); - TamanhoSeparador := Length(Separador); - I := 1; - While I <= NumCaracteres Do - Begin - If (Copy(Texto,I,TamanhoSeparador) = Separador) or (I = NumCaracteres) Then - Begin - if (I = NumCaracteres) then strItem := strItem + Texto[I]; - ListaAuxUTILS.Add(trim(strItem)); - strItem := ''; - I := I + (TamanhoSeparador-1); - end - Else - strItem := strItem + Texto[I]; - - I := I + 1; - End; - Explode := ListaAuxUTILS; -end; - Function CipherOpen(p_DatFileName : string) : TStrings; var v_DatFile : TextFile; @@ -344,12 +142,12 @@ begin Readln(v_DatFile,v_strCipherClosed); while not EOF(v_DatFile) do Readln(v_DatFile,v_strCipherClosed); CloseFile(v_DatFile); - v_strCipherOpened:= DeCrypt(v_strCipherClosed); + v_strCipherOpened:= g_oCacic.deCrypt(v_strCipherClosed); end; if (trim(v_strCipherOpened)<>'') then - Result := explode(v_strCipherOpened,'=CacicIsFree=') + Result := g_oCacic.explode(v_strCipherOpened,g_oCacic.getSeparatorKey) else - Result := explode('Configs.ID_SO=CacicIsFree='+inttostr(GetWinVer)+'=CacicIsFree=Configs.Endereco_WS=CacicIsFree=/cacic2/ws/','=CacicIsFree='); + Result := g_oCacic.explode('Configs.ID_SO' + g_oCacic.getSeparatorKey + g_oCacic.getWindowsStrId + g_oCacic.getSeparatorKey + 'Configs.Endereco_WS'+g_oCacic.getSeparatorKey+'/cacic2/ws/',g_oCacic.getSeparatorKey); if Result.Count mod 2 <> 0 then Result.Add(''); @@ -404,7 +202,7 @@ begin Result := ''; if (p_SectionName <> '') then Begin - v_array_SectionName := explode(p_SectionName,'/'); + v_array_SectionName := g_oCacic.explode(p_SectionName,'/'); v_array_SectionName_Count := v_array_SectionName.Count; End else v_array_SectionName_Count := 0; @@ -485,7 +283,7 @@ var strDataArqLocal, strDataAtual, v_file_debugs : string; begin try - v_file_debugs := p_path_cacic + '\Temp\Debugs\debug_'+StringReplace(ExtractFileName(StrUpper(PChar(ParamStr(0)))),'.EXE','',[rfReplaceAll])+'.txt'; + v_file_debugs := g_oCacic.getCacicPath + 'Temp\Debugs\debug_'+StringReplace(ExtractFileName(StrUpper(PChar(ParamStr(0)))),'.EXE','',[rfReplaceAll])+'.txt'; FileSetAttr (v_file_debugs,0); // Retira os atributos do arquivo para evitar o erro FILE ACCESS DENIED em máquinas 2000 AssignFile(DebugsFile,v_file_debugs); {Associa o arquivo a uma variável do tipo TextFile} @@ -667,7 +465,7 @@ Begin v_conta_EXCECOES := 0; if (p_excecao <> '') then Begin - tstrEXCECOES := Explode(p_excecao,','); // Excecoes a serem tratadas + tstrEXCECOES := g_oCacic.explode(p_excecao,','); // Excecoes a serem tratadas for intAux1 := 0 to tstrEXCECOES.Count-1 Do Begin if (rat(tstrEXCECOES[intAux1],p_mac) > 0) then @@ -739,10 +537,8 @@ var v_te_cpu_fabricante, v_cpu_freq : TStrings; v_registry : TRegistry; - oCacic : TCACIC; - begin - oCacic := TCACIC.Create(); + g_oCacic := TCACIC.Create(); Try SetValorDatMemoria('Col_Hard.Inicio', FormatDateTime('hh:nn:ss', Now), v_tstrCipherOpened1); v_Report := TStringList.Create; @@ -1084,7 +880,7 @@ begin Try // Monto a string que será comparada com o valor armazenado no registro. v_mensagem := 'Montando pacote para comparações...'; - UVC := oCacic.trimEspacosExcedentes(v_Tripa_TCPIP + ';' + + UVC := g_oCacic.trimEspacosExcedentes(v_Tripa_TCPIP + ';' + v_Tripa_CPU + ';' + v_Tripa_CDROM + ';' + v_te_mem_ram_desc + ';' + @@ -1115,30 +911,30 @@ begin // e, se não houver problemas durante esse procedimento, atualizo as // informações no registro. If (GetValorDatMemoria('Configs.IN_COLETA_FORCADA_HARD',v_tstrCipherOpened)='S') or - (oCacic.trimEspacosExcedentes(UVC) <> oCacic.trimEspacosExcedentes(ValorChaveRegistro)) Then + (g_oCacic.trimEspacosExcedentes(UVC) <> g_oCacic.trimEspacosExcedentes(ValorChaveRegistro)) Then Begin Try //Envio via rede para ao Agente Gerente, para gravação no BD. - SetValorDatMemoria('Col_Hard.te_Tripa_TCPIP' , oCacic.trimEspacosExcedentes( v_Tripa_TCPIP ), v_tstrCipherOpened1); - SetValorDatMemoria('Col_Hard.te_Tripa_CPU' , oCacic.trimEspacosExcedentes( v_Tripa_CPU ), v_tstrCipherOpened1); - SetValorDatMemoria('Col_Hard.te_Tripa_CDROM' , oCacic.trimEspacosExcedentes( v_Tripa_CDROM ), v_tstrCipherOpened1); - SetValorDatMemoria('Col_Hard.te_placa_mae_fabricante' , oCacic.trimEspacosExcedentes( v_te_placa_mae_fabricante ) , v_tstrCipherOpened1); - SetValorDatMemoria('Col_Hard.te_placa_mae_desc' , oCacic.trimEspacosExcedentes( v_te_placa_mae_desc ) , v_tstrCipherOpened1); - SetValorDatMemoria('Col_Hard.qt_mem_ram' , oCacic.trimEspacosExcedentes( IntToStr(v_qt_mem_ram) ) , v_tstrCipherOpened1); - SetValorDatMemoria('Col_Hard.te_mem_ram_desc' , oCacic.trimEspacosExcedentes( v_te_mem_ram_desc ) , v_tstrCipherOpened1); - SetValorDatMemoria('Col_Hard.te_bios_desc' , oCacic.trimEspacosExcedentes( v_te_bios_desc ) , v_tstrCipherOpened1); - SetValorDatMemoria('Col_Hard.te_bios_data' , oCacic.trimEspacosExcedentes( v_te_bios_data ) , v_tstrCipherOpened1); - SetValorDatMemoria('Col_Hard.te_bios_fabricante' , oCacic.trimEspacosExcedentes( v_te_bios_fabricante ) , v_tstrCipherOpened1); - SetValorDatMemoria('Col_Hard.qt_placa_video_cores' , oCacic.trimEspacosExcedentes( v_qt_placa_video_cores ) , v_tstrCipherOpened1); - SetValorDatMemoria('Col_Hard.te_placa_video_desc' , oCacic.trimEspacosExcedentes( v_te_placa_video_desc ) , v_tstrCipherOpened1); - SetValorDatMemoria('Col_Hard.qt_placa_video_mem' , oCacic.trimEspacosExcedentes( v_qt_placa_video_mem ) , v_tstrCipherOpened1); - SetValorDatMemoria('Col_Hard.te_placa_video_resolucao', oCacic.trimEspacosExcedentes( v_te_placa_video_resolucao ) , v_tstrCipherOpened1); - SetValorDatMemoria('Col_Hard.te_placa_som_desc' , oCacic.trimEspacosExcedentes( v_te_placa_som_desc ) , v_tstrCipherOpened1); - SetValorDatMemoria('Col_Hard.te_teclado_desc' , oCacic.trimEspacosExcedentes( v_te_teclado_desc ) , v_tstrCipherOpened1); - SetValorDatMemoria('Col_Hard.te_mouse_desc' , oCacic.trimEspacosExcedentes( v_te_mouse_desc ) , v_tstrCipherOpened1); - SetValorDatMemoria('Col_Hard.te_modem_desc' , oCacic.trimEspacosExcedentes( v_te_modem_desc ) , v_tstrCipherOpened1); - SetValorDatMemoria('Col_Hard.UVC' , oCacic.trimEspacosExcedentes( UVC ) , v_tstrCipherOpened1); - CipherClose(p_path_cacic + 'temp\col_hard.dat', v_tstrCipherOpened1); + SetValorDatMemoria('Col_Hard.te_Tripa_TCPIP' , g_oCacic.trimEspacosExcedentes( v_Tripa_TCPIP ), v_tstrCipherOpened1); + SetValorDatMemoria('Col_Hard.te_Tripa_CPU' , g_oCacic.trimEspacosExcedentes( v_Tripa_CPU ), v_tstrCipherOpened1); + SetValorDatMemoria('Col_Hard.te_Tripa_CDROM' , g_oCacic.trimEspacosExcedentes( v_Tripa_CDROM ), v_tstrCipherOpened1); + SetValorDatMemoria('Col_Hard.te_placa_mae_fabricante' , g_oCacic.trimEspacosExcedentes( v_te_placa_mae_fabricante ) , v_tstrCipherOpened1); + SetValorDatMemoria('Col_Hard.te_placa_mae_desc' , g_oCacic.trimEspacosExcedentes( v_te_placa_mae_desc ) , v_tstrCipherOpened1); + SetValorDatMemoria('Col_Hard.qt_mem_ram' , g_oCacic.trimEspacosExcedentes( IntToStr(v_qt_mem_ram) ) , v_tstrCipherOpened1); + SetValorDatMemoria('Col_Hard.te_mem_ram_desc' , g_oCacic.trimEspacosExcedentes( v_te_mem_ram_desc ) , v_tstrCipherOpened1); + SetValorDatMemoria('Col_Hard.te_bios_desc' , g_oCacic.trimEspacosExcedentes( v_te_bios_desc ) , v_tstrCipherOpened1); + SetValorDatMemoria('Col_Hard.te_bios_data' , g_oCacic.trimEspacosExcedentes( v_te_bios_data ) , v_tstrCipherOpened1); + SetValorDatMemoria('Col_Hard.te_bios_fabricante' , g_oCacic.trimEspacosExcedentes( v_te_bios_fabricante ) , v_tstrCipherOpened1); + SetValorDatMemoria('Col_Hard.qt_placa_video_cores' , g_oCacic.trimEspacosExcedentes( v_qt_placa_video_cores ) , v_tstrCipherOpened1); + SetValorDatMemoria('Col_Hard.te_placa_video_desc' , g_oCacic.trimEspacosExcedentes( v_te_placa_video_desc ) , v_tstrCipherOpened1); + SetValorDatMemoria('Col_Hard.qt_placa_video_mem' , g_oCacic.trimEspacosExcedentes( v_qt_placa_video_mem ) , v_tstrCipherOpened1); + SetValorDatMemoria('Col_Hard.te_placa_video_resolucao', g_oCacic.trimEspacosExcedentes( v_te_placa_video_resolucao ) , v_tstrCipherOpened1); + SetValorDatMemoria('Col_Hard.te_placa_som_desc' , g_oCacic.trimEspacosExcedentes( v_te_placa_som_desc ) , v_tstrCipherOpened1); + SetValorDatMemoria('Col_Hard.te_teclado_desc' , g_oCacic.trimEspacosExcedentes( v_te_teclado_desc ) , v_tstrCipherOpened1); + SetValorDatMemoria('Col_Hard.te_mouse_desc' , g_oCacic.trimEspacosExcedentes( v_te_mouse_desc ) , v_tstrCipherOpened1); + SetValorDatMemoria('Col_Hard.te_modem_desc' , g_oCacic.trimEspacosExcedentes( v_te_modem_desc ) , v_tstrCipherOpened1); + SetValorDatMemoria('Col_Hard.UVC' , g_oCacic.trimEspacosExcedentes( UVC ) , v_tstrCipherOpened1); + CipherClose(g_oCacic.getCacicPath + 'temp\col_hard.dat', v_tstrCipherOpened1); Except log_diario('Problema em gravação de dados no DAT!'); End; end @@ -1146,77 +942,60 @@ begin Begin SetValorDatMemoria('Col_Hard.nada','nada', v_tstrCipherOpened1); SetValorDatMemoria('Col_Hard.Fim' , FormatDateTime('hh:nn:ss', Now), v_tstrCipherOpened1); - CipherClose(p_path_cacic + 'temp\col_hard.dat', v_tstrCipherOpened1); + CipherClose(g_oCacic.getCacicPath + 'temp\col_hard.dat', v_tstrCipherOpened1); End; Except Begin SetValorDatMemoria('Col_Hard.nada','nada', v_tstrCipherOpened1); SetValorDatMemoria('Col_Hard.Fim' , '99999999', v_tstrCipherOpened1); - CipherClose(p_path_cacic + 'temp\col_hard.dat', v_tstrCipherOpened1); + CipherClose(g_oCacic.getCacicPath + 'temp\col_hard.dat', v_tstrCipherOpened1); log_diario('Problema na execução => ' + v_mensagem); End; End; - oCacic.Free(); + g_oCacic.Free(); end; -const - CACIC_APP_NAME = 'col_hard'; - -var tstrTripa1 : TStrings; - intAux : integer; - oCacic : TCACIC; - begin - oCacic := TCACIC.Create(); + g_oCacic := TCACIC.Create(); - if( not oCacic.isAppRunning( CACIC_APP_NAME ) ) then + if( not g_oCacic.isAppRunning( CACIC_APP_NAME ) ) then if (ParamCount>0) then - Begin - For intAux := 1 to ParamCount do - Begin - if LowerCase(Copy(ParamStr(intAux),1,13)) = '/p_cipherkey=' then - v_CipherKey := Trim(Copy(ParamStr(intAux),14,Length((ParamStr(intAux))))); - End; - - if (trim(v_CipherKey)<>'') then - Begin - //Pegarei o nível anterior do diretório, que deve ser, por exemplo \Cacic, para leitura do cacic2.ini - tstrTripa1 := explode(ExtractFilePath(ParamStr(0)),'\'); - p_path_cacic := ''; - intAux :=0; - While intAux < tstrTripa1.Count -1 do - begin - p_path_cacic := p_path_cacic + tstrTripa1[intAux] + '\'; - intAux := intAux + 1 - end; - - // A chave AES foi obtida no parâmetro p_CipherKey. Recomenda-se que cada empresa altere a sua chave. - v_IV := 'abcdefghijklmnop'; - v_DatFileName := p_path_cacic + 'cacic2.dat'; - v_tstrCipherOpened := TStrings.Create; - v_tstrCipherOpened := CipherOpen(v_DatFileName); - - v_tstrCipherOpened1 := TStrings.Create; - v_tstrCipherOpened1 := CipherOpen(p_path_cacic + 'temp\col_hard.dat'); - - Try - v_Debugs := false; - if DirectoryExists(p_path_cacic + 'Temp\Debugs') 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 := ''; + intAux :=0; + While intAux < tstrTripa1.Count -1 do + begin + v_path_cacic := v_path_cacic + tstrTripa1[intAux] + '\'; + intAux := intAux + 1 + end; + + g_oCacic.setCacicPath(v_path_cacic); + + v_tstrCipherOpened := TStrings.Create; + v_tstrCipherOpened := CipherOpen(g_oCacic.getDatFileName); + + v_tstrCipherOpened1 := TStrings.Create; + v_tstrCipherOpened1 := CipherOpen(g_oCacic.getCacicPath + 'temp\col_hard.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 - if (FormatDateTime('ddmmyyyy', GetFolderDate(p_path_cacic + 'Temp\Debugs')) = FormatDateTime('ddmmyyyy', date)) then - Begin - v_Debugs := true; - log_diario('Pasta "' + p_path_cacic + 'Temp\Debugs" com data '+FormatDateTime('dd-mm-yyyy', GetFolderDate(p_path_cacic + 'Temp\Debugs'))+' encontrada. DEBUG ativado.'); - End; + 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; - Executa_Col_Hard; - Except - SetValorDatMemoria('Col_Hard.nada', 'nada', v_tstrCipherOpened1); - CipherClose(p_path_cacic + 'temp\col_hard.dat', v_tstrCipherOpened1); - End; - End; + End; + Executa_Col_Hard; + Except + SetValorDatMemoria('Col_Hard.nada', 'nada', v_tstrCipherOpened1); + CipherClose(g_oCacic.getCacicPath + 'temp\col_hard.dat', v_tstrCipherOpened1); + End; End; - oCacic.Free(); + g_oCacic.Free(); end. -- libgit2 0.21.2