forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathscoped_service_handle.h
90 lines (70 loc) · 2.52 KB
/
scoped_service_handle.h
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
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_CHROME_CLEANER_OS_SCOPED_SERVICE_HANDLE_H_
#define CHROME_CHROME_CLEANER_OS_SCOPED_SERVICE_HANDLE_H_
#include <windows.h>
#include "base/logging.h"
#include "base/win/scoped_handle.h"
namespace chrome_cleaner {
class ScHandleTraits {
public:
typedef SC_HANDLE Handle;
// Closes the handle.
static bool CloseHandle(SC_HANDLE handle) {
return ::CloseServiceHandle(handle) != FALSE;
}
// Returns true if the handle value is valid.
static bool IsHandleValid(SC_HANDLE handle) { return handle != nullptr; }
// Returns null handle value.
static SC_HANDLE NullHandle() { return nullptr; }
private:
DISALLOW_IMPLICIT_CONSTRUCTORS(ScHandleTraits);
};
typedef base::win::GenericScopedHandle<ScHandleTraits,
base::win::DummyVerifierTraits>
ScopedScHandle;
class ScopedServiceHandle {
public:
ScopedServiceHandle();
~ScopedServiceHandle();
bool IsValid() const {
return service_manager_.IsValid() && service_.IsValid();
}
SC_HANDLE get() const { return service_.Get(); }
bool OpenService(const wchar_t* service_name,
DWORD service_manager_desired_access,
DWORD service_desired_access) {
DCHECK(service_name);
DCHECK(!service_manager_.IsValid());
DCHECK(!service_.IsValid());
// Get a handle to the service manager.
service_manager_.Set(
::OpenSCManager(nullptr, nullptr, service_manager_desired_access));
if (!service_manager_.IsValid()) {
PLOG(ERROR) << "Cannot open service manager.";
return false;
}
// Get a handle to the service.
service_.Set(::OpenService(service_manager_.Get(), service_name,
service_desired_access));
if (!service_.IsValid()) {
// The service doesn't exists, the returned service handle is null.
DWORD last_error = GetLastError();
if (last_error == ERROR_SERVICE_DOES_NOT_EXIST) {
LOG(INFO) << "Service '" << service_name << "' doesn't exists.";
return true;
}
// Unable to open the service.
PLOG(ERROR) << "Cannot open service '" << service_name << "'.";
return false;
}
// Return the service handle.
return true;
}
protected:
ScopedScHandle service_manager_;
ScopedScHandle service_;
};
} // namespace chrome_cleaner
#endif // CHROME_CHROME_CLEANER_OS_SCOPED_SERVICE_HANDLE_H_