1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "remoting/host/setup/me2me_native_messaging_host_main.h"
7 #include "base/at_exit.h"
8 #include "base/command_line.h"
9 #include "base/files/file.h"
10 #include "base/i18n/icu_util.h"
11 #include "base/message_loop/message_loop.h"
12 #include "base/run_loop.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/threading/thread.h"
15 #include "net/url_request/url_fetcher.h"
16 #include "remoting/base/breakpad.h"
17 #include "remoting/base/url_request_context_getter.h"
18 #include "remoting/host/host_exit_codes.h"
19 #include "remoting/host/logging.h"
20 #include "remoting/host/native_messaging/pipe_messaging_channel.h"
21 #include "remoting/host/pairing_registry_delegate.h"
22 #include "remoting/host/setup/me2me_native_messaging_host.h"
23 #include "remoting/host/usage_stats_consent.h"
25 #if defined(OS_MACOSX)
26 #include "base/mac/scoped_nsautorelease_pool.h"
27 #endif // defined(OS_MACOSX)
30 #include "base/win/registry.h"
31 #include "base/win/windows_version.h"
32 #include "remoting/host/pairing_registry_delegate_win.h"
33 #endif // defined(OS_WIN)
36 #include <glib-object.h>
37 #endif // defined(OS_LINUX)
39 using remoting::protocol::PairingRegistry
;
43 const char kParentWindowSwitchName
[] = "parent-window";
50 bool IsProcessElevated() {
51 // Conceptually, all processes running on a pre-VISTA version of Windows can
52 // be considered "elevated".
53 if (base::win::GetVersion() < base::win::VERSION_VISTA
)
57 OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &process_token
);
59 base::win::ScopedHandle
scoped_process_token(process_token
);
61 // Unlike TOKEN_ELEVATION_TYPE which returns TokenElevationTypeDefault when
62 // UAC is turned off, TOKEN_ELEVATION will tell you the process is elevated.
64 TOKEN_ELEVATION elevation
;
65 GetTokenInformation(process_token
, TokenElevation
,
66 &elevation
, sizeof(elevation
), &size
);
67 return elevation
.TokenIsElevated
!= 0;
69 #endif // defined(OS_WIN)
71 int StartMe2MeNativeMessagingHost() {
72 #if defined(OS_MACOSX)
73 // Needed so we don't leak objects when threads are created.
74 base::mac::ScopedNSAutoreleasePool pool
;
75 #endif // defined(OS_MACOSX)
78 // g_type_init will be deprecated in 2.36. 2.35 is the development
79 // version for 2.36, hence do not call g_type_init starting 2.35.
80 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
81 #if !GLIB_CHECK_VERSION(2, 35, 0)
84 #endif // defined(OS_LINUX)
86 // Required to find the ICU data file, used by some file_util routines.
87 base::i18n::InitializeICU();
89 #if defined(REMOTING_ENABLE_BREAKPAD)
90 // Initialize Breakpad as early as possible. On Mac the command-line needs to
91 // be initialized first, so that the preference for crash-reporting can be
92 // looked up in the config file.
93 if (IsUsageStatsAllowed()) {
94 InitializeCrashReporting();
96 #endif // defined(REMOTING_ENABLE_BREAKPAD)
98 // Mac OS X requires that the main thread be a UI message loop in order to
99 // receive distributed notifications from the System Preferences pane. An
100 // IO thread is needed for the pairing registry and URL context getter.
101 base::Thread
io_thread("io_thread");
102 io_thread
.StartWithOptions(
103 base::Thread::Options(base::MessageLoop::TYPE_IO
, 0));
105 base::Thread
file_thread("file_thread");
106 file_thread
.StartWithOptions(
107 base::Thread::Options(base::MessageLoop::TYPE_IO
, 0));
109 base::MessageLoopForUI message_loop
;
110 base::RunLoop run_loop
;
112 scoped_refptr
<DaemonController
> daemon_controller
=
113 DaemonController::Create();
115 // Pass handle of the native view to the controller so that the UAC prompts
116 // are focused properly.
117 const base::CommandLine
* command_line
=
118 base::CommandLine::ForCurrentProcess();
119 int64 native_view_handle
= 0;
120 if (command_line
->HasSwitch(kParentWindowSwitchName
)) {
121 std::string native_view
=
122 command_line
->GetSwitchValueASCII(kParentWindowSwitchName
);
123 if (!base::StringToInt64(native_view
, &native_view_handle
)) {
124 LOG(WARNING
) << "Invalid parameter value --" << kParentWindowSwitchName
125 << "=" << native_view
;
129 base::File read_file
;
130 base::File write_file
;
131 bool needs_elevation
= false;
134 needs_elevation
= !IsProcessElevated();
136 if (command_line
->HasSwitch(kElevatingSwitchName
)) {
137 DCHECK(!needs_elevation
);
139 // The "elevate" switch is always accompanied by the "input" and "output"
140 // switches whose values name named pipes that should be used in place of
142 DCHECK(command_line
->HasSwitch(kInputSwitchName
));
143 DCHECK(command_line
->HasSwitch(kOutputSwitchName
));
145 // presubmit: allow wstring
146 std::wstring input_pipe_name
=
147 command_line
->GetSwitchValueNative(kInputSwitchName
);
148 // presubmit: allow wstring
149 std::wstring output_pipe_name
=
150 command_line
->GetSwitchValueNative(kOutputSwitchName
);
152 // A NULL SECURITY_ATTRIBUTES signifies that the handle can't be inherited.
154 base::File(CreateFile(input_pipe_name
.c_str(), GENERIC_READ
, 0, nullptr,
155 OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, nullptr));
156 if (!read_file
.IsValid()) {
157 PLOG(ERROR
) << "CreateFile failed on '" << input_pipe_name
<< "'";
158 return kInitializationFailed
;
161 write_file
= base::File(CreateFile(
162 output_pipe_name
.c_str(), GENERIC_WRITE
, 0, nullptr, OPEN_EXISTING
,
163 FILE_ATTRIBUTE_NORMAL
, nullptr));
164 if (!write_file
.IsValid()) {
165 PLOG(ERROR
) << "CreateFile failed on '" << output_pipe_name
<< "'";
166 return kInitializationFailed
;
169 // GetStdHandle() returns pseudo-handles for stdin and stdout even if
170 // the hosting executable specifies "Windows" subsystem. However the
171 // returned handles are invalid in that case unless standard input and
172 // output are redirected to a pipe or file.
173 read_file
= base::File(GetStdHandle(STD_INPUT_HANDLE
));
174 write_file
= base::File(GetStdHandle(STD_OUTPUT_HANDLE
));
176 // After the native messaging channel starts the native messaging reader
177 // will keep doing blocking read operations on the input named pipe.
178 // If any other thread tries to perform any operation on STDIN, it will also
179 // block because the input named pipe is synchronous (non-overlapped).
180 // It is pretty common for a DLL to query the device info (GetFileType) of
181 // the STD* handles at startup. So any LoadLibrary request can potentially
182 // be blocked. To prevent that from happening we close STDIN and STDOUT
183 // handles as soon as we retrieve the corresponding file handles.
184 SetStdHandle(STD_INPUT_HANDLE
, nullptr);
185 SetStdHandle(STD_OUTPUT_HANDLE
, nullptr);
187 #elif defined(OS_POSIX)
188 // The files will be automatically closed.
189 read_file
= base::File(STDIN_FILENO
);
190 write_file
= base::File(STDOUT_FILENO
);
192 #error Not implemented.
195 // OAuth client (for credential requests). IO thread is used for blocking
196 scoped_refptr
<net::URLRequestContextGetter
> url_request_context_getter(
197 new URLRequestContextGetter(io_thread
.task_runner(),
198 file_thread
.task_runner()));
199 scoped_ptr
<OAuthClient
> oauth_client(
200 new OAuthClient(url_request_context_getter
));
202 net::URLFetcher::SetIgnoreCertificateRequests(true);
204 // Create the pairing registry.
205 scoped_refptr
<PairingRegistry
> pairing_registry
;
208 base::win::RegKey root
;
209 LONG result
= root
.Open(HKEY_LOCAL_MACHINE
, kPairingRegistryKeyName
,
211 if (result
!= ERROR_SUCCESS
) {
212 SetLastError(result
);
213 PLOG(ERROR
) << "Failed to open HKLM\\" << kPairingRegistryKeyName
;
214 return kInitializationFailed
;
217 base::win::RegKey unprivileged
;
218 result
= unprivileged
.Open(root
.Handle(), kPairingRegistryClientsKeyName
,
219 needs_elevation
? KEY_READ
: KEY_READ
| KEY_WRITE
);
220 if (result
!= ERROR_SUCCESS
) {
221 SetLastError(result
);
222 PLOG(ERROR
) << "Failed to open HKLM\\" << kPairingRegistryKeyName
223 << "\\" << kPairingRegistryClientsKeyName
;
224 return kInitializationFailed
;
227 // Only try to open the privileged key if the current process is elevated.
228 base::win::RegKey privileged
;
229 if (!needs_elevation
) {
230 result
= privileged
.Open(root
.Handle(), kPairingRegistrySecretsKeyName
,
231 KEY_READ
| KEY_WRITE
);
232 if (result
!= ERROR_SUCCESS
) {
233 SetLastError(result
);
234 PLOG(ERROR
) << "Failed to open HKLM\\" << kPairingRegistryKeyName
<< "\\"
235 << kPairingRegistrySecretsKeyName
;
236 return kInitializationFailed
;
240 // Initialize the pairing registry delegate and set the root keys.
241 scoped_ptr
<PairingRegistryDelegateWin
> delegate(
242 new PairingRegistryDelegateWin());
243 if (!delegate
->SetRootKeys(privileged
.Take(), unprivileged
.Take()))
244 return kInitializationFailed
;
247 new PairingRegistry(io_thread
.task_runner(), delegate
.Pass());
248 #else // defined(OS_WIN)
250 CreatePairingRegistry(io_thread
.task_runner());
251 #endif // !defined(OS_WIN)
253 // Set up the native messaging channel.
254 scoped_ptr
<extensions::NativeMessagingChannel
> channel(
255 new PipeMessagingChannel(read_file
.Pass(), write_file
.Pass()));
257 // Create the native messaging host.
258 scoped_ptr
<Me2MeNativeMessagingHost
> host(
259 new Me2MeNativeMessagingHost(
261 static_cast<intptr_t>(native_view_handle
),
265 oauth_client
.Pass()));
266 host
->Start(run_loop
.QuitClosure());
268 // Run the loop until channel is alive.
270 return kSuccessExitCode
;
273 int Me2MeNativeMessagingHostMain(int argc
, char** argv
) {
274 // This object instance is required by Chrome code (such as MessageLoop).
275 base::AtExitManager exit_manager
;
277 base::CommandLine::Init(argc
, argv
);
278 remoting::InitHostLogging();
280 return StartMe2MeNativeMessagingHost();
283 } // namespace remoting