Autor Beitrag
crowley
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic star
Beiträge: 406

Win XP, Win Vista, Mandriva, Ubuntu
Delphi 4-8, Delphi 2006, Delphi 2007
BeitragVerfasst: Mi 29.11.06 17:17 
Huhu ;)

Ich habe mal wieder ein schwierigeres Problem zu lösen. Ich habe mittels der angehängten Unit (und ein paar kleinen Anpassungen daran) aus einer unserer Anwendungen einen Service gemacht. Der große Vorteil dabei ist, dass die Anwendung nach wie vor auch eben als "Anwendung" und eben auch als "Dienst" genutzt werden kann.

Die einzige Einschränkung ist, dass der Dienst nur als "LocalSystem" bzw. als "System" genutzt werden kann. Wenn der Dienst unter einem anderen UserContext gestartet werden soll, scheitert der Vergleich mit CompareText. Denn in dem ServiceStartName steht die Userid in dem Format %Domain%\%UserId% und GetUserName liefert nur die %UserId%.

Das Problem liegt an dieser Stelle:
ausblenden Delphi-Quelltext
1:
2:
3:
4:
5:
6:
7:
   if FIsService then begin
      Size := 256;
      SetLength(UserName, Size);
      GetUserName(PChar(UserName), Size);
      SetLength(UserName, StrLen(PChar(UserName)));
      FIsService := CompareText(UserName, ServiceStartName) = 0;
   end;


Lange Rede, Kurzer Sinn... dieses Problem ließ sich lösen in dem ich via GetUserNameEx den entsprechenden String erfrage. Auch dabei gibt es zwei Probleme: Zum einen liefert diese Abfrage bei dem SYSTEM- Account %Domain%\%Rechnername%$ (im ServiceStartName steht 'LocalSystem') zurück und zum anderen bei lokalen Usern %Rechnername%\%UserId% (im ServiceStartName steht .\%UserId%).

Prinzipiell ließ sich auch dies lösen, allerdings mit einer anderen Einschränkung: Falls der angemeldete User dem User entspricht, in dessen Kontext dieser Dienst laufen soll, kann nämlich nur noch der Dienst und nicht die "Anwendung" gestartet werden, denn mein Skript führt immer zu einer Übereinstimmung. Nun suche ich eine Möglichkeit, wie ich herausfinden kann, ob die Anwendung z.B. über den Dienste Control Manager gestartet wurde oder eben über einen Doppelklick auf die Exe.

Bisher habe ich dafür zwei theoretische Ansätze:
1. Bei Diensten ist der Parent Process immer services.exe
2. Prüfung des aktuellen Arbeitsverzeichnisses. Wenn das Arbeitsverzeichnis = Anwendungspfad ist, ist die Anwendung aufgerufen worden, wenn das Arbeitsverzeichnis = %Windows%\System32 ist, dann soll es als Dienst gestartet werden.

Mein Wunsch wäre es, meinen ersten Lösungsvorschlag zu realisieren, aber ich finde keinen geeigneten Ansatz dafür. Mit NtQuerySystemInformation bin ich nicht wirklich weit gekommen, denke aber, dass das ein gangbarer Weg dafür wäre.
Die zweite Lösung sieht für mich nach einem "schmutzigen Trick" aus und ich zweifele, dass dies in allen Konstellationen und Konfigurationen läuft.

Kann mir irgendwer hier weiterhelfen? Hat jemand eine Idee dazu, wie ich es mit NtQuerySystemInformation hinbekommen kann oder hat schon selbst etwas vergleichbares "gebastelt"? Oder fällt euch noch ein anderer Weg ein?


ausblenden volle Höhe Delphi-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
//------------------------------------------------------------------------------
function Installing: Boolean;
begin
  Result := FindCmdLineSwitch('INSTALL', ['-','\','/'], True) or
            FindCmdLineSwitch('UNINSTALL', ['-','\','/'], True);
end;

//------------------------------------------------------------------------------
function IsQuiet: Boolean;
begin
  Result := FindCmdLineSwitch('QUIET', ['-','\','/'], True);
end;

//------------------------------------------------------------------------------
function GnStartService(ADisplayName: string): Boolean;
var
  loc_Terminate         : Boolean;
  loc_Icon              : Integer;
  loc_UserName,
  loc_ServiceStartName,
  loc_Msg               : string;
begin
  GnDisplayName := ADisplayName;
  GnServiceName := StringReplace(ADisplayName, ' ', '_', [rfReplaceAll]);

  loc_icon      := MB_ICONINFORMATION;
  loc_Msg       := EmptyStr;

  { Check for a previous instance of the application }
//  if IsWTS or IsSingleUserWTS then
//    GnMutexName := 'Global\' + GnServiceName
//  else
    GnMutexName := GnServiceName;

  GnMutexHandle := CreateMutex(nil, True, PChar(GnMutexName));
  if (GnMutexHandle = 0) or (GetLastError = ERROR_ALREADY_EXISTS) then begin
    { A previous instance of the application was found }
    { quit execution and show error message (if demanded) }
    if not IsQuiet then
      MessageBox(
                 0, PChar(Format('%s already running', [ADisplayName])),
                 PChar(ADisplayName), MB_ICONERROR
                );

    CloseHandle(GnMutexHandle);
    Halt;
  end
  else begin
    { No previous instance of the application was found:
      Release Mutex and go on }

    ReleaseMutex(GnMutexHandle);
    CloseHandle(GnMutexHandle);
  end;

  { Check for installation mode }
  GnRunAsService := Installing;
  if GnRunAsService then begin
    { Application is to be installed or uninstalled as service }
    SvcMgr.Application.Initialize;
    GnService := TGnService.CreateNew(SvcMgr.Application, 0);
    Result := True;

    Exit;
  end;

  loc_Terminate := False;

  { Check for a previous service installation }

  { The TGnServiceManager is a wrapper for the OpenSCManager }
  with TGnServiceManager.Create do begin
    GnRunAsService := False;

    { Users without Admin privileges can not open the Service Manager with
      full access. So as we only want to read configuration data, we set the
      OpenSCManager Flags to CONNECT and nothing "more" }

    if Connect(nil, nil, SC_MANAGER_CONNECT) then begin
      { Look for service in the service configuration manager
        Users without Admin privileges can not open the service
        configuration with full access. So as we only want to read configuration
        data, we set the OpenService Flags to QUERY_CONFIG and nothing "more" }

      if OpenServiceConnection(GnServiceName, SERVICE_QUERY_CONFIG) then begin
        { Application has been installed as service, now get the configuration
          data }

        case GetServiceStartName(loc_ServiceStartName) of
          NO_ERROR :
             begin
               if SameText(loc_ServiceStartName, 'LocalSystem') then
                 loc_ServiceStartName := 'SYSTEM';

               { Get current UserID without Domain- Part, is needed for
                 running service as LocalSystem}

               GnRunAsService := SameText(GetLocalUserName, loc_ServiceStartName);

               if not GnRunAsService then begin
                 { First comparison failed, assumedly because of the
                   missing Domain- Part of the UserId, so have a second
                   try with GetUserNameEx
                   NameFormatId 2 means %DOMAIN%\%USERID%
                 }

                 if GetLoggedOnUserNameEx(2, loc_UserName) = 0 then begin
                   GnRunAsService := SameText(loc_UserName, loc_ServiceStartName);

                   if not GnRunAsService then begin
                   { The second comparison failed, we can have the case,
                     that the ServiceStartName contains a local user
                     account, then it is in the format .\%USERID%
                     and the GetUserNameEx returns a local userid in the
                     format %COMPUTERNAME%\%USERID%.
                     Have a third try then, comparing just the
                     UserId- Part
                   }

                     GnRunAsService := (Copy(loc_ServiceStartName, 1, 2) = '.\') and
                                       (Copy(
                                             loc_ServiceStartName, 3,
                                             Length(loc_ServiceStartName) - 2
                                            ) = GetLocalUserName);
                   end;
                 end
                 else
                   GnRunAsService := False;
               end;
             end;
          ERR_NOT_ASSIGNED : // Should never occurr: Fault of Developer
                     begin
                       loc_icon := MB_ICONERROR;
                       loc_Msg  := 'Service not Assigned';
                       loc_Terminate := True;
                     end;
          ERR_READ_CONFIG :
                     begin
                       loc_icon := MB_ICONERROR;
                       loc_Msg  := 'Error on reading service configuration';
                       loc_Terminate := True;
                     end;
        end;
      end
      else begin
        if GetLastError = ERROR_SERVICE_DOES_NOT_EXIST then begin
          { Application is not installed as service yet }
        end
        else begin
          loc_Msg  := SysErrorMessage(GetLastError);
          loc_Icon := MB_ICONERROR;
          loc_Terminate := True;
        end;
      end;
    end
    else begin
      loc_Msg  := SysErrorMessage(GetLastError);
      loc_Icon := MB_ICONERROR;
      loc_Terminate := True;
    end;

    if loc_Terminate and (not IsQuiet) then begin
      { If a critical error occurred on reading configuration, then we can now
        terminate the execution of the file
        (allocated handles and memory is disposed, cleanup has finished) }

      MessageBox(0, PChar(loc_Msg), PChar(ADisplayName), loc_Icon);
      Halt;
    end;
  end;

  { Finally check, if application was started as server (e.g. via the Service
    Manager) or if it was started via commandline or explorer
  }

  // GnRunAsService := UsingParentConsole;

  Result := GnRunAsService;

  if GnRunAsService then begin
    SvcMgr.Application.Initialize;
    GnService := TGnService.CreateNew(SvcMgr.Application, 1);
  end;
end;


Wenn noch weiterer Code erforderlich ist, kann ich den gerne nachreichen... der obige Code soll quasi nur die Unterschiede zum "Original" verdeutlichen... Ja... ich habe auch einen Mutex integriert, denn die Anwendung soll ENTWEDER als Dienst ODER als Anwendung laufen...

Vielen Dank schon mal im Voraus

C.




Edit: Anstatt auf Upload auf Senden geklickt... tststs
Einloggen, um Attachments anzusehen!


Zuletzt bearbeitet von crowley am Mi 29.11.06 17:45, insgesamt 1-mal bearbeitet
matze
ontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic starofftopic star
Beiträge: 4613
Erhaltene Danke: 24

XP home, prof
Delphi 2009 Prof,
BeitragVerfasst: Mi 29.11.06 17:31 
evtl könntest du noch ein paar Informationen über diese Unit geben ?

_________________
In the beginning was the word.
And the word was content-type: text/plain.
uall@ogc
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starofftopic star
Beiträge: 1826
Erhaltene Danke: 11

Win 2000 & VMware
Delphi 3 Prof, Delphi 7 Prof
BeitragVerfasst: Mi 29.11.06 19:42 
ausblenden volle Höhe Delphi-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
function GetParentProcessID: DWord;
var
  dwHandle: DWord;
  process : TProcessEntry32;
  bContinue: Boolean;
begin
  dwHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
  Result := 0;
  ZeroMemory(@process,SizeOf(TProcessEntry32));
  Process.dwSize := SizeOf(TProcessEntry32);
  if (dwHandle <> 0) then
  begin
    bContinue := Process32First(dwHandle,Process);
    while bContinue do
    begin
      if (Process.th32ProcessID = GetCurrentProcessID) then
        Result := Process.th32ParentProcessID;
      bContinue := Process32Next(dwHandle,Process);
    end;
    CloseHandle(dwHandle);
  end;
end;

function IsServiceExe(dwProcessID: DWord): Boolean;
var
  dwHandle: DWord;
  process : TProcessEntry32;
  bContinue: Boolean;
begin
  dwHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
  Result := False;
  ZeroMemory(@process,SizeOf(TProcessEntry32));
  Process.dwSize := SizeOf(TProcessEntry32);
  if (dwHandle <> 0) then
  begin
    bContinue := Process32First(dwHandle,Process);
    while bContinue do
    begin
      if (Process.th32ProcessID = dwProcessID) then
        Result := LowerCase(ExtractFileName(Process.szExeFile)) = 'services.exe';
      bContinue := Process32Next(dwHandle,Process);
    end;
    CloseHandle(dwHandle);
  end;
end;

_________________
wer andern eine grube gräbt hat ein grubengrabgerät
- oder einfach zu viel zeit
BenBE
ontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic starofftopic star
Beiträge: 8721
Erhaltene Danke: 191

Win95, Win98SE, Win2K, WinXP
D1S, D3S, D4S, D5E, D6E, D7E, D9PE, D10E, D12P, DXEP, L0.9\FPC2.0
BeitragVerfasst: Mi 29.11.06 19:53 
Wäre es nicht sinnvoller, LocalSystem und System als User des Prozesseigentümers über deren SID abzufragen? AFAIK sind diese nämlich für vordefinierte Konten vordefiniert.

@uall: Die IsServiceExe von Dir setzt voraus, dass der Service nicht Teil eines Subservice ist, was bei meiner Prozessstruktur bei einigen Prozessen der Fall ist. Ferner ist LSASS.exe auch als Service angezeigt (Process Explorer), obwohl diese nicht Services.EXE als Parent hat.

_________________
Anyone who is capable of being elected president should on no account be allowed to do the job.
Ich code EdgeMonkey - In dubio pro Setting.
crowley Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic star
Beiträge: 406

Win XP, Win Vista, Mandriva, Ubuntu
Delphi 4-8, Delphi 2006, Delphi 2007
BeitragVerfasst: Do 30.11.06 11:33 
guten und hallo ;)

zuerst einmal vielen lieben dank für die Hilfe.

@user profile iconuall@ogc: Vielen Dank, deine Funktionen helfen schon mal in den meisten Fällen weiter. Das Problem ist, dass die verwendete CreateToolhelp32Snapshot nicht unter Windows NT läuft. In der MSDN findet sich ein entsprechender Hinweis (Win95/Win98/Win ME/Win 2k Pro/Win XP/Win Vista). Leider muss ich irgendwie sicherstellen, dass der Dienst/die Anwendung auch unter Win NT 4 lauffähig ist.

@user profile iconBenBE: Die Funktionen von user profile iconuall@ogc kann man in soweit etwas pimpen, dass du prüfen kannst, ob in der Prozesshierarchie dein Dienst von services.exe abstammt (und das ist für alle Dienste der Fall). Dein Vorschlag den Prozesseigentümer System/LocalSystem via SID abzufragen würde ja nicht wirklich weiterhelfen. Da im Falle, dass der Dienst im Systemkontext läuft, funktioniert ja alles. Das Problem taucht ja dann auf, wenn der Dienst auf einen bestimmten User "registriert" ist, dieser User aber NICHT den Dienst, sondern die Applikation starten möchte.

ausblenden volle Höhe Delphi-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
//------------------------------------------------------------------------------
function GetParentProcessID(const AProcessID: DWORD = 0): DWORD;
var
  dwID      : DWORD;
  dwHandle  : DWORD;
  process : TProcessEntry32;
  bContinue: Boolean;
begin
  Result := 0;

  dwHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  if (dwHandle <> 0) then try
    dwID := AProcessID;
    if dwID = 0 then
      dwID := GetCurrentProcessID;

    ZeroMemory(@process, SizeOf(TProcessEntry32));
    process.dwSize := SizeOf(TProcessEntry32);

    bContinue := Process32First(dwHandle, process);
    while bContinue do begin
      if (process.th32ProcessID = dwID) then
        Result := process.th32ParentProcessID;
      bContinue := Process32Next(dwHandle, process);
    end;

  finally
    CloseHandle(dwHandle);
  end;
end;

//------------------------------------------------------------------------------
function IsServiceExe(AProcessID: DWORD; AIncludeHierarchy: Boolean): Boolean;
var
  dwHandle: DWord;
  process : TProcessEntry32;
  bContinue: Boolean;
begin
  dwHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
  Result := False;
  ZeroMemory(@process, SizeOf(TProcessEntry32));
  process.dwSize := SizeOf(TProcessEntry32);
  if (dwHandle <> 0) then begin
    bContinue := Process32First(dwHandle,process);
    while bContinue do begin
      if (process.th32ProcessID = AProcessID) then
        Result := LowerCase(ExtractFileName(process.szExeFile)) = 'services.exe';
      bContinue := Process32Next(dwHandle, process);
    end;  
    CloseHandle(dwHandle);

    if (not Result) and AIncludeHierarchy then begin
      dwHandle := GetParentProcessID(AProcessID);

      if dwHandle <> 0 then
        Result := IsServiceExe(dwHandle, AIncludeHierarchy);
    end;
  end;
end;



Mir ist noch eine andere Möglichkeit eingefallen, dafür öffne ich aber einen neuen Thread ;)

Danke auf jeden Fall schon einmal, falls jemand eine Möglichkeit sieht, eine ähnliche Funktion wie user profile iconuall@ogc zu erstellen, die auch unter WinNT4 läuft (oder die vorhandene entsprechend zu erweitern)... dann BITTE ;)

C.