From 004d4bae9706fbf6edd7288f9708a10577ce453a Mon Sep 17 00:00:00 2001 From: anderson.peterle@previdencia.gov.br Date: Thu, 2 Apr 2009 15:30:37 +0000 Subject: [PATCH] Implementacao de controles para uso do srCACIC - Suporte Remoto, adequacoes ao funcionamento do agente principal como servico, correcoes diversas. --- CACIC_Library.pas | 16 +++++++++++++++- cacic2.res | Bin 4892 -> 0 bytes cacic_icon_WithoutServer.ico | Bin 0 -> 4286 bytes cacic_icon_raio 32.ico | Bin 0 -> 4286 bytes cacicservice/CACICsvc.cfg | 35 +++++++++++++++++++++++++++++++++++ cacicservice/CACICsvc.dof | 136 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ cacicservice/CACICsvc.dpr | 29 +++++++++++++++++++++++++++++ cacicservice/CACICsvc.exe | Bin 0 -> 422912 bytes cacicservice/CACICsvc.res | Bin 0 -> 5272 bytes cacicservice/CACICsvc.~dpr | 29 +++++++++++++++++++++++++++++ cacicservice/CACICsvcMain.dcu | Bin 0 -> 8566 bytes cacicservice/CACICsvcMain.ddp | Bin 0 -> 51 bytes cacicservice/CACICsvcMain.dfm | 20 ++++++++++++++++++++ cacicservice/CACICsvcMain.pas | 239 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ cacicservice/CACICsvcMain.~ddp | Bin 0 -> 51 bytes cacicservice/CACICsvcMain.~dfm | 20 ++++++++++++++++++++ cacicservice/CACICsvcMain.~pas | 234 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ cacicservice/CACICsvcThread.dcu | Bin 0 -> 1456 bytes cacicservice/CACICsvcThread.pas | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ cacicservice/CACICsvcThread.~pas | 202 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ cacicservice/cacic_service_32x32.ico | Bin 0 -> 4286 bytes chkcacic/FormConfig.dfm | 6 +++--- chkcacic/FormConfig.pas | 2 +- chkcacic/chkcacic.res | Bin 5204 -> 0 bytes chkcacic/main.dfm | 4 ++-- chkcacic/main.pas | 556 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- chksis/chksis.dpr | 105 +++++++++++++++++++++++++++++++++++---------------------------------------------------------------------- chksis/chksis.res | Bin 5156 -> 0 bytes col_anvi/col_anvi.res | Bin 16316 -> 0 bytes col_comp/col_comp.res | Bin 16328 -> 0 bytes col_hard/col_hard.res | Bin 16312 -> 0 bytes col_moni/col_moni.res | Bin 16272 -> 0 bytes col_patr/col_patr.res | Bin 16316 -> 0 bytes col_soft/col_soft.res | Bin 16332 -> 0 bytes col_undi/col_undi.res | Bin 16332 -> 0 bytes ger_cols/ger_cols.dpr | 68 ++++++++++++++++++++++++++++++++++++++++++++++++-------------------- ger_cols/ger_cols.res | Bin 4816 -> 0 bytes ini_cols/ini_cols.res | Bin 6732 -> 0 bytes main.dfm | 174 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------ main.pas | 231 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------------------------------------------------------------------------------------------------- mapa/mapacacic.res | Bin 5140 -> 0 bytes testacrypt/testacrypt.res | Bin 1544 -> 0 bytes vaca/vaca.res | Bin 4828 -> 0 bytes vacon/vacon.res | Bin 4856 -> 0 bytes 44 files changed, 1773 insertions(+), 399 deletions(-) create mode 100755 cacic_icon_WithoutServer.ico create mode 100755 cacic_icon_raio 32.ico create mode 100755 cacicservice/CACICsvc.cfg create mode 100755 cacicservice/CACICsvc.dof create mode 100755 cacicservice/CACICsvc.dpr create mode 100755 cacicservice/CACICsvc.exe create mode 100755 cacicservice/CACICsvc.res create mode 100755 cacicservice/CACICsvc.~dpr create mode 100755 cacicservice/CACICsvcMain.dcu create mode 100755 cacicservice/CACICsvcMain.ddp create mode 100755 cacicservice/CACICsvcMain.dfm create mode 100755 cacicservice/CACICsvcMain.pas create mode 100755 cacicservice/CACICsvcMain.~ddp create mode 100755 cacicservice/CACICsvcMain.~dfm create mode 100755 cacicservice/CACICsvcMain.~pas create mode 100755 cacicservice/CACICsvcThread.dcu create mode 100755 cacicservice/CACICsvcThread.pas create mode 100755 cacicservice/CACICsvcThread.~pas create mode 100755 cacicservice/cacic_service_32x32.ico diff --git a/CACIC_Library.pas b/CACIC_Library.pas index 386e01b..56b4cb7 100644 --- a/CACIC_Library.pas +++ b/CACIC_Library.pas @@ -47,7 +47,7 @@ unit CACIC_Library; interface uses - Windows, SysUtils, StrUtils; + Windows, SysUtils, StrUtils, md5; type @@ -96,6 +96,7 @@ type function isWindowsAdmin(): Boolean; function createSampleProcess(p_cmd: string; p_wait: boolean ): boolean; procedure showTrayIcon(p_visible:boolean); + function GetFileHash(strFileName : String) : String; end; {*------------------------------------------------------------------------------ @@ -531,6 +532,19 @@ begin end; {*------------------------------------------------------------------------------ + Para cálculo de HASH de determinado arquivo. + + @autor: Anderson Peterle + @param p_strFileName - Nome do arquivo para extração do HashCode +-------------------------------------------------------------------------------} +function TCACIC_Windows.GetFileHash(strFileName : String) : String; +Begin + Result := 'Arquivo "'+strFileName+'" Inexistente!'; + if (FileExists(strFileName)) then + Result := MD5Print(MD5File(strFileName)); +End; + +{*------------------------------------------------------------------------------ Mostra ou oculta o cacic na "systray" do windows @autor: Diversos - compilado de vários exemplos obtidos na internet diff --git a/cacic2.res b/cacic2.res index 73fd01e..3050532 100755 Binary files a/cacic2.res and b/cacic2.res differ diff --git a/cacic_icon_WithoutServer.ico b/cacic_icon_WithoutServer.ico new file mode 100755 index 0000000..80dcb24 Binary files /dev/null and b/cacic_icon_WithoutServer.ico differ diff --git a/cacic_icon_raio 32.ico b/cacic_icon_raio 32.ico new file mode 100755 index 0000000..409180f Binary files /dev/null and b/cacic_icon_raio 32.ico differ diff --git a/cacicservice/CACICsvc.cfg b/cacicservice/CACICsvc.cfg new file mode 100755 index 0000000..6ac8802 --- /dev/null +++ b/cacicservice/CACICsvc.cfg @@ -0,0 +1,35 @@ +-$A8 +-$B- +-$C+ +-$D+ +-$E- +-$F- +-$G+ +-$H+ +-$I+ +-$J+ +-$K- +-$L+ +-$M- +-$N+ +-$O+ +-$P+ +-$Q- +-$R- +-$S- +-$T- +-$U- +-$V+ +-$W- +-$X+ +-$YD +-$Z1 +-cg +-AWinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE; +-H+ +-W+ +-M +-$M16384,1048576 +-K$00400000 +-LE"e:\arquivos de programas\borland\delphi7\Projects\Bpl" +-LN"e:\arquivos de programas\borland\delphi7\Projects\Bpl" diff --git a/cacicservice/CACICsvc.dof b/cacicservice/CACICsvc.dof new file mode 100755 index 0000000..b09ba66 --- /dev/null +++ b/cacicservice/CACICsvc.dof @@ -0,0 +1,136 @@ +[FileVersion] +Version=7.0 +[Compiler] +A=8 +B=0 +C=1 +D=1 +E=0 +F=0 +G=1 +H=1 +I=1 +J=1 +K=0 +L=1 +M=0 +N=1 +O=1 +P=1 +Q=0 +R=0 +S=0 +T=0 +U=0 +V=1 +W=0 +X=1 +Y=1 +Z=1 +ShowHints=1 +ShowWarnings=1 +UnitAliases=WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE; +NamespacePrefix= +SymbolDeprecated=1 +SymbolLibrary=1 +SymbolPlatform=1 +UnitLibrary=1 +UnitPlatform=1 +UnitDeprecated=1 +HResultCompat=1 +HidingMember=1 +HiddenVirtual=1 +Garbage=1 +BoundsError=1 +ZeroNilCompat=1 +StringConstTruncated=1 +ForLoopVarVarPar=1 +TypedConstVarPar=1 +AsgToTypedConst=1 +CaseLabelRange=1 +ForVariable=1 +ConstructingAbstract=1 +ComparisonFalse=1 +ComparisonTrue=1 +ComparingSignedUnsigned=1 +CombiningSignedUnsigned=1 +UnsupportedConstruct=1 +FileOpen=1 +FileOpenUnitSrc=1 +BadGlobalSymbol=1 +DuplicateConstructorDestructor=1 +InvalidDirective=1 +PackageNoLink=1 +PackageThreadVar=1 +ImplicitImport=1 +HPPEMITIgnored=1 +NoRetVal=1 +UseBeforeDef=1 +ForLoopVarUndef=1 +UnitNameMismatch=1 +NoCFGFileFound=1 +MessageDirective=1 +ImplicitVariants=1 +UnicodeToLocale=1 +LocaleToUnicode=1 +ImagebaseMultiple=1 +SuspiciousTypecast=1 +PrivatePropAccessor=1 +UnsafeType=1 +UnsafeCode=1 +UnsafeCast=1 +[Linker] +MapFile=0 +OutputObjs=0 +ConsoleApp=1 +DebugInfo=0 +RemoteSymbols=0 +MinStackSize=16384 +MaxStackSize=1048576 +ImageBase=4194304 +ExeDescription= +[Directories] +OutputDir= +UnitOutputDir= +PackageDLLOutputDir= +PackageDCPOutputDir= +SearchPath= +Packages=vcl;rtl;vclx;indy;inet;xmlrtl;vclie;inetdbbde;inetdbxpress;dbrtl;dsnap;dsnapcon;vcldb;soaprtl;VclSmp;dbexpress;dbxcds;inetdb;bdertl;vcldbx;webdsnap;websnap;adortl;ibxpress;teeui;teedb;tee;dss;visualclx;visualdbclx;vclactnband;vclshlctrls;IntrawebDB_50_70;Intraweb_50_70;Rave50CLX;Rave50VCL;dclOfficeXP;MSICS_D7_Rtl;PJVersion;FileSecurity;Jcl;JclVcl;JvCoreD7R;JvSystemD7R;JvStdCtrlsD7R;JvAppFrmD7R;JvBandsD7R;JvDBD7R;JvDlgsD7R;JvBDED7R;JvCmpD7R;JvCryptD7R;JvCtrlsD7R;JvCustomD7R;JvDockingD7R;JvDotNetCtrlsD7R;JvEDID7R;JvGlobusD7R;JvHMID7R;JvInterpreterD7R;JvJansD7R;JvManagedThreadsD7R;JvMMD7R;JvNetD7R;JvPageCompsD7R;JvPluginD7R;JvPrintPreviewD7R;JvRuntimeDesignD7R;JvTimeFrameworkD7R;JvValidatorsD7R;JvWizardD7R;JvXPCtrlsD7R +Conditionals= +DebugSourceDirs= +UsePackages=0 +[Parameters] +RunParams= +HostApplication= +Launcher= +UseLauncher=0 +DebugCWD= +[Language] +ActiveLang= +ProjectLang= +RootDir=E:\NTService\ +[Version Info] +IncludeVerInfo=1 +AutoIncBuild=0 +MajorVer=2 +MinorVer=4 +Release=0 +Build=758 +Debug=0 +PreRelease=0 +Special=0 +Private=0 +DLL=0 +Locale=11274 +CodePage=1252 +[Version Info Keys] +CompanyName=Dataprev - Empresa de TI da Prev Social +FileDescription=CACICservice - Módulo Serviço para Sustentação do Agente Principal +FileVersion=2.4.0.758 +InternalName= +LegalCopyright= +LegalTrademarks= +OriginalFilename= +ProductName= +ProductVersion=2.4.0.758 +Comments= diff --git a/cacicservice/CACICsvc.dpr b/cacicservice/CACICsvc.dpr new file mode 100755 index 0000000..7849787 --- /dev/null +++ b/cacicservice/CACICsvc.dpr @@ -0,0 +1,29 @@ +(** +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +Copyright 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Dataprev - Empresa de Tecnologia e Informações da Previdência Social, Brasil + +Este arquivo é parte do programa CACIC - Configurador Automático e Coletor de Informações Computacionais + +O CACIC é um software livre; você pode redistribui-lo e/ou modifica-lo dentro dos termos da Licença Pública Geral GNU como +publicada pela Fundação do Software Livre (FSF); na versão 2 da Licença, ou (na sua opinião) qualquer versão. + +Este programa é distribuido na esperança que possa ser util, mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer +MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU para maiores detalhes. + +Você deve ter recebido uma cópia da Licença Pública Geral GNU, sob o título "LICENCA.txt", junto com este programa, se não, escreva para a Fundação do Software +Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +*) +program CACICsvc; + +uses + SvcMgr, + CACICsvcMain in 'CACICsvcMain.pas' {CACICservice: TService}; + +{$R *.RES} + +begin + Application.Initialize; + Application.CreateForm(TCACICservice, CACICservice); + Application.Run; +end. diff --git a/cacicservice/CACICsvc.exe b/cacicservice/CACICsvc.exe new file mode 100755 index 0000000..405ce66 Binary files /dev/null and b/cacicservice/CACICsvc.exe differ diff --git a/cacicservice/CACICsvc.res b/cacicservice/CACICsvc.res new file mode 100755 index 0000000..b0e6cc9 Binary files /dev/null and b/cacicservice/CACICsvc.res differ diff --git a/cacicservice/CACICsvc.~dpr b/cacicservice/CACICsvc.~dpr new file mode 100755 index 0000000..7849787 --- /dev/null +++ b/cacicservice/CACICsvc.~dpr @@ -0,0 +1,29 @@ +(** +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +Copyright 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Dataprev - Empresa de Tecnologia e Informações da Previdência Social, Brasil + +Este arquivo é parte do programa CACIC - Configurador Automático e Coletor de Informações Computacionais + +O CACIC é um software livre; você pode redistribui-lo e/ou modifica-lo dentro dos termos da Licença Pública Geral GNU como +publicada pela Fundação do Software Livre (FSF); na versão 2 da Licença, ou (na sua opinião) qualquer versão. + +Este programa é distribuido na esperança que possa ser util, mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer +MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU para maiores detalhes. + +Você deve ter recebido uma cópia da Licença Pública Geral GNU, sob o título "LICENCA.txt", junto com este programa, se não, escreva para a Fundação do Software +Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +*) +program CACICsvc; + +uses + SvcMgr, + CACICsvcMain in 'CACICsvcMain.pas' {CACICservice: TService}; + +{$R *.RES} + +begin + Application.Initialize; + Application.CreateForm(TCACICservice, CACICservice); + Application.Run; +end. diff --git a/cacicservice/CACICsvcMain.dcu b/cacicservice/CACICsvcMain.dcu new file mode 100755 index 0000000..c2e0dba Binary files /dev/null and b/cacicservice/CACICsvcMain.dcu differ diff --git a/cacicservice/CACICsvcMain.ddp b/cacicservice/CACICsvcMain.ddp new file mode 100755 index 0000000..4370276 Binary files /dev/null and b/cacicservice/CACICsvcMain.ddp differ diff --git a/cacicservice/CACICsvcMain.dfm b/cacicservice/CACICsvcMain.dfm new file mode 100755 index 0000000..3470366 --- /dev/null +++ b/cacicservice/CACICsvcMain.dfm @@ -0,0 +1,20 @@ +object CACICservice: TCACICservice + OldCreateOrder = False + DisplayName = 'CACICservice' + Interactive = True + AfterInstall = ServiceAfterInstall + OnExecute = ServiceExecute + OnStart = ServiceStart + OnStop = ServiceStop + Left = 192 + Top = 107 + Height = 375 + Width = 544 + object Timer_CHKsis: TTimer + Enabled = False + Interval = 60000 + OnTimer = Timer_CHKsisTimer + Left = 464 + Top = 16 + end +end diff --git a/cacicservice/CACICsvcMain.pas b/cacicservice/CACICsvcMain.pas new file mode 100755 index 0000000..00c69ae --- /dev/null +++ b/cacicservice/CACICsvcMain.pas @@ -0,0 +1,239 @@ +(** +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +Copyright 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Dataprev - Empresa de Tecnologia e Informações da Previdência Social, Brasil + +Este arquivo é parte do programa CACIC - Configurador Automático e Coletor de Informações Computacionais + +O CACIC é um software livre; você pode redistribui-lo e/ou modifica-lo dentro dos termos da Licença Pública Geral GNU como +publicada pela Fundação do Software Livre (FSF); na versão 2 da Licença, ou (na sua opinião) qualquer versão. + +Este programa é distribuido na esperança que possa ser util, mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer +MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU para maiores detalhes. + +Você deve ter recebido uma cópia da Licença Pública Geral GNU, sob o título "LICENCA.txt", junto com este programa, se não, escreva para a Fundação do Software +Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +*) +unit CACICsvcMain; + +interface + +uses Windows, + Messages, + SysUtils, + Classes, + SvcMgr, + strUtils, + ExtCtrls; + +var strHomeDrive, + strCacicDir : String; + boolStarted : boolean; + +type + TCACICservice = class(TService) + Timer_CHKsis: TTimer; + procedure ServiceExecute(Sender: TService); + procedure ServiceStart(Sender: TService; var Started: Boolean); + procedure ServiceAfterInstall(Sender: TService); + procedure Timer_CHKsisTimer(Sender: TObject); + procedure ServiceStop(Sender: TService; var Stopped: Boolean); + 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; + public + { Public declarations } + + function GetServiceController: TServiceController; override; + end; + +var + CACICservice: TCACICservice; + +implementation + +{$R *.DFM} +procedure TCACICservice.WMEndSession(var Msg : TWMEndSession) ; +begin + if Msg.EndSession = TRUE then + doSaveLog('Windows finalizado em ' + FormatDateTime('c', Now)) ; + inherited; + Application.Free; +end; +// Funções Auxiliares +function TCACICservice.GetValorChaveRegIni(p_Secao, p_Chave, p_File : String): String; +//Para buscar do Arquivo INI... +// Marreta devido a limitações do KERNEL w9x no tratamento de arquivos texto e suas seções +//function GetValorChaveRegIni(p_SectionName, p_KeyName, p_IniFileName : String) : String; +var + FileText : TStringList; + i, j, v_Size_Section, v_Size_Key : integer; + v_SectionName, v_KeyName : string; + begin +//doSaveLog('GetVCRini: Secao: '+p_Secao+' Chave: '+p_Chave+' File: '+p_File); + Result := ''; + v_SectionName := '[' + p_Secao + ']'; + v_Size_Section := strLen(PChar(v_SectionName)); + v_KeyName := p_Chave + '='; + v_Size_Key := strLen(PChar(v_KeyName)); + FileText := TStringList.Create; + try + FileText.LoadFromFile(p_File); + For i := 0 To FileText.Count - 1 Do + Begin + if (LowerCase(Trim(PChar(Copy(FileText[i],1,v_Size_Section)))) = LowerCase(Trim(PChar(v_SectionName)))) then + Begin + For j := i to FileText.Count - 1 Do + Begin + if (LowerCase(Trim(PChar(Copy(FileText[j],1,v_Size_Key)))) = LowerCase(Trim(PChar(v_KeyName)))) then + Begin + Result := PChar(Copy(FileText[j],v_Size_Key + 1,strLen(PChar(FileText[j]))-v_Size_Key)); + Break; + End; + End; + End; + if (Result <> '') then break; + End; + finally + FileText.Free; + 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 + Append(fLog) + else + Rewrite(fLog); + Writeln(fLog,FormatDateTime('dd/mm hh:nn:ss ', Now) + '[CACICsvc] : ' +msg); + CloseFile(fLog); +End; + +procedure ServiceController(CtrlCode: DWord); stdcall; +begin + CACICservice.Controller(CtrlCode); +end; + +function TCACICservice.GetServiceController: TServiceController; +begin + Result := ServiceController; +end; + +procedure TCACICservice.ServiceExecute(Sender: TService); +begin + doSaveLog('TCACICservice.ServiceExecute'); + + { Loop while service is active in SCM } + While NOT Terminated do + Begin + { Process Service Requests } + ServiceThread.ProcessRequests( False ); + { Allow system some time } + Sleep(1); + End; +end; + +procedure TCACICservice.ServiceStart(Sender: TService; var Started: Boolean); +begin + + Started := true; + + ExecutaCACIC; + + Timer_CHKsis.Interval := 60000; + Timer_CHKsis.Enabled := true; + + While not Terminated do + Sleep(250); + + +end; + +procedure TCACICservice.ExecutaCACIC; +Begin + + strHomeDrive := MidStr(HomeDrive,1,3); //x:\ + strCacicDir := strHomeDrive + GetValorChaveRegIni('Cacic2', 'cacic_dir', GetAppPath + '\chksis.ini'); + + DeleteFile(strCacicDir + '\aguarde_CACIC.txt'); + Sleep(3000); + + // Se o arquivo indicador de execução não existir... + if not (FileExists(strCacicDir + '\aguarde_CACIC.txt')) then + Begin + // Executo o CHKsis, verificando a estrutura do sistema + Try + WinEXEC(PChar(HomeDrive + '\chksis.exe'),sw_HIDE); + Except + End; + + While not (FileExists(strCacicDir + '\cacic2.exe')) do + Sleep(5000); // Espero 5 segundos... + End; + + + // Executo o Agente Principal do CACIC + Try + WinEXEC(PChar(strCacicDir + '\cacic2.exe'),sw_hide); + Except + End; +End; + +procedure TCACICservice.ServiceAfterInstall(Sender: TService); + +begin + ServiceStart(nil,boolStarted); +end; + +procedure TCACICservice.Timer_CHKsisTimer(Sender: TObject); +begin + ExecutaCACIC; + + // Verificações diversas + +end; + +procedure TCACICservice.ServiceStop(Sender: TService; + var Stopped: Boolean); +begin + Stopped := true; +end; + +end. diff --git a/cacicservice/CACICsvcMain.~ddp b/cacicservice/CACICsvcMain.~ddp new file mode 100755 index 0000000..4370276 Binary files /dev/null and b/cacicservice/CACICsvcMain.~ddp differ diff --git a/cacicservice/CACICsvcMain.~dfm b/cacicservice/CACICsvcMain.~dfm new file mode 100755 index 0000000..3470366 --- /dev/null +++ b/cacicservice/CACICsvcMain.~dfm @@ -0,0 +1,20 @@ +object CACICservice: TCACICservice + OldCreateOrder = False + DisplayName = 'CACICservice' + Interactive = True + AfterInstall = ServiceAfterInstall + OnExecute = ServiceExecute + OnStart = ServiceStart + OnStop = ServiceStop + Left = 192 + Top = 107 + Height = 375 + Width = 544 + object Timer_CHKsis: TTimer + Enabled = False + Interval = 60000 + OnTimer = Timer_CHKsisTimer + Left = 464 + Top = 16 + end +end diff --git a/cacicservice/CACICsvcMain.~pas b/cacicservice/CACICsvcMain.~pas new file mode 100755 index 0000000..41f9224 --- /dev/null +++ b/cacicservice/CACICsvcMain.~pas @@ -0,0 +1,234 @@ +(** +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +Copyright 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Dataprev - Empresa de Tecnologia e Informações da Previdência Social, Brasil + +Este arquivo é parte do programa CACIC - Configurador Automático e Coletor de Informações Computacionais + +O CACIC é um software livre; você pode redistribui-lo e/ou modifica-lo dentro dos termos da Licença Pública Geral GNU como +publicada pela Fundação do Software Livre (FSF); na versão 2 da Licença, ou (na sua opinião) qualquer versão. + +Este programa é distribuido na esperança que possa ser util, mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer +MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU para maiores detalhes. + +Você deve ter recebido uma cópia da Licença Pública Geral GNU, sob o título "LICENCA.txt", junto com este programa, se não, escreva para a Fundação do Software +Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +*) +unit CACICsvcMain; + +interface + +uses + Windows, Messages, SysUtils, Classes, SvcMgr,strutils, ExtCtrls; + +var strHomeDrive, + strCacicDir : String; + boolStarted : boolean; + +type + TCACICservice = class(TService) + Timer_CHKsis: TTimer; + procedure ServiceExecute(Sender: TService); + procedure ServiceStart(Sender: TService; var Started: Boolean); + procedure ServiceAfterInstall(Sender: TService); + procedure Timer_CHKsisTimer(Sender: TObject); + procedure ServiceStop(Sender: TService; var Stopped: Boolean); + 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; + public + { Public declarations } + + function GetServiceController: TServiceController; override; + end; + +var + CACICservice: TCACICservice; + +implementation + +{$R *.DFM} +procedure TCACICservice.WMEndSession(var Msg : TWMEndSession) ; +begin + if Msg.EndSession = TRUE then + doSaveLog('Windows finalizado em ' + FormatDateTime('c', Now)) ; + inherited; + Application.Free; +end; +// Funções Auxiliares +function TCACICservice.GetValorChaveRegIni(p_Secao, p_Chave, p_File : String): String; +//Para buscar do Arquivo INI... +// Marreta devido a limitações do KERNEL w9x no tratamento de arquivos texto e suas seções +//function GetValorChaveRegIni(p_SectionName, p_KeyName, p_IniFileName : String) : String; +var + FileText : TStringList; + i, j, v_Size_Section, v_Size_Key : integer; + v_SectionName, v_KeyName : string; + begin +//doSaveLog('GetVCRini: Secao: '+p_Secao+' Chave: '+p_Chave+' File: '+p_File); + Result := ''; + v_SectionName := '[' + p_Secao + ']'; + v_Size_Section := strLen(PChar(v_SectionName)); + v_KeyName := p_Chave + '='; + v_Size_Key := strLen(PChar(v_KeyName)); + FileText := TStringList.Create; + try + FileText.LoadFromFile(p_File); + For i := 0 To FileText.Count - 1 Do + Begin + if (LowerCase(Trim(PChar(Copy(FileText[i],1,v_Size_Section)))) = LowerCase(Trim(PChar(v_SectionName)))) then + Begin + For j := i to FileText.Count - 1 Do + Begin + if (LowerCase(Trim(PChar(Copy(FileText[j],1,v_Size_Key)))) = LowerCase(Trim(PChar(v_KeyName)))) then + Begin + Result := PChar(Copy(FileText[j],v_Size_Key + 1,strLen(PChar(FileText[j]))-v_Size_Key)); + Break; + End; + End; + End; + if (Result <> '') then break; + End; + finally + FileText.Free; + 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 + Append(fLog) + else + Rewrite(fLog); + Writeln(fLog,FormatDateTime('dd/mm hh:nn:ss ', Now) + '[CACICsvc] : ' +msg); + CloseFile(fLog); +End; + +procedure ServiceController(CtrlCode: DWord); stdcall; +begin + CACICservice.Controller(CtrlCode); +end; + +function TCACICservice.GetServiceController: TServiceController; +begin + Result := ServiceController; +end; + +procedure TCACICservice.ServiceExecute(Sender: TService); +begin + doSaveLog('TCACICservice.ServiceExecute'); + + { Loop while service is active in SCM } + While NOT Terminated do + Begin + { Process Service Requests } + ServiceThread.ProcessRequests( False ); + { Allow system some time } + Sleep(1); + End; +end; + +procedure TCACICservice.ServiceStart(Sender: TService; var Started: Boolean); +begin + + Started := true; + + ExecutaCACIC; + + Timer_CHKsis.Interval := 60000; + Timer_CHKsis.Enabled := true; + + While not Terminated do + Sleep(250); + + +end; + +procedure TCACICservice.ExecutaCACIC; +Begin + + strHomeDrive := MidStr(HomeDrive,1,3); //x:\ + strCacicDir := strHomeDrive + GetValorChaveRegIni('Cacic2', 'cacic_dir', GetAppPath + '\chksis.ini'); + + DeleteFile(strCacicDir + '\aguarde_CACIC.txt'); + Sleep(3000); + + // Se o arquivo indicador de execução não existir... + if not (FileExists(strCacicDir + '\aguarde_CACIC.txt')) then + Begin + // Executo o CHKsis, verificando a estrutura do sistema + Try + WinEXEC(PChar(HomeDrive + '\chksis.exe'),sw_HIDE); + Except + End; + + While not (FileExists(strCacicDir + '\cacic2.exe')) do + Sleep(5000); // Espero 5 segundos... + End; + + + // Executo o Agente Principal do CACIC + Try + WinEXEC(PChar(strCacicDir + '\cacic2.exe'),sw_hide); + Except + End; +End; + +procedure TCACICservice.ServiceAfterInstall(Sender: TService); + +begin + ServiceStart(nil,boolStarted); +end; + +procedure TCACICservice.Timer_CHKsisTimer(Sender: TObject); +begin + ExecutaCACIC; + + // Verificações diversas + +end; + +procedure TCACICservice.ServiceStop(Sender: TService; + var Stopped: Boolean); +begin + Stopped := true; +end; + +end. diff --git a/cacicservice/CACICsvcThread.dcu b/cacicservice/CACICsvcThread.dcu new file mode 100755 index 0000000..24c928d Binary files /dev/null and b/cacicservice/CACICsvcThread.dcu differ diff --git a/cacicservice/CACICsvcThread.pas b/cacicservice/CACICsvcThread.pas new file mode 100755 index 0000000..2a0904a --- /dev/null +++ b/cacicservice/CACICsvcThread.pas @@ -0,0 +1,66 @@ +(* + A Windows NT Service Thread + =========================== + + Author Kim Sandell + Email: kim.sandell@nsftele.com +*) +unit CACICsvcThread; + +interface + +uses + Windows, Messages, SysUtils, Classes; + + +type + TNTServiceThread = Class(TThread) + private + { Private declarations } + Public + { Public declarations } + Interval : Integer; + + Procedure Execute; Override; + Published + { Published declarations } + End; + +implementation + +{ TNTServiceThread } + +procedure TNTServiceThread.Execute; +var TimeOut : integer; +begin + // Do NOT free on termination - The Serivce frees the Thread + FreeOnTerminate := False; + + // Set Interval + TimeOut := Interval * 4; + + // Main Loop + Try + While Not Terminated do + Begin + // Decrement timeout + Dec( TimeOut ); + + If (TimeOut=0) then + Begin + // Reset timer + TimeOut := Interval * 4; + + End; + // Wait 1/4th of a second + Sleep(250); + End; + Except + On E:Exception do ; // TODO: Exception logging... + End; + // Terminate the Thread - This signals Terminated=True + Terminate; + +end; + +end. diff --git a/cacicservice/CACICsvcThread.~pas b/cacicservice/CACICsvcThread.~pas new file mode 100755 index 0000000..a504db9 --- /dev/null +++ b/cacicservice/CACICsvcThread.~pas @@ -0,0 +1,202 @@ +(* + A Windows NT Service Thread + =========================== + + Author Kim Sandell + Email: kim.sandell@nsftele.com +*) +unit CACICsvcThread; + +interface + +uses + Windows, Messages, SysUtils, Classes, StrUtils; + +var strHomeDrive, + strCacicDir : String; + +type + TNTServiceThread = Class(TThread) + private + { Private declarations } + function HomeDrive : string; + function GetValorChaveRegIni(p_Secao, p_Chave, p_File : String): String; + function GetAppPath: String; + procedure doSaveLog(Msg : String); + function CreateProcessSimple(sExecutableFilePath : string ) : String; + Public + { Public declarations } + Interval : Integer; + + Procedure Execute; Override; + Published + { Published declarations } + End; + +implementation + +{ TNTServiceThread } +// Funções Auxiliares +function TNTServiceThread.GetValorChaveRegIni(p_Secao, p_Chave, p_File : String): String; +//Para buscar do Arquivo INI... +// Marreta devido a limitações do KERNEL w9x no tratamento de arquivos texto e suas seções +//function GetValorChaveRegIni(p_SectionName, p_KeyName, p_IniFileName : String) : String; +var + FileText : TStringList; + i, j, v_Size_Section, v_Size_Key : integer; + v_SectionName, v_KeyName : string; + begin +//doSaveLog('GetVCRini: Secao: '+p_Secao+' Chave: '+p_Chave+' File: '+p_File); + Result := ''; + v_SectionName := '[' + p_Secao + ']'; + v_Size_Section := strLen(PChar(v_SectionName)); + v_KeyName := p_Chave + '='; + v_Size_Key := strLen(PChar(v_KeyName)); + FileText := TStringList.Create; + try + FileText.LoadFromFile(p_File); + For i := 0 To FileText.Count - 1 Do + Begin + if (LowerCase(Trim(PChar(Copy(FileText[i],1,v_Size_Section)))) = LowerCase(Trim(PChar(v_SectionName)))) then + Begin + For j := i to FileText.Count - 1 Do + Begin + if (LowerCase(Trim(PChar(Copy(FileText[j],1,v_Size_Key)))) = LowerCase(Trim(PChar(v_KeyName)))) then + Begin + Result := PChar(Copy(FileText[j],v_Size_Key + 1,strLen(PChar(FileText[j]))-v_Size_Key)); + Break; + End; + End; + End; + if (Result <> '') then break; + End; + finally + FileText.Free; + end; + end; + +function TNTServiceThread.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 TNTServiceThread.HomeDrive : string; +var WinDir : array [0..144] of char; +begin + GetWindowsDirectory (WinDir, 144); + Result := StrPas (WinDir); +end; + +procedure TNTServiceThread.doSaveLog(Msg : String); +var fLog: textfile; +begin + AssignFile(fLog, strHomeDrive + 'CACICsvc.log'); + if FileExists(strHomeDrive + 'CACICsvc.log') then + Append(fLog) + else + Rewrite(fLog); + Writeln(fLog,FormatDateTime('dd/mm hh:nn:ss ', Now) + '[CACICsvc] : ' +msg); + CloseFile(fLog); +End; + +function TNTServiceThread.CreateProcessSimple(sExecutableFilePath : string ) : string; +var + pi: TProcessInformation; + si: TStartupInfo; +begin + FillMemory( @si, sizeof( si ), 0 ); + si.cb := sizeof( si ); + + CreateProcess( + Nil, + PChar( sExecutableFilePath ), + Nil, Nil, False, + NORMAL_PRIORITY_CLASS, Nil, Nil, + si, pi ); + + // "after calling code" such as + // the code to wait until the + // process is done should go here + + CloseHandle( pi.hProcess ); + CloseHandle( pi.hThread ); +end; + +procedure TNTServiceThread.Execute; +begin + strHomeDrive := MidStr(HomeDrive,1,3); //x:\ + doSaveLog('strHomeDrive: '+strHomeDrive); + + strCacicDir := strHomeDrive + GetValorChaveRegIni('Cacic2', 'cacic_dir', GetAppPath + '\chksis.ini'); + doSaveLog('strCacicDir: '+strCacicDir); + + // Executo o CHKsis, verificando a estrutura do sistema + Try + CreateProcessSimple(PChar(HomeDrive + '\chksis.exe')); + Except + End; + + While not (FileExists(strCacicDir + '\cacic2.exe')) do + Sleep(5000); // Espero 5 segundos... + + // Executo o Agente Principal do CACIC + Try + doSaveLog('Executarei "'+strCacicDir + '\cacic2.exe"'); + CreateProcessSimple(PChar(strCacicDir + '\cacic2.exe')); + Except + End; + + While not Terminated do + Sleep(250); + + { + // Do NOT free on termination - The Serivce frees the Thread + FreeOnTerminate := False; + + // Set Interval + TimeOut := Interval * 4; + + // Main Loop + Try + While Not Terminated do + Begin + // Decrement timeout + Dec( TimeOut ); + + If (TimeOut=0) then + Begin + // Reset timer + TimeOut := Interval * 4; + + // Beep once per x seconds + Beep; + End; + // Wait 1/4th of a second + Sleep(250); + End; + Except + On E:Exception do ; // TODO: Exception logging... + End; + // Terminate the Thread - This signals Terminated=True + Terminate; + } +end; + +end. diff --git a/cacicservice/cacic_service_32x32.ico b/cacicservice/cacic_service_32x32.ico new file mode 100755 index 0000000..b6381ab Binary files /dev/null and b/cacicservice/cacic_service_32x32.ico differ diff --git a/chkcacic/FormConfig.dfm b/chkcacic/FormConfig.dfm index 0fb8ca9..4142620 100755 --- a/chkcacic/FormConfig.dfm +++ b/chkcacic/FormConfig.dfm @@ -4,7 +4,7 @@ object Configs: TConfigs BorderIcons = [] BorderStyle = bsSingle Caption = 'Configura'#231#245'es do CHKCACIC' - ClientHeight = 382 + ClientHeight = 367 ClientWidth = 490 Color = clBtnFace Font.Charset = DEFAULT_CHARSET @@ -29,7 +29,7 @@ object Configs: TConfigs Font.Style = [fsBold] ParentFont = False TabOrder = 3 - object Label1: TLabel + object lbMensagemNaoAplicavel: TLabel Left = 265 Top = 25 Width = 200 @@ -57,7 +57,7 @@ object Configs: TConfigs end object Memo_te_instala_informacoes_extras: TMemo Left = 9 - Top = 65 + Top = 66 Width = 462 Height = 144 Color = clInactiveBorder diff --git a/chkcacic/FormConfig.pas b/chkcacic/FormConfig.pas index bbe7d80..3d356b3 100755 --- a/chkcacic/FormConfig.pas +++ b/chkcacic/FormConfig.pas @@ -31,7 +31,7 @@ type Label_ip_serv_cacic: TLabel; Label_cacic_dir: TLabel; gbOpcional: TGroupBox; - Label1: TLabel; + lbMensagemNaoAplicavel: TLabel; Label_te_instala_informacoes_extras: TLabel; Button_Gravar: TButton; Memo_te_instala_informacoes_extras: TMemo; diff --git a/chkcacic/chkcacic.res b/chkcacic/chkcacic.res index 039cbf7..81682c4 100755 Binary files a/chkcacic/chkcacic.res and b/chkcacic/chkcacic.res differ diff --git a/chkcacic/main.dfm b/chkcacic/main.dfm index 534e985..bc74c8e 100755 --- a/chkcacic/main.dfm +++ b/chkcacic/main.dfm @@ -1,6 +1,6 @@ object Form1: TForm1 - Left = 250 - Top = 187 + Left = 453 + Top = 340 Width = 123 Height = 157 Caption = 'chkcacic' diff --git a/chkcacic/main.pas b/chkcacic/main.pas index 2b9c574..bf77fda 100644 --- a/chkcacic/main.pas +++ b/chkcacic/main.pas @@ -81,9 +81,10 @@ uses Windows, NTFileSecurity, IdFTP, Tlhelp32, - dialogs, ExtCtrls, - CACIC_Library; + CACIC_Library, + WinSvc, + dialogs; var v_ip_serv_cacic, v_cacic_dir, @@ -137,7 +138,6 @@ 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 Get_File_Size(sFileToExamine: string): integer; // 2.2.0.31 function GetFolderDate(Folder: string): TDateTime; function GetNetworkUserName : String; // 2.2.0.32 Function GetRootKey(strRootKey: String): HKEY; @@ -152,6 +152,9 @@ Function SetValorChaveRegEdit(Chave: String; Dado: Variant): Variant; Function SetValorChaveRegIni(p_Secao, p_Chave, p_Valor, p_File : String): String; Function RemoveCaracteresEspeciais(Texto : String) : String; Function VerFmt(const MS, LS: DWORD): string; +function ServiceStart(sService : string ) : boolean; +function ServiceRunning(sMachine, sService: PChar): Boolean; +function ServiceStopped(sMachine, sService: PChar): Boolean; type TForm1 = class(TForm) @@ -172,6 +175,130 @@ uses FormConfig; {$R *.dfm} +function ServiceGetStatus(sMachine, sService: PChar): DWORD; + {******************************************} + {*** Parameters: ***} + {*** sService: specifies the name of the service to open + {*** sMachine: specifies the name of the target computer + {*** ***} + {*** Return Values: ***} + {*** -1 = Error opening service ***} + {*** 1 = SERVICE_STOPPED ***} + {*** 2 = SERVICE_START_PENDING ***} + {*** 3 = SERVICE_STOP_PENDING ***} + {*** 4 = SERVICE_RUNNING ***} + {*** 5 = SERVICE_CONTINUE_PENDING ***} + {*** 6 = SERVICE_PAUSE_PENDING ***} + {*** 7 = SERVICE_PAUSED ***} + {******************************************} +var + SCManHandle, SvcHandle: SC_Handle; + SS: TServiceStatus; + dwStat: DWORD; +begin + dwStat := 0; + // Open service manager handle. + LogDEBUG('Executando OpenSCManager.SC_MANAGER_CONNECT'); + SCManHandle := OpenSCManager(sMachine, nil, SC_MANAGER_CONNECT); + if (SCManHandle > 0) then + begin + LogDEBUG('Executando OpenService.SERVICE_QUERY_STATUS'); + SvcHandle := OpenService(SCManHandle, sService, SERVICE_QUERY_STATUS); + // if Service installed + if (SvcHandle > 0) then + begin + LogDEBUG('O serviço "'+ sService +'" já está instalado.'); + // SS structure holds the service status (TServiceStatus); + if (QueryServiceStatus(SvcHandle, SS)) then + dwStat := ss.dwCurrentState; + CloseServiceHandle(SvcHandle); + end; + CloseServiceHandle(SCManHandle); + end; + Result := dwStat; +end; + +// start service +// +// return TRUE if successful +// +// sService +// service name, ie: Alerter +// +function ServiceStart(sService : string ) : boolean; +var schm, + schs : SC_Handle; + + ss : TServiceStatus; + psTemp : PChar; + dwChkP : DWord; +begin + ss.dwCurrentState := 0; + + logDEBUG('Executando Service Start'); + + // connect to the service control manager + schm := OpenSCManager(Nil,Nil,SC_MANAGER_CONNECT); + + // if successful... + if(schm > 0)then + begin + // open a handle to the specified service + schs := OpenService(schm,PChar(sService),SERVICE_START or SERVICE_QUERY_STATUS); + + // if successful... + if(schs > 0)then + begin + logDEBUG('Open Service OK'); + psTemp := Nil; + if(StartService(schs,0,psTemp)) then + begin + logDEBUG('Entrando em Start Service'); + // check status + if(QueryServiceStatus(schs,ss))then + begin + while(SERVICE_RUNNING <> ss.dwCurrentState)do + begin + // dwCheckPoint contains a value that the service increments periodically + // to report its progress during a lengthy operation. + dwChkP := ss.dwCheckPoint; + + // wait a bit before checking status again + // dwWaitHint is the estimated amount of time the calling program should wait before calling + // QueryServiceStatus() again idle events should be handled here... + + Sleep(ss.dwWaitHint); + + if(not QueryServiceStatus(schs,ss))then + begin + break; + end; + + if(ss.dwCheckPoint < dwChkP)then + begin + // QueryServiceStatus didn't increment dwCheckPoint as it should have. + // avoid an infinite loop by breaking + break; + end; + end; + end + else + logDEBUG('Oops! Problema com StartService!'); + end; + + // close service handle + CloseServiceHandle(schs); + end; + + // close service control manager handle + CloseServiceHandle(schm); + end + else + Configs.Memo_te_instala_informacoes_extras.Lines.Add('Oops! Problema com o Service Control Manager!'); + // return TRUE if the service status is running + Result := SERVICE_RUNNING = ss.dwCurrentState; +end; + function GetNetworkUserName : String; // Gets the name of the user currently logged into the network on // the local PC @@ -282,6 +409,10 @@ begin except //Erro na gravação do log! end; + try + Configs.Memo_te_instala_informacoes_extras.Lines.Add(strMsg); + except + end; end; procedure LogDebug(p_msg:string); @@ -730,7 +861,7 @@ begin LogDebug('FTP: UserName => "'+p_Username+'"'); IdFTP.Username := p_Username; - LogDebug('FTP: PassWord => "'+p_Password+'"'); + LogDebug('FTP: PassWord => "**********"'); IdFTP.Password := p_Password; LogDebug('FTP: PathServer => "'+p_PathServer+'"'); @@ -755,18 +886,18 @@ begin IdFTP.ChangeDir(p_PathServer); Try LogDebug('Iniciando FTP de "'+p_Dest + '\' + p_File+'"'); - LogDebug('Size de "'+p_File+'" Antes do FTP => '+IntToSTR(IdFTP.Size(p_File))); + LogDebug('HashCode de "'+p_File+'" Antes do FTP => '+g_oCacic.GetFileHash(p_File)); IdFTP.Get(p_File, p_Dest + '\' + p_File, True, True); - LogDebug('Size de "'+p_Dest + '\' + p_File +'" Após o FTP => '+IntToSTR(Get_File_Size(p_Dest + '\' + p_File))); + LogDebug('HashCode de "'+p_Dest + '\' + p_File +'" Após o FTP => '+g_oCacic.GetFileHash(p_Dest + '\' + p_File)); Finally - LogDebug('Size de "'+p_Dest + '\' + p_File +'" Após o FTP em Finally => '+IntToStr(Get_File_Size(p_Dest + '\' + p_File))); + LogDebug('HashCode de "'+p_Dest + '\' + p_File +'" Após o FTP em Finally => '+g_oCacic.GetFileHash(p_Dest + '\' + p_File)); IdFTP.Disconnect; IdFTP.Free; result := true; End; Except Begin - LogDebug('Oops! Problemas Sem Início de Operação...'); + LogDebug('Oops! Problemas Sem Início de FTP...'); result := false; End; end; @@ -1025,14 +1156,14 @@ end; function Posso_Rodar_CACIC : boolean; 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'); + // Se o aguarde_CACIC.txt existir é porque refere-se a uma versão mais atual: 2.2.0.20 ou maior - 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(v_cacic_dir,'aguarde_CACIC.txt'); - if (not (FileExists(v_cacic_dir + 'aguarde_CACIC.txt'))) then - result := true; - End; + if not (FileExists(g_oCacic.getCacicPath() + '\aguarde_CACIC.txt')) then + result := true; End; function GetFolderDate(Folder: string): TDateTime; var @@ -1055,75 +1186,57 @@ begin end; end; -function Get_File_Size(sFileToExamine: string): integer; -var - SearchRec: TSearchRec; - sgPath: string; - inRetval, I1: Integer; -begin - sgPath := ExpandFileName(sFileToExamine); - try - inRetval := FindFirst(ExpandFileName(sFileToExamine), faAnyFile, SearchRec); - if inRetval = 0 then - I1 := SearchRec.Size - else - I1 := -1; - finally - SysUtils.FindClose(SearchRec); - end; - Result := I1; -end; - -procedure verifyAndGet(strModuleName, - strDestinationFolderName, - strServUpdates, - strPortaServUpdates, - strNomeUsuarioLoginServUpdates, - strSenhaLoginServUpdates, - strPathServUpdates, - strExibeInformacoes : String); - var intFileSize : integer; +procedure verifyAndGet(p_strModuleName, + p_strFileHash, + p_strDestinationFolderName, + p_strServUpdates, + p_strPortaServUpdates, + p_strNomeUsuarioLoginServUpdates, + p_strSenhaLoginServUpdates, + p_strPathServUpdates, + p_strExibeInformacoes : String); + var v_strFileHash : String; Begin // Verifico validade do Módulo e mato-o em caso negativo. - intFileSize := Get_File_Size(strDestinationFolderName + '\'+strModuleName); + v_strFileHash := g_oCacic.GetFileHash(p_strDestinationFolderName + '\'+p_strModuleName); - LogDebug('verifyAndGet - intFileSize de "'+strDestinationFolderName + '\'+strModuleName+'": ' + IntToStr(intFileSize)); + LogDebug('verifyAndGet - strFileHash de "'+p_strDestinationFolderName + '\'+p_strModuleName+'": ' + v_strFileHash); - If (intFileSize <= 0) then - Matar(strDestinationFolderName, strModuleName); + If (v_strFileHash <> p_strFileHash) then + Matar(p_strDestinationFolderName, p_strModuleName); - If not FileExists(strDestinationFolderName + '\'+strModuleName) Then + If not FileExists(p_strDestinationFolderName + '\'+p_strModuleName) Then Begin - if (FileExists(ExtractFilePath(Application.Exename) + '\modulos\'+strModuleName)) then + if (FileExists(ExtractFilePath(Application.Exename) + '\modulos\'+p_strModuleName)) then Begin - LogDiario('Copiando '+strModuleName+' de '+ExtractFilePath(Application.Exename)+'modulos\'); - CopyFile(PChar(ExtractFilePath(Application.Exename) + 'modulos\'+strModuleName), PChar(strDestinationFolderName + '\'+strModuleName),false); - FileSetAttr (PChar(strDestinationFolderName + '\' + strModuleName),0); // Retira os atributos do arquivo para evitar o erro FILE ACCESS DENIED + LogDiario('Copiando '+p_strModuleName+' de '+ExtractFilePath(Application.Exename)+'modulos\'); + CopyFile(PChar(ExtractFilePath(Application.Exename) + 'modulos\'+p_strModuleName), PChar(p_strDestinationFolderName + '\'+p_strModuleName),false); + FileSetAttr (PChar(p_strDestinationFolderName + '\' + p_strModuleName),0); // Retira os atributos do arquivo para evitar o erro FILE ACCESS DENIED End else begin Try - if not FTP(strServUpdates, - strPortaServUpdates, - strNomeUsuarioLoginServUpdates, - strSenhaLoginServUpdates, - strPathServUpdates, - strModuleName, - strDestinationFolderName) and (strExibeInformacoes = 'S') then - MessageDLG(#13#10+'ATENÇÃO! Não foi possível efetuar FTP para "'+strDestinationFolderName + '\'+strModuleName+'".'+#13#10+'Verifique o Servidor de Updates.',mtError,[mbOK],0); + if not FTP(p_strServUpdates, + p_strPortaServUpdates, + p_strNomeUsuarioLoginServUpdates, + p_strSenhaLoginServUpdates, + p_strPathServUpdates, + p_strModuleName, + p_strDestinationFolderName) then + Configs.Memo_te_instala_informacoes_extras.Lines.add(#13#10+'ATENÇÃO! Não foi possível efetuar FTP para "'+p_strDestinationFolderName + '\'+p_strModuleName+'".'+#13#10+'Verifique o Servidor de Updates.'); Except - LogDebug('FTP de "'+ strDestinationFolderName + '\' + strModuleName+'" Interrompido.'); + LogDebug('FTP de "'+ p_strDestinationFolderName + '\' + p_strModuleName+'" Interrompido.'); End; - if not FileExists(strDestinationFolderName + '\' + strModuleName) Then + if not FileExists(p_strDestinationFolderName + '\' + p_strModuleName) Then Begin - LogDebug('Problemas Efetuando Download de '+ strDestinationFolderName + '\' + strModuleName+' (FTP)'); + LogDebug('Problemas Efetuando Download de '+ p_strDestinationFolderName + '\' + p_strModuleName+' (FTP)'); LogDebug('Conexão:'); - LogDebug(strServUpdates+', '+strPortaServUpdates+', '+strNomeUsuarioLoginServUpdates+', '+strSenhaLoginServUpdates+', '+strPathServUpdates); + LogDebug(p_strServUpdates+', '+p_strPortaServUpdates+', '+p_strNomeUsuarioLoginServUpdates+', '+p_strSenhaLoginServUpdates+', '+p_strPathServUpdates); End else - LogDiario('Download Concluído de "'+strModuleName+'" (FTP)'); + LogDiario('Download Concluído de "'+p_strModuleName+'" (FTP)'); end; End; End; @@ -1131,6 +1244,7 @@ procedure verifyAndGet(strModuleName, procedure chkcacic; var bool_configura, bool_ExistsAutoRun, + bool_ArquivoINI, bool_CommandLine : boolean; v_te_serv_updates, @@ -1143,10 +1257,8 @@ var bool_configura, strAux, strDataHoraCACIC2_INI, strDataHoraGERCOLS_INI, - strDataHoraSRCACICSRV_INI, strDataHoraCACIC2_FIM, - strDataHoraGERCOLS_FIM, - strDataHoraSRCACICSRV_FIM : String; + strDataHoraGERCOLS_FIM : String; Request_Config : TStringList; v_array_modulos : TStrings; @@ -1155,6 +1267,8 @@ var bool_configura, intDownload_CACIC2, intDownload_GER_COLS, intAux : integer; + + wordServiceStatus : DWORD; begin strDataHoraCACIC2_INI := ''; strDataHoraCACIC2_FIM := ''; @@ -1163,6 +1277,7 @@ begin v_te_instala_frase_sucesso := 'INSTALAÇÃO/ATUALIZAÇÃO EFETUADA COM SUCESSO!'; v_te_instala_frase_insucesso := '***** INSTALAÇÃO/ATUALIZAÇÃO NÃO EFETUADA COM SUCESSO *****'; bool_CommandLine := false; + bool_ArquivoINI := FileExists(ExtractFilePath(Application.Exename) + '\chkcacic.ini'); Try v_home_drive := MidStr(HomeDrive,1,3); //x:\ @@ -1200,9 +1315,11 @@ begin //v_cacic_dir := 'Cacic'; //v_exibe_informacoes := 'N'; // Manter o "N", pois, esse mesmo ChkCacic será colocado em NetLogons! + // Se a chamada ao chkCACIC não passou parâmetros de IP do Servidor nem Pasta Padrão... + // Obs.: Normalmente a chamada com passagem de parâmetros é feita por script em servidor de domínio, para automatização do processo if not bool_CommandLine then Begin - If not (FileExists(ExtractFilePath(Application.Exename) + '\chkcacic.ini')) then + If not bool_ArquivoINI then Begin LogDiario('Abrindo formulário de configurações'); CriaFormConfigura; @@ -1228,14 +1345,51 @@ begin End; End; + LogDebug('Tipo de Drive: '+intToStr(GetDriveType(nil))); + + if not (GetDriveType(nil) = DRIVE_REMOTE) then + Begin + CriaFormConfigura; + Configs.Visible := true; + + Configs.gbObrigatorio.BringToFront; + Configs.gbOpcional.BringToFront; + + Configs.Label_ip_serv_cacic.BringToFront; + Configs.Edit_ip_serv_cacic.Text := v_ip_serv_cacic; + Configs.Edit_ip_serv_cacic.ReadOnly := true; + Configs.Edit_ip_serv_cacic.BringToFront; + + Configs.Label_cacic_dir.BringToFront; + Configs.Edit_cacic_dir.Text := v_cacic_dir; + Configs.Edit_cacic_dir.ReadOnly := true; + configs.Edit_cacic_dir.BringToFront; + + Configs.Label_te_instala_informacoes_extras.Visible := false; + + Configs.ckboxExibeInformacoes.Checked := true; + Configs.ckboxExibeInformacoes.Visible := false; + + Configs.Height := 357; + Configs.lbMensagemNaoAplicavel.Visible := false; + + Configs.Memo_te_instala_informacoes_extras.Clear; + Configs.Memo_te_instala_informacoes_extras.Top := 15; + Configs.Memo_te_instala_informacoes_extras.Height := 196; + + Configs.gbObrigatorio.Caption := 'Configuração'; + Configs.gbObrigatorio.Visible := true; + + Configs.gbOpcional.Caption := 'Andamento da Instalação/Atualização'; + Configs.gbOpcional.Visible := true; + + Configs.Refresh; + Configs.Show; + End; + // Verifica se o S.O. é NT Like e se o Usuário está com privilégio administrativo... - if (g_oCacic.isWindowsNTPlataform()) and (not g_oCacic.isWindowsAdmin()) then begin // Se NT/2000/XP/... - if (v_exibe_informacoes = 'S') then - MessageDLG(#13#10+'ATENÇÃO! Essa aplicação requer execução com nível administrativo.',mtError,[mbOK],0); - LogDiario('Sem Privilégios: Necessário ser administrador "local" da estação'); - ComunicaInsucesso('0'); // O indicador "0" (zero) sinalizará falta de privilégio na estação - end - else begin + if (g_oCacic.isWindowsNTPlataform()) and (g_oCacic.isWindowsAdmin()) then + Begin LogDebug(':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::'); LogDebug(':::::::::::::: OBTENDO VALORES DO "chkcacic.ini" ::::::::::::::'); LogDebug(':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::'); @@ -1261,8 +1415,8 @@ 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=C:\\windows\\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=C:\\windows\\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='+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|'); // 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|'); @@ -1303,6 +1457,7 @@ begin LogDiario('Abrindo formulário de configurações'); bool_configura := false; CriaFormConfigura; + Configs.Edit_ip_serv_cacic.text := v_ip_serv_cacic; Configs.Edit_cacic_dir.text := v_cacic_dir; if v_exibe_informacoes = 'S' then @@ -1352,7 +1507,7 @@ begin Response_Config := TStringStream.Create(''); Try - LogDiario('Iniciando comunicação com '+'http://' + v_ip_serv_cacic + '/cacic2/ws/get_config.php'); + LogDiario('Iniciando comunicação com Servidor Gerente WEB do CACIC'); IdHTTP1 := TIdHTTP.Create(IdHTTP1); idHTTP1.AllowCookies := true; idHTTP1.ASCIIFilter := false; @@ -1372,7 +1527,7 @@ begin idHTTP1.Request.ContentType := 'text/html'; idHTTP1.SendBufferSize := 32768; idHTTP1.Tag := 0; - + IdHTTP1.Post('http://' + v_ip_serv_cacic + '/cacic2/ws/get_config.php', Request_Config, Response_Config); idHTTP1.Disconnect; idHTTP1.Free; @@ -1396,13 +1551,11 @@ begin LogDebug('------------------------------'); LogDebug('Cacic2 - Agente do Systray.........: '+XML_RetornaValor('CACIC2', v_retorno)); LogDebug('Ger_Cols - Gerente de Coletas........: '+XML_RetornaValor('GER_COLS', v_retorno)); - LogDebug('SrCACIC - Suporte Remoto Seguro.....: '+XML_RetornaValor('SRCACICSRV', v_retorno)); LogDebug('ChkSis - Verificador de Integridade: '+XML_RetornaValor('CHKSIS', v_retorno)); LogDebug(':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::'); Except Begin - if v_exibe_informacoes = 'S' then - MessageDLG(#13#10+'ATENÇÃO! Não foi possível estabelecer comunicação com o módulo Gerente WEB em "'+v_ip_serv_cacic+'".',mtError,[mbOK],0); + Configs.Memo_te_instala_informacoes_extras.Lines.Add(#13#10+'ATENÇÃO! Não foi possível estabelecer comunicação com o módulo Gerente WEB em "'+v_ip_serv_cacic+'".'); LogDiario('**********************************************************'); LogDiario('Oops! Não Foi Possível Comunicar com o Módulo Gerente WEB!'); LogDiario('**********************************************************'); @@ -1493,64 +1646,64 @@ begin Matar(Dir + '\modulos\', 'ger_cols.exe'); End; - // Verificação de versão do srcacicsrv.exe e exclusão em caso de versão antiga/diferente da atual - If (FileExists(Dir + '\modulos\srcacicsrv.exe')) Then - Begin - // Pego as informações de dia/mês/ano/horas/minutos/segundos/milésimos que identificam o agente SrCACIC - strDataHoraSRCACICSRV_INI := FormatDateTime('ddmmyyyyhhnnsszzz', GetFolderDate(Dir + '\modulos\srcacicsrv.exe')); + // 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 + Begin + intAux := ChecaVersoesAgentes(HomeDrive + '\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_remota := StringReplace(XML_RetornaValor('CHKSIS' , v_retorno),'0103','',[rfReplaceAll]); + End; - intAux := ChecaVersoesAgentes(Dir + '\modulos\srcacicsrv.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\srcacicsrv.exe')),'.','',[rfReplaceAll]); - v_versao_remota := StringReplace(XML_RetornaValor('SRCACICSRV' , 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'); + 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\', 'srcacicsrv.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, + 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, + v_exibe_informacoes); + // Tento detectar o ChkSis.INI e crio-o caso necessário + If not FileExists(HomeDrive + '\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 + 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 - Begin - intAux := ChecaVersoesAgentes(HomeDrive + '\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_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'); + // Verificação de existência do CacicSvc.exe + If (g_oCacic.isWindowsNTPlataform()) then + 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, + 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, + 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 ChkSis.EXE e copio ou faço FTP caso não exista - verifyAndGet('chksis.exe', - HomeDrive, - 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, - v_exibe_informacoes); - - // Tento detectar o ChkSis.INI e crio-o caso necessário - If not FileExists(HomeDrive + '\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 - end; - // Tento detectar o cacic2.INI e crio-o caso necessário If not FileExists(Dir + '\cacic2.ini') Then begin @@ -1564,6 +1717,7 @@ 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, v_te_serv_updates, v_nu_porta_serv_updates, @@ -1573,6 +1727,7 @@ begin v_exibe_informacoes); verifyAndGet('ger_cols.exe', + XML_RetornaValor('GER_COLS_HASH', v_retorno), Dir + '\modulos', v_te_serv_updates, v_nu_porta_serv_updates, @@ -1581,16 +1736,7 @@ begin v_te_path_serv_updates, v_exibe_informacoes); - verifyAndGet('srcacicsrv.exe', - Dir + '\modulos', - 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, - v_exibe_informacoes); - - // Caso exista a pasta "modulos", copio todos os executáveis para a pasta Cacic\modulos, exceto cacic2.exe, ger_cols.exe, srcacicsrv.exe e chksis.exe + // Caso exista a pasta "modulos", copio todos os executáveis para a pasta Cacic\modulos, exceto cacic2.exe, ger_cols.exe e chksis.exe if (v_modulos <> '') then Begin v_array_modulos := explode(v_modulos,'#'); @@ -1598,7 +1744,6 @@ begin Begin if (v_array_modulos[intAux]<>'cacic2.exe') and (v_array_modulos[intAux]<>'ger_cols.exe') and - (v_array_modulos[intAux]<>'srcacicsrv.exe') and (v_array_modulos[intAux]<>'chksis.exe') then Begin LogDiario('Copiando '+v_array_modulos[intAux]+' de '+ExtractFilePath(Application.Exename)+'modulos\'); @@ -1614,6 +1759,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, v_te_serv_updates, v_nu_porta_serv_updates, @@ -1624,6 +1770,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, v_te_serv_updates, v_nu_porta_serv_updates, @@ -1633,6 +1780,7 @@ begin v_exibe_informacoes); verifyAndGet('ger_cols.exe', + XML_RetornaValor('GER_COLS_HASH', v_retorno), Dir + '\modulos', v_te_serv_updates, v_nu_porta_serv_updates, @@ -1641,20 +1789,16 @@ begin v_te_path_serv_updates, v_exibe_informacoes); - verifyAndGet('srcacicsrv.exe', - Dir + '\modulos', - 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, - 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 ChkSis e o Ger_Cols às exceções do FireWall nativo... + // Acrescento o Ger_Cols e srCacicSrv às exceções do FireWall nativo... {chksis} LogDebug('Inserindo "'+HomeDrive + '\chksis" nas exceções do FireWall!'); @@ -1674,15 +1818,24 @@ begin LogDebug('Gravando registros para auto-execução'); - // 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'); + // Somente para S.O. NOT NT LIKE + if NOT (g_oCacic.isWindowsNTPlataform) then + 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'); - bool_ExistsAutoRun := false; - if (GetValorChaveRegEdit('HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run\cacic2')=Dir + '\cacic2.exe') then - bool_ExistsAutoRun := true + bool_ExistsAutoRun := false; + if (GetValorChaveRegEdit('HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run\cacic2')=Dir + '\cacic2.exe') then + bool_ExistsAutoRun := true + else + SetValorChaveRegEdit('HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run\cacic2', Dir + '\cacic2.exe'); + End else - SetValorChaveRegEdit('HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run\cacic2', Dir + '\cacic2.exe'); + Begin + DelValorReg('HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run\cacic2'); + DelValorReg('HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run\CheckSystemRoutine'); + End; // Igualo as chaves ip_serv_cacic dos arquivos chksis.ini e cacic2.ini! SetValorDatMemoria('Configs.EnderecoServidor', v_ip_serv_cacic); @@ -1707,24 +1860,21 @@ begin strDataHoraGERCOLS_FIM := FormatDateTime('ddmmyyyyhhnnsszzz', GetFolderDate(Dir + '\modulos\ger_cols.exe')); LogDebug('Inicial => "' + strDataHoraGERCOLS_INI + '" Final => "' + strDataHoraGERCOLS_FIM + '"'); - LogDebug('Resgatando informações para identificação de alteração do agente SRCACIC'); - strDataHoraSRCACICSRV_FIM := FormatDateTime('ddmmyyyyhhnnsszzz', GetFolderDate(Dir + '\modulos\srcacicsrv.exe')); - LogDebug('Inicial => "' + strDataHoraSRCACICSRV_INI + '" Final => "' + strDataHoraSRCACICSRV_FIM + '"'); - // Caso o Cacic tenha sido baixado executo-o com parâmetro de configuração de servidor if ((strDataHoraCACIC2_INI <> strDataHoraCACIC2_FIM) OR (strDataHoraGERCOLS_INI <> strDataHoraGERCOLS_FIM)) then 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') then + + if (GetValorChaveRegEdit('HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run\cacic2')=Dir + '\cacic2.exe') and + (not g_oCacic.isWindowsNTPlataform()) or + (g_oCacic.isWindowsNTPlataform()) then Begin - if (v_exibe_informacoes = 'S') then - MessageDlg(#13#10+#13#10+'Sistema CACIC'+#13#10+#13#10+v_te_instala_frase_sucesso+#13#10+#13#10+#13#10 + '======================================================' + #13#10 + v_te_texto_janela_instalacao+ #13#10 +'======================================================',mtInformation,[mbok],0); + configs.Memo_te_instala_informacoes_extras.Lines.Add(#13#10+#13#10+'Sistema CACIC'+#13#10+#13#10+v_te_instala_frase_sucesso); End else Begin - if (v_exibe_informacoes = 'S') then - MessageDlg(#13#10+#13#10+'Sistema CACIC'+#13#10+#13#10+v_te_instala_frase_insucesso+#13#10+#13#10+#13#10 + '======================================================' + #13#10 + v_te_texto_janela_instalacao+ #13#10 +'======================================================',mtInformation,[mbok],0); + Configs.Memo_te_instala_informacoes_extras.Lines.Add(#13#10+#13#10+'Sistema CACIC'+#13#10+#13#10+v_te_instala_frase_insucesso); ComunicaInsucesso('1'); // O indicador "1" sinalizará que não foi devido a privilégio na estação End; End @@ -1735,25 +1885,76 @@ begin not bool_ExistsAutoRun or (strDataHoraCACIC2_INI <> strDataHoraCACIC2_FIM) then Begin - LogDebug('Executando '+Dir + '\cacic2.exe /ip_serv_cacic=' + v_ip_serv_cacic); - - // Caso tenha havido download de agentes principais, executar coletas imediatamente... - if (strDataHoraCACIC2_INI <> strDataHoraCACIC2_FIM) then - WinExec(PChar(Dir + '\cacic2.exe /ip_serv_cacic=' + v_ip_serv_cacic+ ' /execute'), SW_HIDE) + // 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); + if (strDataHoraCACIC2_INI <> strDataHoraCACIC2_FIM) then + WinExec(PChar(Dir + '\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); + End else - WinExec(PChar(Dir + '\cacic2.exe /ip_serv_cacic=' + v_ip_serv_cacic ), SW_HIDE); + Begin + + {*** 1 = SERVICE_STOPPED ***} + {*** 2 = SERVICE_START_PENDING ***} + {*** 3 = SERVICE_STOP_PENDING ***} + {*** 4 = SERVICE_RUNNING ***} + {*** 5 = SERVICE_CONTINUE_PENDING ***} + {*** 6 = SERVICE_PAUSE_PENDING ***} + {*** 7 = SERVICE_PAUSED ***} + + // Verifico se o serviço está instalado/rodando,etc. + wordServiceStatus := ServiceGetStatus(nil,'cacicservice'); + if (wordServiceStatus = 0) then + Begin + // Instalo e Habilito o serviço + LogDiario('Instalando CACICservice...'); + WinExec(PChar(HomeDrive + '\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); + End + else + LogDiario('Não instalei o CACICservice. Já está rodando...'); + End; End else LogDebug('Chave de Auto-Execução já existente ou Execução já iniciada...'); + End + else + Begin // Se NT/2000/XP/... + if (v_exibe_informacoes = 'S') and not bool_CommandLine then + MessageDLG(#13#10+'ATENÇÃO! Essa aplicação requer execução com nível administrativo.',mtError,[mbOK],0); + LogDiario('Sem Privilégios: Necessário ser administrador "local" da estação'); + ComunicaInsucesso('0'); // O indicador "0" (zero) sinalizará falta de privilégio na estação End; Except 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; +begin + Result := SERVICE_RUNNING = ServiceGetStatus(sMachine, sService); +end; + +function ServiceStopped(sMachine, sService: PChar): Boolean; +begin + Result := SERVICE_STOPPED = ServiceGetStatus(sMachine, sService); end; function FindWindowByTitle(WindowTitle: string): Hwnd; @@ -1855,7 +2056,6 @@ end; procedure TForm1.FS_SetSecurity(p_Target : String); var intAux : integer; v_FS_Security : TNTFileSecurity; - boolFound : boolean; begin v_FS_Security := TNTFileSecurity.Create(nil); v_FS_Security.FileName := ''; diff --git a/chksis/chksis.dpr b/chksis/chksis.dpr index ec39192..eef3feb 100755 --- a/chksis/chksis.dpr +++ b/chksis/chksis.dpr @@ -842,7 +842,7 @@ begin 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')) or (not FileExists(Dir + '\modulos\srcacicsrv.exe')) Then + If (not FileExists(Dir + '\cacic2.exe')) or (not FileExists(Dir + '\modulos\ger_cols.exe')) Then Begin // Busco as configurações para acesso ao ambiente FTP - Updates Request_Config := TStringList.Create; @@ -876,7 +876,6 @@ begin log_diario('------------------------------'); log_diario('Cacic2 - Agente do Systray.........: '+XML_RetornaValor('CACIC2', v_retorno)); log_diario('Ger_Cols - Gerente de Coletas........: '+XML_RetornaValor('GER_COLS', v_retorno)); - log_diario('SrCACIC - Suporte Remoto Seguro.....: '+XML_RetornaValor('SRCACICSRV', v_retorno)); log_diario('ChkSis - Verificador de Integridade: '+XML_RetornaValor('CHKSIS', v_retorno)); log_diario(':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::'); @@ -924,81 +923,47 @@ begin End; - // Verificação de versão do srcacic.exe e exclusão em caso de versão antiga - If (FileExists(Dir + '\modulos\srcacicsrv.exe')) Then - Begin - intAux := ChecaVersoesAgentes(Dir + '\modulos\srcacicsrv.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\srcacicsrv.exe')),'.','',[rfReplaceAll]); - v_versao_remota := StringReplace(XML_RetornaValor('SRCACICSRV' , 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\', 'srcacicsrv.exe'); - End; + // Tento detectar o Agente Principal e faço FTP caso não exista + If not FileExists(Dir + '\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); + 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); + bool_download_CACIC2 := true; + end; - // Tento detectar o Agente Principal e faço FTP caso não exista - If not FileExists(Dir + '\cacic2.exe') Then - begin - log_diario('Fazendo FTP de cacic2.exe a partir de ' + v_te_serv_updates + '/' + + // Tento detectar o Gerente de Coletas e faço FTP caso não exista + If (not FileExists(Dir + '\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); - 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); - 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 - 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'); - - 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, - 'ger_cols.exe', - Dir + '\modulos'); - end; - - // Tento detectar o Suporte Remoto Seguro e faço FTP caso não exista - If (not FileExists(Dir + '\modulos\srcacicsrv.exe')) Then - begin - log_diario('Fazendo FTP de srcacicsrv.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'); - - 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, - 'srcacicsrv.exe', - Dir + '\modulos'); - end; + v_te_path_serv_updates + ' para a pasta ' + Dir + '\modulos'); + + 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, + 'ger_cols.exe', + Dir + '\modulos'); + end; + End; // 5 segundos para espera de possível FTP... Sleep(5000); - + { Try // Crio a chave/valor chksis para autoexecução do Cacic, caso não exista esta chave/valor log_diario('Setando chave HLM../Run com ' + HomeDrive + '\chksis.exe'); @@ -1006,6 +971,7 @@ begin Except End; + bool_ExistsAutoRun := false; if (GetValorChaveRegEdit('HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run\cacic2')=Dir + '\cacic2.exe') then bool_ExistsAutoRun := true @@ -1018,7 +984,7 @@ begin Except End; End; - + } // 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 @@ -1030,7 +996,6 @@ begin else WinExec(PChar(Dir + '\cacic2.exe /ip_serv_cacic=' + v_ip_serv_cacic ), SW_HIDE); End; - log_diario('Não Executei. Chave de AutoExecução já existente...'); end; const diff --git a/chksis/chksis.res b/chksis/chksis.res index 2096004..b34c8a5 100755 Binary files a/chksis/chksis.res and b/chksis/chksis.res differ diff --git a/col_anvi/col_anvi.res b/col_anvi/col_anvi.res index 58b94eb..4ed0817 100755 Binary files a/col_anvi/col_anvi.res and b/col_anvi/col_anvi.res differ diff --git a/col_comp/col_comp.res b/col_comp/col_comp.res index fd6d0a3..dc7b7ec 100755 Binary files a/col_comp/col_comp.res and b/col_comp/col_comp.res differ diff --git a/col_hard/col_hard.res b/col_hard/col_hard.res index 3ccadc2..d0ef03b 100755 Binary files a/col_hard/col_hard.res and b/col_hard/col_hard.res differ diff --git a/col_moni/col_moni.res b/col_moni/col_moni.res index 2e2d138..d664c5a 100755 Binary files a/col_moni/col_moni.res and b/col_moni/col_moni.res differ diff --git a/col_patr/col_patr.res b/col_patr/col_patr.res index f71d919..7944157 100755 Binary files a/col_patr/col_patr.res and b/col_patr/col_patr.res differ diff --git a/col_soft/col_soft.res b/col_soft/col_soft.res index 0e26a95..49bdf09 100755 Binary files a/col_soft/col_soft.res and b/col_soft/col_soft.res differ diff --git a/col_undi/col_undi.res b/col_undi/col_undi.res index 667abed..b1c3847 100755 Binary files a/col_undi/col_undi.res and b/col_undi/col_undi.res differ diff --git a/ger_cols/ger_cols.dpr b/ger_cols/ger_cols.dpr index 01c1154..51fd0b4 100755 --- a/ger_cols/ger_cols.dpr +++ b/ger_cols/ger_cols.dpr @@ -67,7 +67,7 @@ var p_path_cacic, v_DatFileName, v_ResultCompress, v_ResultUnCompress, - v_te_so : string; + g_te_so : string; var v_Aguarde : TextFile; @@ -1177,19 +1177,16 @@ Begin strAux := 'A.B.C.D'; // Apenas para forçar que o Gerente extraia via _SERVER[REMOTE_ADDR] // Tratamentos de valores para tráfego POST: - // v_te_so => transformar ' ' em Razão: o mmcrypt se perde quando encontra ' ' (espaço) - v_te_so := StringReplace(v_te_so,' ','',[rfReplaceAll]); - v_AuxRequest.Values['te_node_address'] := StringReplace(EnCrypt(GetValorDatMemoria('TcpIp.TE_NODE_ADDRESS' , v_tstrCipherOpened),l_cs_compress),'+','',[rfReplaceAll]); - v_AuxRequest.Values['id_so'] := StringReplace(EnCrypt(g_oCacic.getWindowsStrId() , l_cs_compress),'+','',[rfReplaceAll]); - v_AuxRequest.Values['te_so'] := StringReplace(EnCrypt(v_te_so ,l_cs_compress),'+','',[rfReplaceAll]); + v_AuxRequest.Values['id_so'] := StringReplace(EnCrypt(g_oCacic.getWindowsStrId() ,l_cs_compress),'+','',[rfReplaceAll]); + v_AuxRequest.Values['te_so'] := StringReplace(EnCrypt(g_te_so ,l_cs_compress),'+','',[rfReplaceAll]); v_AuxRequest.Values['te_ip'] := StringReplace(EnCrypt(strAux ,l_cs_compress),'+','',[rfReplaceAll]); v_AuxRequest.Values['id_ip_rede'] := StringReplace(EnCrypt(GetValorDatMemoria('TcpIp.ID_IP_REDE' , v_tstrCipherOpened),l_cs_compress),'+','',[rfReplaceAll]); v_AuxRequest.Values['te_workgroup'] := StringReplace(EnCrypt(GetValorDatMemoria('TcpIp.TE_WORKGROUP' , v_tstrCipherOpened),l_cs_compress),'+','',[rfReplaceAll]); v_AuxRequest.Values['te_nome_computador']:= StringReplace(EnCrypt(GetValorDatMemoria('TcpIp.TE_NOME_COMPUTADOR', v_tstrCipherOpened),l_cs_compress),'+','',[rfReplaceAll]); - v_AuxRequest.Values['id_ip_estacao'] := StringReplace(EnCrypt(GetIP,l_cs_compress),'+','',[rfReplaceAll]); - v_AuxRequest.Values['te_versao_cacic'] := StringReplace(EnCrypt(getVersionInfo(p_path_cacic + 'cacic2.exe'),l_cs_compress),'+','',[rfReplaceAll]); - v_AuxRequest.Values['te_versao_gercols'] := StringReplace(EnCrypt(getVersionInfo(ParamStr(0)),l_cs_compress),'+','',[rfReplaceAll]); + v_AuxRequest.Values['id_ip_estacao'] := StringReplace(EnCrypt(GetIP ,l_cs_compress),'+','',[rfReplaceAll]); + v_AuxRequest.Values['te_versao_cacic'] := StringReplace(EnCrypt(getVersionInfo(p_path_cacic + 'cacic2.exe') ,l_cs_compress),'+','',[rfReplaceAll]); + v_AuxRequest.Values['te_versao_gercols'] := StringReplace(EnCrypt(getVersionInfo(ParamStr(0)) ,l_cs_compress),'+','',[rfReplaceAll]); v_Endereco_WS := GetValorDatMemoria('Configs.Endereco_WS', v_tstrCipherOpened); v_Endereco_Servidor := GetValorDatMemoria('Configs.EnderecoServidor', v_tstrCipherOpened); @@ -1243,7 +1240,7 @@ Begin if v_Debugs then Begin - Log_Debug('te_so => '+v_te_so); + Log_Debug('te_so => '+g_te_so); Log_Debug('Valores de REQUEST para envio ao Gerente WEB:'); for intAux := 0 to v_AuxRequest.count -1 do Log_Debug('#'+inttostr(intAux)+': '+v_AuxRequest[intAux]); @@ -1267,9 +1264,11 @@ Begin log_diario('Endereço: ' + strEndereco); log_diario('Mensagem: ' + Response_CS.DataString); result := '0'; + setValorDatMemoria('Configs.ConexaoOK','N',v_tstrCipherOpened); end Else Begin + setValorDatMemoria('Configs.ConexaoOK','S',v_tstrCipherOpened); result := Response_CS.DataString; end; Response_CS.Free; @@ -2081,9 +2080,12 @@ Begin Ver_UPD(StringReplace(v_scripter,'.exe','',[rfReplaceAll]),'Interpretador VBS' ,p_path_cacic + 'modulos\','',false); Ver_UPD('chksis' ,'Verificador de Integridade do Sistema',PegaWinDir(nil)+'\' ,'',false); + // O módulo de Suporte Remoto é opcional, através da opção Administração / Módulos + { log_diario('Verificando nova versão para módulo Suporte Remoto Seguro.'); // Caso encontre nova versão de srCACICsrv esta será gravada em modulos. Ver_UPD('srcacicsrv','Suporte Remoto Seguro',p_path_cacic + 'modulos\','',false); + } // Verifico existência do chksis.ini if not (FileExists(PegaWinDir(nil) + 'chksis.ini')) then @@ -2423,6 +2425,25 @@ Begin strAux := GeraPalavraChave; SetValorDatMemoria('Configs.te_palavra_chave',strAux, v_tstrCipherOpened); + + // Verifico se srCACIC está em execução e em caso positivo entrego a chave atualizada + Matar(p_path_cacic+'Temp\','aguarde_SRCACIC.txt'); + sleep(2000); + if (FileExists(p_path_cacic + 'Temp\aguarde_SRCACIC.txt')) then + Begin + // Alguns cuidados necessários ao tráfego e recepção de valores pelo Gerente WEB + // Some cares about send and receive at Gerente WEB + v_Aux := StringReplace(strAux ,' ' ,'' ,[rfReplaceAll]); + v_Aux := StringReplace(v_Aux ,'"' ,'' ,[rfReplaceAll]); + v_Aux := StringReplace(v_Aux ,'''','' ,[rfReplaceAll]); + v_Aux := StringReplace(v_Aux ,'\' ,'' ,[rfReplaceAll]); + v_Aux := StringReplace(EnCrypt(v_Aux,l_cs_compress) ,'+' ,'' ,[rfReplaceAll]); + + log_DEBUG('Invocando "'+p_path_cacic + 'modulos\srcacicsrv.exe -update [' + v_Aux + ']' ); + WinExec(PChar(p_path_cacic + 'modulos\srcacicsrv.exe -update [' + v_Aux + ']'),SW_NORMAL); + End; + + Request_SVG.Values['te_palavra_chave'] := EnCrypt(strAux,l_cs_compress); v_te_serv_cacic := GetValorDatMemoria('Configs.EnderecoServidor', v_tstrCipherOpened); @@ -2512,6 +2533,7 @@ Begin SetValorDatMemoria('Configs.CS_COLETA_COMPARTILHAMENTOS' ,UpperCase(DeCrypt(XML_RetornaValor('cs_coleta_compart' , strRetorno),true)), v_tstrCipherOpened); SetValorDatMemoria('Configs.CS_COLETA_UNID_DISC' ,UpperCase(DeCrypt(XML_RetornaValor('cs_coleta_unid_disc' , strRetorno),true)), v_tstrCipherOpened); SetValorDatMemoria('Configs.CS_COLETA_PATRIMONIO' ,UpperCase(DeCrypt(XML_RetornaValor('cs_coleta_patrimonio' , strRetorno),true)), v_tstrCipherOpened); + SetValorDatMemoria('Configs.CS_SUPORTE_REMOTO' ,UpperCase(DeCrypt(XML_RetornaValor('cs_suporte_remoto' , strRetorno),true)), v_tstrCipherOpened); SetValorDatMemoria('Configs.DT_VERSAO_CACIC2_DISPONIVEL' ,DeCrypt(XML_RetornaValor('dt_versao_cacic2_disponivel' , strRetorno),true) , v_tstrCipherOpened); SetValorDatMemoria('Configs.TE_HASH_CACIC2' ,DeCrypt(XML_RetornaValor('te_hash_cacic2' , strRetorno),true) , v_tstrCipherOpened); SetValorDatMemoria('Configs.DT_VERSAO_GER_COLS_DISPONIVEL' ,DeCrypt(XML_RetornaValor('dt_versao_ger_cols_disponivel' , strRetorno),true) , v_tstrCipherOpened); @@ -2746,9 +2768,13 @@ Begin // Caso encontre nova versão de Ger_Cols esta será gravada em temp e ocorrerá o autoupdate. Ver_UPD('ger_cols','Gerente de Coletas',p_path_cacic + 'modulos\','Temp',false); - log_diario('Verificando nova versão para módulo Suporte Remoto Seguro.'); - // Caso encontre nova versão de srCACICsrv esta será gravada em modulos. - Ver_UPD('srcacicsrv','Suporte Remoto Seguro',p_path_cacic + 'modulos\','Modulos',false); + // O módulo de Suporte Remoto é opcional... + if (GetValorDatMemoria('Configs.CS_SUPORTE_REMOTO' , v_tstrCipherOpened) = 'S') then + Begin + log_diario('Verificando nova versão para módulo Suporte Remoto Seguro.'); + // Caso encontre nova versão de srCACICsrv esta será gravada em modulos. + Ver_UPD('srcacicsrv','Suporte Remoto Seguro',p_path_cacic + 'modulos\','Modulos',false); + End; if (FileExists(p_path_cacic + 'Temp\ger_cols.exe')) or (FileExists(p_path_cacic + 'Temp\cacic2.exe')) then @@ -3359,7 +3385,7 @@ Begin else begin // Atualiza a data de última coleta SetValorDatMemoria('Configs.DT_HR_ULTIMA_COLETA',FormatDateTime('YYYYmmddHHnnss', Now), v_tstrCipherOpened); - log_diario('Todos os dados coletados foram enviados ao Gerente WEB.'); + log_diario('Os dados coletados - e não redundantes - foram enviados ao Gerente WEB.'); end; end; Except @@ -3387,11 +3413,6 @@ begin For intAux := 0 to tstrTripa1.Count -2 do p_path_cacic := p_path_cacic + tstrTripa1[intAux] + '\'; - g_oCacic.setCacicPath(p_path_cacic); - - // Obtem a string de identificação do SO (v_te_so), para uso nas comunicações com o Gerente WEB. - v_te_so := g_oCacic.getWindowsStrId(); - v_Debugs := false; if DirectoryExists(p_path_cacic + 'Temp\Debugs') then if (FormatDateTime('ddmmyyyy', GetFolderDate(p_path_cacic + 'Temp\Debugs')) = FormatDateTime('ddmmyyyy', date)) then @@ -3400,6 +3421,8 @@ begin log_DEBUG('Pasta "' + p_path_cacic + 'Temp\Debugs" com data '+FormatDateTime('dd-mm-yyyy', GetFolderDate(p_path_cacic + 'Temp\Debugs'))+' encontrada. DEBUG ativado.'); End; + g_oCacic.setCacicPath(p_path_cacic); + For intAux := 1 to ParamCount do if LowerCase(Copy(ParamStr(intAux),1,13)) = '/p_cipherkey=' then Begin @@ -3429,8 +3452,13 @@ begin v_tstrCipherOpened := TStrings.Create; v_tstrCipherOpened := CipherOpen(v_DatFileName); + // Obtem a string de identificação do SO (g_te_so), para uso nas comunicações com o Gerente WEB. + g_te_so := g_oCacic.getWindowsStrId(); + // Não tirar desta posição - SetValorDatMemoria('Configs.ID_SO',g_oCacic.getWindowsStrId(), v_tstrCipherOpened); + SetValorDatMemoria('Configs.ID_SO',g_te_so, v_tstrCipherOpened); + + log_DEBUG('Te_So obtido: "' + g_te_so +'"'); v_scripter := 'wscript.exe'; // A existência e bloqueio do arquivo abaixo evitará que Cacic2.exe chame o Ger_Cols quando este estiver em funcionamento diff --git a/ger_cols/ger_cols.res b/ger_cols/ger_cols.res index 3c058ec..36840ec 100755 Binary files a/ger_cols/ger_cols.res and b/ger_cols/ger_cols.res differ diff --git a/ini_cols/ini_cols.res b/ini_cols/ini_cols.res index 82fc265..f054e94 100755 Binary files a/ini_cols/ini_cols.res and b/ini_cols/ini_cols.res differ diff --git a/main.dfm b/main.dfm index 995a823..d7bf291 100755 --- a/main.dfm +++ b/main.dfm @@ -1,6 +1,6 @@ object FormularioGeral: TFormularioGeral - Left = 300 - Top = 107 + Left = 301 + Top = 108 HorzScrollBar.Visible = False VertScrollBar.Visible = False BiDiMode = bdLeftToRight @@ -143,10 +143,10 @@ object FormularioGeral: TFormularioGeral TextHeight = 13 object Panel3: TPanel Left = 648 - Top = 3 + Top = -1 Width = 68 - Height = 593 - Color = clCaptionText + Height = 597 + Color = clGray TabOrder = 3 object pnVersao: TPanel Left = 6 @@ -168,8 +168,8 @@ object FormularioGeral: TFormularioGeral object bt_Fechar_Infos_Gerais: TBitBtn Left = 6 Top = 252 - Width = 60 - Height = 27 + Width = 61 + Height = 33 Caption = 'Fechar' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText @@ -1339,9 +1339,9 @@ object FormularioGeral: TFormularioGeral end object Panel1: TPanel Left = 645 - Top = 2 + Top = 0 Width = 5 - Height = 591 + Height = 597 Color = clGreen TabOrder = 1 end @@ -1367,11 +1367,11 @@ object FormularioGeral: TFormularioGeral Left = 674 Top = 2 end - object PopupMenu1: TPopupMenu + object Popup_Menu_Contexto: TPopupMenu MenuAnimation = [maLeftToRight, maRightToLeft, maTopToBottom, maBottomToTop] - OnPopup = PopupMenu1Popup + OnPopup = Popup_Menu_ContextoPopup Left = 674 - Top = 58 + Top = 86 object Mnu_LogAtividades: TMenuItem Caption = 'Log de Atividades' OnClick = ExibirLogAtividades @@ -1401,4 +1401,154 @@ object FormularioGeral: TFormularioGeral OnClick = Sair end end + object Timer_InicializaTray: TTimer + Interval = 60000 + OnTimer = Timer_InicializaTrayTimer + Left = 674 + Top = 58 + end + object imgList_Icones: TImageList + ShareImages = True + Left = 674 + Top = 114 + Bitmap = { + 494C010103000400040010001000FFFFFFFFFF10FFFFFFFFFFFFFFFF424D3600 + 0000000000003600000028000000400000001000000001002000000000000010 + 00000000000000000000000000000000000000000000021C7800000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000125B000000000000000000C0C4D7FF000000000000 + 00001E1E1EFF0000000000000000000000000000000000000000000000000000 + 00000000000000000000F0F1F5FF0000000000000000C0C4D7FF000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 00000000000000000000F0F1F5FF000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 000000000000000000000000000000000000000000000032FD00000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 000000000000000000000032FD0000000000404B7BFF0032FDFF000000000000 + 00001E1E1EFFB9B9B9FF00000000000000000000000000000000000000000000 + 000000000000405EDCFF002BDCFF00000000404B7BFF0032FDFF000000000000 + 00000000000000000000000000001E1E1EFF1E1E1EFF1E1E1EFF000000000000 + 000000000000405EDCFF002BDCFF000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 000000000000000000000000000000000000305159000032FD00163886000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 000000000000163886000032FD001E333A000C32A8FF0131F6FFC0C7E3FF0000 + 00001E1E1EFF1E1E1EFFC0C0C0FF000000000000000000000000000000000000 + 000000000000032FDBFF002EF0FFC0C3CCFF0C32A8FF0131F6FFC0C7E3FF0000 + 000000000000000000001E1E1EFF0000FFFF0000FFFF1E1E1EFF000000000000 + 000000000000032FDBFF002EF0FFC0C3CCFF0000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 00000000000000000000000000000000000083DADC009DFFFE0083DADC000000 + 00000000000025375E005078C900679AFE00679AFE004B71BB00000000000000 + 00000000000092F3F3009DFFFE005F9DA00098F8F7FF6AB1B3FFB8D3D3FF0000 + 00001E1E1EFF62F6FFFF1E1E1EFF2E4065FFAFBFDEFFD0D7E8FF000000000000 + 000000000000A6FCFCFF88E3E3FFD7E9EAFF98F8F7FF6AB1B3FFB8D3D3FF0000 + 000000000000CCD2DDFF1E1E1EFF0000FFFF0000FFFF1E1E1EFF000000000000 + 000000000000A6FCFCFF88E3E3FFD7E9EAFF0000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000001126080098FDFC0030554500354F + 85006DA2FF00679AFE00679AFE0039558E004262A400679AFE00679AFE006DA2 + FF0000000000345951008FEEEB0011211100487E6AFF9BFEFDFFA8B9B8FFD2DB + EEFF1E1E1EFF4AE9F4FF5EEDFFFF1E1E1EFF5074B9FF679AFEFF6BA0FFFF3B59 + 95FF000000008FE6E7FF8AE5E4FFC4C9C6FF487E6AFF9BFEFDFFA8B9B8FFD2DB + EEFF689CFAFF679AFEFF6394F3FF2F4673FF334C7DFF679AFEFF6BA0FFFF3B59 + 95FF000000008FE6E7FF8AE5E4FFC4C9C6FF0000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000070E136001D2C49002EB8 + E700679AFE00679AFE002A3F6900679AFE00679AFE002F477700679AFE00679A + FE002EB8E7001E333A0070E1360000000000587251FF51A42AFF41639EFF5097 + E8FF1E1E1EFF45E8F2FF5EEAFFFF5FEEFFFF1E1E1EFF4F72B0FF679AFEFF6498 + FAFF4B93DFFF468F25FF61C330FF00000000587251FF51A42AFF41639EFF5097 + E8FF679AFEFF679AFEFF1E1E1EFF0000FFFF0000FFFF1E1E1EFF679AFEFF6498 + FAFF4B93DFFF468F25FF61C330FF000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 000000000000000000000000000000000000000000004262A400679AFE0030C0 + F00030C0F0006494F800679AFE00679AFE00679AFE00679AFE005F91F0002EB8 + E70030C8F9006DA2FF004B71BB0000000000D2D2D4FF2F5B1EFF3FA2E2FF3F99 + D9FF42A0E3FF1E1E1EFF5EEAFFFF5EEAFFFF61F2FFFF1E1E1EFF4E72B8FF33B5 + E9FF33B9EDFF36577FFFA3AEB5FF00000000D2D2D4FF2F5B1EFF3FA2E2FF3F99 + D9FF42A0E3FF679AFEFF1E1E1EFF0000FFFF0000FFFF1E1E1EFF5F95F3FF33B5 + E9FF33B9EDFF36577FFFA3AEB5FF000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 000000000000000000000000000000000000679AFE00679AFE00679AFE00679A + FE005F91F000679AFE00679AFE00679AFE00679AFE00679AFE00679AFE005690 + E600679AFE00679AFE00679AFE005A88E2006090EEFF679AFEFF679AFEFF40A1 + E1FF5C93EFFF1E1E1EFF5FEDFFFF5EEAFFFF5EEAFFFF60F1FFFF1E1E1EFF2C8D + B1FF6498FAFF679AFEFF679AFEFFCBD0DAFF6090EEFF679AFEFF679AFEFF40A1 + E1FF5C93EFFF679AFEFF1E1E1EFF0000FFFF0000FFFF1E1E1EFF679AFEFF38B0 + EAFF6498FAFF679AFEFF679AFEFFCBD0DAFF0000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000004262A400679AFE00679AFE00679A + FE005A88E2005078C9004262A400679AFE00679AFE005781D9004B71BB005781 + D900679AFE00679AFE00679AFE004669B0006597F9FF679AFEFF679AFEFF1E1E + 1EFF55EBFFFF55EAFFFF5EEAFFFF1E1E1EFF1E1E1EFF1E1E1EFF1E1E1EFF1E1E + 1EFF5F8DE7FF679AFEFF679AFEFF526385FF6597F9FF679AFEFF679AFEFF679A + FEFF6394F6FF6090EFFF1E1E1EFF0000FFFF0000FFFF0000FFFF1E1E1EFF6395 + F7FF679AFEFF679AFEFF679AFEFF526385FF0000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 000000000000000000000000000000000000000000003D5C99005E8DE900679A + FE00679AFE00679AFE00679AFE00679AFE00679AFE00679AFE00679AFE00679A + FE00679AFE005A88E20025375E000000000004070BFF6190F0FF6698FCFF1E1E + 1EFF4FE9F5FF5EEAFFFF5EEAFFFF5FEEFFFF1E1E1EFF1E1E1EFF1E1E1EFF1E1E + 1EFF1E1E1EFF6496F7FF263A5EFFD0D0D0FF04070BFF6190F0FF6698FCFF679A + FEFF6BA0FFFF679AFEFF679AFEFF2F4F90FF0000FFFF0000FFFF0000FFFF1E1E + 1EFF6699FDFF6496F7FF263A5EFFD0D0D0FF0000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 000000000000000000000000000000000000404040FF000000FF000000FF0203 + 03FF034F5EFF5EEBFFFF5EEAFFFF5EEAFFFF23E2F8FF1F2228FF0F1626FF0206 + 0CFF000000FF000000FF000000FF00000000404040FF000000FF000000FF0203 + 03FF0000FFFF0000FFFF1E1E1EFF476BB2FF2A3F6AFF0000FFFF0000FFFF1E1E + 1EFF000000FF000000FF000000FF000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000092E00000724000007 + 2400000724000007240000072400000724000007240000072400000724000007 + 2400000724000007240000092E000000000000000000000109FF000109FF0001 + 09FF1E1E1EFF5AEFFDFF5EEAFFFF5EEAFFFF5EEAFFFF149DADFF0D0D0EFF0001 + 09FF000109FF000109FF000105FF0000000000000000000109FF000109FF0001 + 09FF0000FFFF0000FFFF1E1E1EFF1E1E1EFF000109FF1E1E1EFF0000FFFF1E1E + 1EFF000109FF000109FF000105FF000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 00000000000000000000000000000000000000000000000000004DBCB1004DBC + B1004DBCB1004DBCB1004DBCB1004DBCB1004DBCB1004DBCB1004DBCB1004DBC + B1004DBCB1004DBCB1000000000000000000000000001B3C7DFF144486FF1444 + 86FF1E1E1EFF0AA2B7FF5EEAFFFF5EEAFFFF5EEAFFFF5EEAFFFF10353AFF1E1E + 1EFF144486FF134081FFD0D2E0FF00000000000000001B3C7DFF144486FF1444 + 86FF0000FFFF0000FFFF0000FFFF1E1E1EFF1E1E1EFF0000FFFF0000FFFF1E1E + 1EFF1E1E1EFF134081FFD0D2E0FF000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000296355002757 + BC006DC1830027636C00325B7F0034662900113562003C6C960060B150001247 + A1005693AB0000000000000000000000000000000000000000005E8A57FF061C + 62FF355B54FF1D311FFF5DEEFFFF5EEAFFFF5EEAFFFF5EEAFFFF2AC4D5FF1D1F + 1CFF0B165DFFE9FAF5FF000000000000000000000000000000005E8A57FF061C + 62FF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF1E1E + 1EFF1E1E1EFFE9FAF5FF00000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 00000000000000000000000000000000000000000000000000001854B8006ABD + FE006ECE4F000B3AB70073C1D4005AB32B000333EE0089E9FF006BD335000026 + C10077C7CB004E9F2A00000000000000000000000000D0D7F5FF54AE4DFF1946 + E0FF88ECB6FF418E54FF54F0FFFF5EEAFFFF5EEAFFFF5EEAFFFF5EEAFFFF1768 + 74FF1E1E1EFF78D39AFF000000000000000000000000D0D7F5FF54AE4DFF1946 + E0FF5FA87CFF1E1E1EFF1E1E1EFF1E1E1EFF1E1E1EFF1E1E1EFF1E1E1EFF1E1E + 1EFF1E1E1EFF78D39AFF00000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 000075CD91003B855B000000000000000000000000000000000063B55900205C + 8E000000000000000000000000000000000000000000000000006BC061FF1E4A + CFFF77CBC0FF639D64FF1E1E1EFF1E1E1EFF1E1E1EFF1E1E1EFF1E1E1EFF1E1E + 1EFF555555FF1E1E1EFF000000000000000000000000000000006BC061FF1E4A + CFFF77CBC0FF639D64FF1E1E1EFF1E1E1EFF1E1E1EFF1E1E1EFF1E1E1EFF1E1E + 1EFF557FEFFF88E1B9FF00000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 000000000000000000000000000000000000424D3E000000000000003E000000 + 2800000040000000100000000100010000000000800000000000000000000000 + 000000000000000000000000FFFFFF00BFFDB7FDBFFD0000BFFD33F93E390000 + 1FF811F81C380000183810381838000000080008000800008001000100010000 + 8001000100010000000000000000000000000000000000000001000000000000 + 80010001000100008001800180010000C003800180010000C007C003C0030000 + C003800380030000F3CFC003C003000000000000000000000000000000000000 + 000000000000} + end end diff --git a/main.pas b/main.pas index 384e2be..29198fe 100755 --- a/main.pas +++ b/main.pas @@ -37,8 +37,11 @@ uses Windows, DCPbase64, ComCtrls, IdBaseComponent, - IdComponent, Buttons, - CACIC_Library; + IdComponent, + Buttons, + CACIC_Library, + ImgList, + Graphics; //IdTCPServer; //IdFTPServer; @@ -49,16 +52,16 @@ var p_path_cacic, p_path_cacic_ini, p_Shell_Command, p_Shell_Path, - v_versao : string; - BatchFile : TStringList; + v_versao, + g_te_so, v_CipherKey, v_SeparatorKey, v_IV, v_DatFileName, v_DataCacic2DAT, v_Tamanho_Arquivo, - v_te_so, strConfigsPatrimonio : string; + BatchFile : TStringList; v_tstrCipherOpened : TStrings; boolCrypt, boolDebugs : Boolean; @@ -106,7 +109,7 @@ type Pn_Linha5_TCPIP: TPanel; Timer_Nu_Intervalo: TTimer; Timer_Nu_Exec_Apos: TTimer; - PopupMenu1: TPopupMenu; + Popup_Menu_Contexto: TPopupMenu; Mnu_LogAtividades: TMenuItem; Mnu_Configuracoes: TMenuItem; Mnu_ExecutarAgora: TMenuItem; @@ -161,6 +164,8 @@ type Panel3: TPanel; pnVersao: TPanel; bt_Fechar_Infos_Gerais: TBitBtn; + Timer_InicializaTray: TTimer; + imgList_Icones: TImageList; procedure RemoveIconesMortos; procedure ChecaCONFIGS; procedure CriaFormSenha(Sender: TObject); @@ -178,6 +183,7 @@ type procedure Mnu_InfosPatrimoniaisClick(Sender: TObject); procedure HabilitaTCP; procedure HabilitaPatrimonio; + procedure HabilitaSuporteRemoto; procedure Matar(v_dir,v_files: string); Procedure DelValorReg(Chave: String); @@ -198,13 +204,13 @@ type const AUsername, APassword: String; var AAuthenticated: Boolean); } procedure Mnu_SuporteRemotoClick(Sender: TObject); -// procedure StartVNCServer; - procedure PopupMenu1Popup(Sender: TObject); + procedure Popup_Menu_ContextoPopup(Sender: TObject); + procedure Timer_InicializaTrayTimer(Sender: TObject); private ShutdownEmExecucao : Boolean; IsMenuOpen : Boolean; NotifyStruc : TNotifyIconData; {Estrutura do tray icon} - procedure InicializaTray(v_Hint:string); + procedure InicializaTray; procedure Finaliza; procedure VerificaDebugs; procedure MontaVetoresPatrimonio(p_strConfigs : String); @@ -220,7 +226,6 @@ type // Shutdown do Windows e "derrubar" o Cacic. procedure WMQueryEndSession(var Msg : TWMQueryEndSession); Message WM_QUERYENDSESSION; procedure WMMENUSELECT(var msg: TWMMENUSELECT); message WM_MENUSELECT; - function GetFileHash(strFileName : String) : String; public Function Implode(p_Array : TStrings ; p_Separador : String) : String; function HomeDrive : string; @@ -239,15 +244,6 @@ type var FormularioGeral : TFormularioGeral; boolServerON : Boolean; - handleStartServerThreadID, - handleStartVNCThreadID, - handleCacicRC : THandle; - dwordStartServerID, - dwordStartVNCID : dword; - procStartServer : procedure; stdcall; - procStopServer : procedure; stdcall; - threadCacicRC : TThread; - // Some constants that are dependant on the cipher being used // Assuming MCRYPT_RIJNDAEL_128 (i.e., 128bit blocksize, 256bit keysize) @@ -260,7 +256,7 @@ implementation {$R *.dfm} Uses StrUtils, Inifiles, frmConfiguracoes, frmSenha, frmLog, - Math,md5,LibXmlParser,WinVNC; + Math,LibXmlParser,WinVNC; // Estruturas de dados para armazenar os itens da uon1, uon1a e uon2 type @@ -291,16 +287,6 @@ var VetorUON1 : TVetorUON1; VetorUON1a : TVetorUON1a; VetorUON2 : TVetorUON2; -// Para cálculo de HASH de determinado arquivo. -// Objetivo principal: Verificar autenticidade de agentes quando em trabalho cooperativo -// Anderson Peterle - Dataprev/ES - 08/Maio/2008 -function TFormularioGeral.GetFileHash(strFileName : String) : String; -Begin - Result := 'Arquivo "'+strFileName+'" Inexistente!'; - if (FileExists(strFileName)) then - Result := MD5Print(MD5File(strFileName)); -End; - // Pad a string with zeros so that it is a multiple of size function TFormularioGeral.PadWithZeros(const str : string; size : integer) : string; var @@ -930,7 +916,6 @@ end; // Verifico a existência do Gerente de Coletas, caso não exista, o chksis.exe fará download! function TFormularioGeral.ChecaGERCOLS : boolean; -var strFraseVersao : String; Begin Result := true; @@ -945,11 +930,8 @@ Begin Matar(p_path_cacic + 'modulos\','ger_cols.exe'); - strFraseVersao := 'CACIC V:' + getVersionInfo(ParamStr(0)); - if not (getValorDatMemoria('TcpIp.TE_IP',v_tstrCipherOpened) = '') then - strFraseVersao := strFraseVersao + #13#10 + 'IP: '+getValorDatMemoria('TcpIp.TE_IP',v_tstrCipherOpened); + InicializaTray; - InicializaTray(strFraseVersao); log_diario('Acionando recuperador de Módulo Gerente de Coletas.'); log_DEBUG('Recuperador de Módulo Gerente de Coletas: '+HomeDrive + '\chksis.exe'); WinExec(PChar(HomeDrive + '\chksis.exe'),SW_HIDE); @@ -959,7 +941,7 @@ Begin if not(v_Tamanho_Arquivo = '0') and not(v_Tamanho_Arquivo = '-1') then Begin log_diario('Módulo Gerente de Coletas RECUPERADO COM SUCESSO!'); - InicializaTray(''); + InicializaTray; Result := True; End else @@ -1099,6 +1081,13 @@ Begin if (getValorDatMemoria('Configs.CS_COLETA_PATRIMONIO',v_tstrCipherOpened) = 'S') then Mnu_InfosPatrimoniais.Enabled := True; End; +procedure TFormularioGeral.HabilitaSuporteRemoto; +Begin + // Desabilita/Habilita a opção de Suporte Remoto + Mnu_SuporteRemoto.Enabled := False; + if (getValorDatMemoria('Configs.CS_SUPORTE_REMOTO',v_tstrCipherOpened) = 'S') then Mnu_SuporteRemoto.Enabled := True; +End; + //Para buscar do Arquivo INI... // Marreta devido a limitações do KERNEL w9x no tratamento de arquivos texto e suas seções @@ -1184,7 +1173,7 @@ begin // Não mostrar o formulário... Application.ShowMainForm:=false; g_oCacic := TCACIC.Create; - g_oCacic.showTrayIcon(false); + //g_oCacic.showTrayIcon(false); boolCrypt := true; Try @@ -1329,12 +1318,7 @@ begin log_diario('PROBLEMAS SETANDO VARIÁVEIS GLOBAIS!'); End; - // Envia o ícone para a bandeja com HINT mostrando Versão... - strFraseVersao := 'CACIC v:' + getVersionInfo(ParamStr(0)); - if not (getValorDatMemoria('TcpIp.TE_IP',v_tstrCipherOpened) = '') then - strFraseVersao := strFraseVersao + char(13) + char(10) + 'IP: '+ getValorDatMemoria('TcpIp.TE_IP',v_tstrCipherOpened); - pnVersao.Caption := 'V. ' + getVersionInfo(ParamStr(0)); - InicializaTray(strFraseVersao); + InicializaTray; CipherClose; End else @@ -1391,6 +1375,8 @@ Begin // Desabilita/Habilita a opção de Informações Gerais HabilitaTCP; + // Desabilita/Habilita a opção de Suporte Remoto + HabilitaSuporteRemoto; Except log_diario('PROBLEMAS NA INICIALIZAÇÃO (1)'); End; @@ -1515,6 +1501,8 @@ begin CipherOpen; + SetValorDatMemoria('Configs.TE_SO',g_te_so,v_tstrCipherOpened); + try if FindCmdLineSwitch('execute', True) or FindCmdLineSwitch('atualizacao', True) or @@ -1546,7 +1534,7 @@ begin intContaExec := 2; // Muda HINT - InicializaTray(''); + InicializaTray; // Loop para possível necessidade de updates de Agente Principal e/ou Gerente de Coletas For intAux := intContaExec to 2 do @@ -1575,11 +1563,14 @@ begin Invoca_GerCols(nil,'coletas'); sleep(3000); // Pausa para início do Gerente de Coletas e criação do arquivo temp\aguarde_GER.txt - // Pausas de 10 segundos para o caso de ser(em) baixada(s) nova(s) versão(ões) de Ger_Cols e/ou Cacic2. + InicializaTray; + + // Pausas de 15 segundos para o caso de ser(em) baixada(s) nova(s) versão(ões) de Ger_Cols e/ou Cacic2. while not Pode_Coletar do Begin log_DEBUG('Aguardando mais 15 segundos...'); sleep(15000); + InicializaTray; End; Mnu_InfosPatrimoniais.Caption := v_Aux1; Mnu_InfosTCP.Caption := v_Aux2; @@ -1633,6 +1624,9 @@ begin // Desabilita/Habilita a opção de Informações de TCP/IP HabilitaTCP; + // Desabilita/Habilita a opção de Suporte Remoto + HabilitaSuporteRemoto; + // Para evitar uma reexecução de Ger_Cols sem necessidade... intContaExec := 3; End; @@ -1692,12 +1686,8 @@ begin End; End; - // Volta a mostrar a versão no HINT... - strFraseVersao := 'CACIC V:' + getVersionInfo(ParamStr(0)); - if not (getValorDatMemoria('TcpIp.TE_IP',v_tstrCipherOpened) = '') then - strFraseVersao := strFraseVersao + #13#10 + 'IP: '+getValorDatMemoria('TcpIp.TE_IP',v_tstrCipherOpened); - InicializaTray(strFraseVersao); + InicializaTray; except log_diario('PROBLEMAS AO TENTAR ATIVAR COLETAS.'); @@ -1768,35 +1758,77 @@ end; // Todo o código deste ponto em diante está relacionado às rotinas de // de inclusão do ícone do programa na bandeja do sistema //======================================================================= -procedure TFormularioGeral.InicializaTray(v_Hint:string); +procedure TFormularioGeral.InicializaTray; +var Icon : TIcon; + v_intStatus : integer; + v_strHint : String; +const NORMAL = 0; + OCUPADO = 1; + DESCONFIGURADO = 2; begin + Icon := TIcon.Create; - {Estrutura do tray icon sendo criada.} - NotifyStruc.cbSize := SizeOf(NotifyStruc); - NotifyStruc.Wnd := Handle; - NotifyStruc.uID := 1; - NotifyStruc.uFlags := NIF_ICON or NIF_TIP or NIF_MESSAGE; - NotifyStruc.uCallbackMessage := WM_MYMESSAGE; {User defined message} - NotifyStruc.hIcon := Application.Icon.Handle; + // Monto a frase a ser colocada no Hint + v_strHint := 'CACIC v:' + getVersionInfo(ParamStr(0)); + if not (getValorDatMemoria('TcpIp.TE_IP',v_tstrCipherOpened) = '') then + v_strHint := v_strHint + char(13) + char(10); + v_strHint := v_strHint + 'IP: '+ getValorDatMemoria('TcpIp.TE_IP',v_tstrCipherOpened); - if (v_Hint = '') then - v_Hint := 'Aguarde...'; + // Mostro a versão no painel de Informações Gerais + pnVersao.Caption := 'V. ' + getVersionInfo(ParamStr(0)); - log_DEBUG('Setando o HINT do Systray para: "'+v_Hint+'"'); + // Estrutura do tray icon sendo criada. + NotifyStruc.cbSize := SizeOf(NotifyStruc); + NotifyStruc.Wnd := Handle; + NotifyStruc.uID := 1; + NotifyStruc.uFlags := NIF_ICON or NIF_TIP or NIF_MESSAGE; + NotifyStruc.uCallbackMessage := WM_MYMESSAGE; //User defined message + + // Tento apagar os arquivos indicadores de ações de coletas + FormularioGeral.Matar(p_path_cacic+'temp\','aguarde_GER.txt'); + FormularioGeral.Matar(p_path_cacic+'temp\','aguarde_INI.txt'); - // Atualiza o conteúdo do tip da bandeja - StrPCopy(NotifyStruc.szTip, v_Hint); + v_intStatus := NORMAL; - if (getValorDatMemoria('Configs.IN_EXIBE_BANDEJA',v_tstrCipherOpened) <> 'N') Then + // Caso os indicadores de ações de coletas não existam, ativo o ícone normal/desconectado... + if not FileExists(p_path_cacic+'temp\aguarde_GER.txt') and + not FileExists(p_path_cacic+'temp\aguarde_INI.txt') then Begin - Shell_NotifyIcon(NIM_ADD, @NotifyStruc); + if not (FormularioGeral.getValorDatMemoria('Configs.ConexaoOK',v_tstrCipherOpened)='S') then + Begin + v_strHint := v_strHint + ' SERVIDOR NÃO ENCONTRADO!'; + v_intStatus := DESCONFIGURADO; + End; End - else + else Begin - Shell_NotifyIcon(HIDE_WINDOW,@NotifyStruc); - Shell_NotifyIcon(NIM_Delete,@NotifyStruc); + v_intStatus := OCUPADO; + v_strHint := 'Aguarde...'; End; - Shell_NotifyIcon(nim_Modify,@NotifyStruc); + + imgList_Icones.GetIcon(v_intStatus,Icon); + + NotifyStruc.hIcon := Icon.Handle; + + log_DEBUG('Setando o HINT do Systray para: "'+v_strHint+'"'); + + // Atualiza o conteúdo do tip da bandeja + StrPCopy(NotifyStruc.szTip, v_strHint); + + if (getValorDatMemoria('Configs.IN_EXIBE_BANDEJA',v_tstrCipherOpened) <> 'N') Then + Begin + Shell_NotifyIcon(NIM_ADD, @NotifyStruc); + End + else + Begin + Shell_NotifyIcon(HIDE_WINDOW,@NotifyStruc); + Shell_NotifyIcon(NIM_Delete,@NotifyStruc); + End; + Shell_NotifyIcon(nim_Modify,@NotifyStruc); + + Application.ProcessMessages; + + Icon.Free; end; procedure TFormularioGeral.WMSysCommand; @@ -1817,9 +1849,13 @@ begin Mnu_InfosPatrimoniais.Enabled := False; // Habilita a opção de menu caso a coleta de patrimonio esteja habilitado. HabilitaPatrimonio; + + // Habilita a opção de menu caso o suporte remoto esteja habilitado. + HabilitaSuporteRemoto; + SetForegroundWindow(Handle); GetCursorPos(Posicao); - PopupMenu1.Popup(Posicao.X, Posicao.Y); + Popup_Menu_Contexto.Popup(Posicao.X, Posicao.Y); end; end; @@ -2235,7 +2271,7 @@ begin (strCmd = 'Exit') then AResponseinfo.ContentText := 'OK' else - AResponseinfo.ContentText := 'COMANDO NÃO PERMITIDO!'; + AResponseinfo.ContentText := 'COMANDO NÃO RECONHECIDO!'; End else AResponseinfo.ContentText := 'ACESSO NÃO PERMITIDO!'; @@ -2276,7 +2312,6 @@ begin End else Begin - GetWinVer; log_DEBUG('Invocando "'+p_path_cacic + 'modulos\srcacicsrv.exe"...'); Log_Diario('Ativando Suporte Remoto Seguro.'); boolAux := boolCrypt; @@ -2291,7 +2326,7 @@ begin strPalavraChave := StringReplace(strPalavraChave,'\' ,'' ,[rfReplaceAll]); strPalavraChave := StringReplace(EnCrypt(strPalavraChave),'+','',[rfReplaceAll]); - strTeSO := StringReplace(v_te_so ,' ' ,'' ,[rfReplaceAll]); + strTeSO := StringReplace(FormularioGeral.getValorDatMemoria('Configs.TE_SO', v_tstrCipherOpened),' ','',[rfReplaceAll]); strTeSO := StringReplace(EnCrypt(strTeSO),'+','',[rfReplaceAll]); strTeNodeAddress := StringReplace(FormularioGeral.getValorDatMemoria('TcpIp.TE_NODE_ADDRESS' , v_tstrCipherOpened),' ','' ,[rfReplaceAll]); @@ -2333,48 +2368,13 @@ begin BoolServerON := true; End; - { - //handleCacicRC := LoadLibrary('modulos\cacicrc.dll'); - threadCacicRC := WinVNCThread.Create(false); - -// if (handleCacicRC > 0) then - if (threadCacicRC.Handle > 0) then - Begin - //procStartServer := GetProcAddress(handleCacicRC,'StartServer'); - WinVNCThread.Synchronize(threadCacicRC,StartVNCServer); - if not boolServerON then - begin - handleStartVNCThreadID := CreateThread(nil, 0, @TFormularioGeral.StartVNCServer, nil, 0, dwordStartVNCID); - if (handleStartVNCThreadID <> 0) then - boolServerON := true; - end - else - begin - procStopServer := GetProcAddress(handleCacicRC,'StopServer'); - procStopServer; - TerminateThread(dwordStartServerID, 0); - TerminateThread(handleStartServerThreadID, 0); - FreeProcInstance(@procStartServer); - FreeProcInstance(@procStopServer); - FreeLibrary(handleCacicRC); - boolServerON := false; - end; - End - else - MessageBox(0, 'Não foi possivel carregar a biblioteca de acesso remoto!', 'Erro', MB_ICONERROR); - - } -end; -{ -procedure TFormularioGeral.StartVNCServer; -begin - handleStartServerThreadID := CreateThread(nil, 0, @procStartServer, nil, 0, dwordStartServerID); end; -} -procedure TFormularioGeral.PopupMenu1Popup(Sender: TObject); + +procedure TFormularioGeral.Popup_Menu_ContextoPopup(Sender: TObject); begin VerificaDebugs; - if FileExists(p_path_cacic + 'modulos\srcacicsrv.exe') then + if (getValorDatMemoria('Configs.CS_SUPORTE_REMOTO',v_tstrCipherOpened) = 'S') and + (FileExists(p_path_cacic + 'modulos\srcacicsrv.exe')) then Mnu_SuporteRemoto.Enabled := true else Mnu_SuporteRemoto.Enabled := false; @@ -2391,4 +2391,11 @@ begin end; +procedure TFormularioGeral.Timer_InicializaTrayTimer(Sender: TObject); +begin + Timer_InicializaTray.Enabled := false; + InicializaTray; + Timer_InicializaTray.Enabled := true; +end; + end. diff --git a/mapa/mapacacic.res b/mapa/mapacacic.res index f83c94d..d87d360 100755 Binary files a/mapa/mapacacic.res and b/mapa/mapacacic.res differ diff --git a/testacrypt/testacrypt.res b/testacrypt/testacrypt.res index 394a8ce..20a6172 100755 Binary files a/testacrypt/testacrypt.res and b/testacrypt/testacrypt.res differ diff --git a/vaca/vaca.res b/vaca/vaca.res index b0f447b..796021a 100755 Binary files a/vaca/vaca.res and b/vaca/vaca.res differ diff --git a/vacon/vacon.res b/vacon/vacon.res index 8fe175d..ef3ee0d 100755 Binary files a/vacon/vacon.res and b/vacon/vacon.res differ -- libgit2 0.21.2