1 // Copyright (c) 2012 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 "chrome/service/service_utility_process_host.h"
10 #include "base/command_line.h"
11 #include "base/files/file.h"
12 #include "base/files/file_path.h"
13 #include "base/files/file_util.h"
14 #include "base/files/scoped_temp_dir.h"
15 #include "base/logging.h"
16 #include "base/message_loop/message_loop_proxy.h"
17 #include "base/metrics/histogram.h"
18 #include "base/process/kill.h"
19 #include "base/process/launch.h"
20 #include "base/process/process_handle.h"
21 #include "base/task_runner_util.h"
22 #include "chrome/common/chrome_switches.h"
23 #include "chrome/common/chrome_utility_printing_messages.h"
24 #include "content/public/common/child_process_host.h"
25 #include "content/public/common/result_codes.h"
26 #include "content/public/common/sandbox_init.h"
27 #include "content/public/common/sandboxed_process_launcher_delegate.h"
28 #include "ipc/ipc_switches.h"
29 #include "printing/emf_win.h"
30 #include "sandbox/win/src/sandbox_policy_base.h"
31 #include "ui/base/ui_base_switches.h"
35 using content::ChildProcessHost
;
37 enum ServiceUtilityProcessHostEvent
{
38 SERVICE_UTILITY_STARTED
,
39 SERVICE_UTILITY_DISCONNECTED
,
40 SERVICE_UTILITY_METAFILE_REQUEST
,
41 SERVICE_UTILITY_METAFILE_SUCCEEDED
,
42 SERVICE_UTILITY_METAFILE_FAILED
,
43 SERVICE_UTILITY_CAPS_REQUEST
,
44 SERVICE_UTILITY_CAPS_SUCCEEDED
,
45 SERVICE_UTILITY_CAPS_FAILED
,
46 SERVICE_UTILITY_SEMANTIC_CAPS_REQUEST
,
47 SERVICE_UTILITY_SEMANTIC_CAPS_SUCCEEDED
,
48 SERVICE_UTILITY_SEMANTIC_CAPS_FAILED
,
49 SERVICE_UTILITY_FAILED_TO_START
,
50 SERVICE_UTILITY_EVENT_MAX
,
53 void ReportUmaEvent(ServiceUtilityProcessHostEvent id
) {
54 UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceUtilityProcessHostEvent",
56 SERVICE_UTILITY_EVENT_MAX
);
59 // NOTE: changes to this class need to be reviewed by the security team.
60 class ServiceSandboxedProcessLauncherDelegate
61 : public content::SandboxedProcessLauncherDelegate
{
63 ServiceSandboxedProcessLauncherDelegate() {}
65 virtual void PreSpawnTarget(sandbox::TargetPolicy
* policy
,
66 bool* success
) override
{
67 // Service process may run as windows service and it fails to create a
69 policy
->SetAlternateDesktop(false);
73 DISALLOW_COPY_AND_ASSIGN(ServiceSandboxedProcessLauncherDelegate
);
78 class ServiceUtilityProcessHost::PdfToEmfState
{
80 explicit PdfToEmfState(ServiceUtilityProcessHost
* host
)
81 : host_(host
), page_count_(0), current_page_(0), pages_in_progress_(0) {}
82 ~PdfToEmfState() { Stop(); }
84 bool Start(base::File pdf_file
,
85 const printing::PdfRenderSettings
& conversion_settings
) {
86 if (!temp_dir_
.CreateUniqueTempDir())
88 return host_
->Send(new ChromeUtilityMsg_RenderPDFPagesToMetafiles(
89 IPC::TakeFileHandleForProcess(pdf_file
.Pass(), host_
->handle()),
90 conversion_settings
));
94 const int kMaxNumberOfTempFilesPerDocument
= 3;
95 while (pages_in_progress_
< kMaxNumberOfTempFilesPerDocument
&&
96 current_page_
< page_count_
) {
98 emf_files_
.push(CreateTempFile());
99 host_
->Send(new ChromeUtilityMsg_RenderPDFPagesToMetafiles_GetPage(
101 IPC::GetFileHandleForProcess(
102 emf_files_
.back().GetPlatformFile(), host_
->handle(), false)));
106 // Returns true if all pages processed and client should not expect more
108 bool OnPageProcessed() {
109 --pages_in_progress_
;
111 if (pages_in_progress_
|| current_page_
< page_count_
)
117 base::File
TakeNextFile() {
118 DCHECK(!emf_files_
.empty());
120 if (!emf_files_
.empty())
121 file
= emf_files_
.front().Pass();
126 void set_page_count(int page_count
) { page_count_
= page_count
; }
127 bool has_page_count() { return page_count_
> 0; }
131 host_
->Send(new ChromeUtilityMsg_RenderPDFPagesToMetafiles_Stop());
134 base::File
CreateTempFile() {
136 if (!base::CreateTemporaryFileInDir(temp_dir_
.path(), &path
))
138 return base::File(path
,
139 base::File::FLAG_CREATE_ALWAYS
|
140 base::File::FLAG_WRITE
|
141 base::File::FLAG_READ
|
142 base::File::FLAG_DELETE_ON_CLOSE
|
143 base::File::FLAG_TEMPORARY
);
146 base::ScopedTempDir temp_dir_
;
147 ServiceUtilityProcessHost
* host_
;
148 std::queue
<base::File
> emf_files_
;
151 int pages_in_progress_
;
154 ServiceUtilityProcessHost::ServiceUtilityProcessHost(
156 base::MessageLoopProxy
* client_message_loop_proxy
)
158 client_message_loop_proxy_(client_message_loop_proxy
),
159 waiting_for_reply_(false),
160 weak_ptr_factory_(this) {
161 child_process_host_
.reset(ChildProcessHost::Create(this));
164 ServiceUtilityProcessHost::~ServiceUtilityProcessHost() {
165 // We need to kill the child process when the host dies.
166 base::KillProcess(process_
.Handle(), content::RESULT_CODE_NORMAL_EXIT
, false);
169 bool ServiceUtilityProcessHost::StartRenderPDFPagesToMetafile(
170 const base::FilePath
& pdf_path
,
171 const printing::PdfRenderSettings
& render_settings
) {
172 ReportUmaEvent(SERVICE_UTILITY_METAFILE_REQUEST
);
173 start_time_
= base::Time::Now();
174 base::File
pdf_file(pdf_path
, base::File::FLAG_OPEN
| base::File::FLAG_READ
);
175 if (!pdf_file
.IsValid() || !StartProcess(false))
178 DCHECK(!waiting_for_reply_
);
179 waiting_for_reply_
= true;
181 pdf_to_emf_state_
.reset(new PdfToEmfState(this));
182 return pdf_to_emf_state_
->Start(pdf_file
.Pass(), render_settings
);
185 bool ServiceUtilityProcessHost::StartGetPrinterCapsAndDefaults(
186 const std::string
& printer_name
) {
187 ReportUmaEvent(SERVICE_UTILITY_CAPS_REQUEST
);
188 start_time_
= base::Time::Now();
189 if (!StartProcess(true))
191 DCHECK(!waiting_for_reply_
);
192 waiting_for_reply_
= true;
193 return Send(new ChromeUtilityMsg_GetPrinterCapsAndDefaults(printer_name
));
196 bool ServiceUtilityProcessHost::StartGetPrinterSemanticCapsAndDefaults(
197 const std::string
& printer_name
) {
198 ReportUmaEvent(SERVICE_UTILITY_SEMANTIC_CAPS_REQUEST
);
199 start_time_
= base::Time::Now();
200 if (!StartProcess(true))
202 DCHECK(!waiting_for_reply_
);
203 waiting_for_reply_
= true;
205 new ChromeUtilityMsg_GetPrinterSemanticCapsAndDefaults(printer_name
));
208 bool ServiceUtilityProcessHost::StartProcess(bool no_sandbox
) {
209 std::string channel_id
= child_process_host_
->CreateChannel();
210 if (channel_id
.empty())
213 base::FilePath exe_path
= GetUtilityProcessCmd();
214 if (exe_path
.empty()) {
215 NOTREACHED() << "Unable to get utility process binary name.";
219 base::CommandLine
cmd_line(exe_path
);
220 cmd_line
.AppendSwitchASCII(switches::kProcessType
, switches::kUtilityProcess
);
221 cmd_line
.AppendSwitchASCII(switches::kProcessChannelID
, channel_id
);
222 cmd_line
.AppendSwitch(switches::kLang
);
224 if (Launch(&cmd_line
, no_sandbox
)) {
225 ReportUmaEvent(SERVICE_UTILITY_STARTED
);
228 ReportUmaEvent(SERVICE_UTILITY_FAILED_TO_START
);
232 bool ServiceUtilityProcessHost::Launch(base::CommandLine
* cmd_line
,
235 cmd_line
->AppendSwitch(switches::kNoSandbox
);
236 process_
= base::LaunchProcess(*cmd_line
, base::LaunchOptions());
238 ServiceSandboxedProcessLauncherDelegate delegate
;
239 process_
= content::StartSandboxedProcess(&delegate
, cmd_line
);
241 return process_
.IsValid();
244 bool ServiceUtilityProcessHost::Send(IPC::Message
* msg
) {
245 if (child_process_host_
)
246 return child_process_host_
->Send(msg
);
251 base::FilePath
ServiceUtilityProcessHost::GetUtilityProcessCmd() {
252 #if defined(OS_LINUX)
253 int flags
= ChildProcessHost::CHILD_ALLOW_SELF
;
255 int flags
= ChildProcessHost::CHILD_NORMAL
;
257 return ChildProcessHost::GetChildPath(flags
);
260 void ServiceUtilityProcessHost::OnChildDisconnected() {
261 if (waiting_for_reply_
) {
262 // If we are yet to receive a reply then notify the client that the
264 client_message_loop_proxy_
->PostTask(
265 FROM_HERE
, base::Bind(&Client::OnChildDied
, client_
.get()));
266 ReportUmaEvent(SERVICE_UTILITY_DISCONNECTED
);
267 UMA_HISTOGRAM_TIMES("CloudPrint.ServiceUtilityDisconnectTime",
268 base::Time::Now() - start_time_
);
273 bool ServiceUtilityProcessHost::OnMessageReceived(const IPC::Message
& message
) {
275 IPC_BEGIN_MESSAGE_MAP(ServiceUtilityProcessHost
, message
)
277 ChromeUtilityHostMsg_RenderPDFPagesToMetafiles_PageCount
,
278 OnRenderPDFPagesToMetafilesPageCount
)
279 IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_RenderPDFPagesToMetafiles_PageDone
,
280 OnRenderPDFPagesToMetafilesPageDone
)
282 ChromeUtilityHostMsg_GetPrinterCapsAndDefaults_Succeeded
,
283 OnGetPrinterCapsAndDefaultsSucceeded
)
284 IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_GetPrinterCapsAndDefaults_Failed
,
285 OnGetPrinterCapsAndDefaultsFailed
)
287 ChromeUtilityHostMsg_GetPrinterSemanticCapsAndDefaults_Succeeded
,
288 OnGetPrinterSemanticCapsAndDefaultsSucceeded
)
290 ChromeUtilityHostMsg_GetPrinterSemanticCapsAndDefaults_Failed
,
291 OnGetPrinterSemanticCapsAndDefaultsFailed
)
292 IPC_MESSAGE_UNHANDLED(handled
= false)
293 IPC_END_MESSAGE_MAP()
297 const base::Process
& ServiceUtilityProcessHost::GetProcess() const {
301 void ServiceUtilityProcessHost::OnMetafileSpooled(bool success
) {
302 if (!success
|| pdf_to_emf_state_
->OnPageProcessed())
303 OnPDFToEmfFinished(success
);
306 void ServiceUtilityProcessHost::OnRenderPDFPagesToMetafilesPageCount(
308 DCHECK(waiting_for_reply_
);
309 if (!pdf_to_emf_state_
|| page_count
<= 0 ||
310 pdf_to_emf_state_
->has_page_count()) {
311 return OnPDFToEmfFinished(false);
313 pdf_to_emf_state_
->set_page_count(page_count
);
314 pdf_to_emf_state_
->GetMorePages();
317 void ServiceUtilityProcessHost::OnRenderPDFPagesToMetafilesPageDone(
319 float scale_factor
) {
320 DCHECK(waiting_for_reply_
);
321 if (!pdf_to_emf_state_
|| !success
)
322 return OnPDFToEmfFinished(false);
323 base::File emf_file
= pdf_to_emf_state_
->TakeNextFile();
324 base::PostTaskAndReplyWithResult(
325 client_message_loop_proxy_
.get(), FROM_HERE
,
326 base::Bind(&Client::MetafileAvailable
, client_
.get(), scale_factor
,
327 base::Passed(&emf_file
)),
328 base::Bind(&ServiceUtilityProcessHost::OnMetafileSpooled
,
329 weak_ptr_factory_
.GetWeakPtr()));
332 void ServiceUtilityProcessHost::OnPDFToEmfFinished(bool success
) {
333 if (!waiting_for_reply_
)
335 waiting_for_reply_
= false;
337 ReportUmaEvent(SERVICE_UTILITY_METAFILE_SUCCEEDED
);
338 UMA_HISTOGRAM_TIMES("CloudPrint.ServiceUtilityMetafileTime",
339 base::Time::Now() - start_time_
);
341 ReportUmaEvent(SERVICE_UTILITY_METAFILE_FAILED
);
342 UMA_HISTOGRAM_TIMES("CloudPrint.ServiceUtilityMetafileFailTime",
343 base::Time::Now() - start_time_
);
345 client_message_loop_proxy_
->PostTask(
348 &Client::OnRenderPDFPagesToMetafileDone
, client_
.get(), success
));
349 pdf_to_emf_state_
.reset();
352 void ServiceUtilityProcessHost::OnGetPrinterCapsAndDefaultsSucceeded(
353 const std::string
& printer_name
,
354 const printing::PrinterCapsAndDefaults
& caps_and_defaults
) {
355 DCHECK(waiting_for_reply_
);
356 ReportUmaEvent(SERVICE_UTILITY_CAPS_SUCCEEDED
);
357 UMA_HISTOGRAM_TIMES("CloudPrint.ServiceUtilityCapsTime",
358 base::Time::Now() - start_time_
);
359 waiting_for_reply_
= false;
360 client_message_loop_proxy_
->PostTask(
362 base::Bind(&Client::OnGetPrinterCapsAndDefaults
, client_
.get(), true,
363 printer_name
, caps_and_defaults
));
366 void ServiceUtilityProcessHost::OnGetPrinterSemanticCapsAndDefaultsSucceeded(
367 const std::string
& printer_name
,
368 const printing::PrinterSemanticCapsAndDefaults
& caps_and_defaults
) {
369 DCHECK(waiting_for_reply_
);
370 ReportUmaEvent(SERVICE_UTILITY_SEMANTIC_CAPS_SUCCEEDED
);
371 UMA_HISTOGRAM_TIMES("CloudPrint.ServiceUtilitySemanticCapsTime",
372 base::Time::Now() - start_time_
);
373 waiting_for_reply_
= false;
374 client_message_loop_proxy_
->PostTask(
376 base::Bind(&Client::OnGetPrinterSemanticCapsAndDefaults
, client_
.get(),
377 true, printer_name
, caps_and_defaults
));
380 void ServiceUtilityProcessHost::OnGetPrinterCapsAndDefaultsFailed(
381 const std::string
& printer_name
) {
382 DCHECK(waiting_for_reply_
);
383 ReportUmaEvent(SERVICE_UTILITY_CAPS_FAILED
);
384 UMA_HISTOGRAM_TIMES("CloudPrint.ServiceUtilityCapsFailTime",
385 base::Time::Now() - start_time_
);
386 waiting_for_reply_
= false;
387 client_message_loop_proxy_
->PostTask(
389 base::Bind(&Client::OnGetPrinterCapsAndDefaults
, client_
.get(), false,
390 printer_name
, printing::PrinterCapsAndDefaults()));
393 void ServiceUtilityProcessHost::OnGetPrinterSemanticCapsAndDefaultsFailed(
394 const std::string
& printer_name
) {
395 DCHECK(waiting_for_reply_
);
396 ReportUmaEvent(SERVICE_UTILITY_SEMANTIC_CAPS_FAILED
);
397 UMA_HISTOGRAM_TIMES("CloudPrint.ServiceUtilitySemanticCapsFailTime",
398 base::Time::Now() - start_time_
);
399 waiting_for_reply_
= false;
400 client_message_loop_proxy_
->PostTask(
402 base::Bind(&Client::OnGetPrinterSemanticCapsAndDefaults
,
403 client_
.get(), false, printer_name
,
404 printing::PrinterSemanticCapsAndDefaults()));
407 bool ServiceUtilityProcessHost::Client::MetafileAvailable(float scale_factor
,
409 file
.Seek(base::File::FROM_BEGIN
, 0);
410 int64 size
= file
.GetLength();
412 OnRenderPDFPagesToMetafileDone(false);
415 std::vector
<char> data(size
);
416 if (file
.ReadAtCurrentPos(data
.data(), data
.size()) != size
) {
417 OnRenderPDFPagesToMetafileDone(false);
421 if (!emf
.InitFromData(data
.data(), data
.size())) {
422 OnRenderPDFPagesToMetafileDone(false);
425 OnRenderPDFPagesToMetafilePageDone(scale_factor
, emf
);