Introduce the PlatformNotificationContext class.
[chromium-blink-merge.git] / chrome / service / service_utility_process_host.cc
blob7bb80e22edd48f5f6392e04a49f3c6eec2c38f77
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"
7 #include <queue>
9 #include "base/bind.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"
33 namespace {
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",
55 id,
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 {
62 public:
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
68 // window station.
69 policy->SetAlternateDesktop(false);
72 private:
73 DISALLOW_COPY_AND_ASSIGN(ServiceSandboxedProcessLauncherDelegate);
76 } // namespace
78 class ServiceUtilityProcessHost::PdfToEmfState {
79 public:
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())
87 return false;
88 return host_->Send(new ChromeUtilityMsg_RenderPDFPagesToMetafiles(
89 IPC::TakeFileHandleForProcess(pdf_file.Pass(), host_->handle()),
90 conversion_settings));
93 void GetMorePages() {
94 const int kMaxNumberOfTempFilesPerDocument = 3;
95 while (pages_in_progress_ < kMaxNumberOfTempFilesPerDocument &&
96 current_page_ < page_count_) {
97 ++pages_in_progress_;
98 emf_files_.push(CreateTempFile());
99 host_->Send(new ChromeUtilityMsg_RenderPDFPagesToMetafiles_GetPage(
100 current_page_++,
101 IPC::GetFileHandleForProcess(
102 emf_files_.back().GetPlatformFile(), host_->handle(), false)));
106 // Returns true if all pages processed and client should not expect more
107 // results.
108 bool OnPageProcessed() {
109 --pages_in_progress_;
110 GetMorePages();
111 if (pages_in_progress_ || current_page_ < page_count_)
112 return false;
113 Stop();
114 return true;
117 base::File TakeNextFile() {
118 DCHECK(!emf_files_.empty());
119 base::File file;
120 if (!emf_files_.empty())
121 file = emf_files_.front().Pass();
122 emf_files_.pop();
123 return file.Pass();
126 void set_page_count(int page_count) { page_count_ = page_count; }
127 bool has_page_count() { return page_count_ > 0; }
129 private:
130 void Stop() {
131 host_->Send(new ChromeUtilityMsg_RenderPDFPagesToMetafiles_Stop());
134 base::File CreateTempFile() {
135 base::FilePath path;
136 if (!base::CreateTemporaryFileInDir(temp_dir_.path(), &path))
137 return base::File();
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_;
149 int page_count_;
150 int current_page_;
151 int pages_in_progress_;
154 ServiceUtilityProcessHost::ServiceUtilityProcessHost(
155 Client* client,
156 base::MessageLoopProxy* client_message_loop_proxy)
157 : client_(client),
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))
176 return 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))
190 return false;
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))
201 return false;
202 DCHECK(!waiting_for_reply_);
203 waiting_for_reply_ = true;
204 return Send(
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())
211 return false;
213 base::FilePath exe_path = GetUtilityProcessCmd();
214 if (exe_path.empty()) {
215 NOTREACHED() << "Unable to get utility process binary name.";
216 return false;
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);
226 return true;
228 ReportUmaEvent(SERVICE_UTILITY_FAILED_TO_START);
229 return false;
232 bool ServiceUtilityProcessHost::Launch(base::CommandLine* cmd_line,
233 bool no_sandbox) {
234 if (no_sandbox) {
235 cmd_line->AppendSwitch(switches::kNoSandbox);
236 process_ = base::LaunchProcess(*cmd_line, base::LaunchOptions());
237 } else {
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);
247 delete msg;
248 return false;
251 base::FilePath ServiceUtilityProcessHost::GetUtilityProcessCmd() {
252 #if defined(OS_LINUX)
253 int flags = ChildProcessHost::CHILD_ALLOW_SELF;
254 #else
255 int flags = ChildProcessHost::CHILD_NORMAL;
256 #endif
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
263 // child died.
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_);
270 delete this;
273 bool ServiceUtilityProcessHost::OnMessageReceived(const IPC::Message& message) {
274 bool handled = true;
275 IPC_BEGIN_MESSAGE_MAP(ServiceUtilityProcessHost, message)
276 IPC_MESSAGE_HANDLER(
277 ChromeUtilityHostMsg_RenderPDFPagesToMetafiles_PageCount,
278 OnRenderPDFPagesToMetafilesPageCount)
279 IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_RenderPDFPagesToMetafiles_PageDone,
280 OnRenderPDFPagesToMetafilesPageDone)
281 IPC_MESSAGE_HANDLER(
282 ChromeUtilityHostMsg_GetPrinterCapsAndDefaults_Succeeded,
283 OnGetPrinterCapsAndDefaultsSucceeded)
284 IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_GetPrinterCapsAndDefaults_Failed,
285 OnGetPrinterCapsAndDefaultsFailed)
286 IPC_MESSAGE_HANDLER(
287 ChromeUtilityHostMsg_GetPrinterSemanticCapsAndDefaults_Succeeded,
288 OnGetPrinterSemanticCapsAndDefaultsSucceeded)
289 IPC_MESSAGE_HANDLER(
290 ChromeUtilityHostMsg_GetPrinterSemanticCapsAndDefaults_Failed,
291 OnGetPrinterSemanticCapsAndDefaultsFailed)
292 IPC_MESSAGE_UNHANDLED(handled = false)
293 IPC_END_MESSAGE_MAP()
294 return handled;
297 const base::Process& ServiceUtilityProcessHost::GetProcess() const {
298 return process_;
301 void ServiceUtilityProcessHost::OnMetafileSpooled(bool success) {
302 if (!success || pdf_to_emf_state_->OnPageProcessed())
303 OnPDFToEmfFinished(success);
306 void ServiceUtilityProcessHost::OnRenderPDFPagesToMetafilesPageCount(
307 int page_count) {
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(
318 bool success,
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_)
334 return;
335 waiting_for_reply_ = false;
336 if (success) {
337 ReportUmaEvent(SERVICE_UTILITY_METAFILE_SUCCEEDED);
338 UMA_HISTOGRAM_TIMES("CloudPrint.ServiceUtilityMetafileTime",
339 base::Time::Now() - start_time_);
340 } else {
341 ReportUmaEvent(SERVICE_UTILITY_METAFILE_FAILED);
342 UMA_HISTOGRAM_TIMES("CloudPrint.ServiceUtilityMetafileFailTime",
343 base::Time::Now() - start_time_);
345 client_message_loop_proxy_->PostTask(
346 FROM_HERE,
347 base::Bind(
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(
361 FROM_HERE,
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(
375 FROM_HERE,
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(
388 FROM_HERE,
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(
401 FROM_HERE,
402 base::Bind(&Client::OnGetPrinterSemanticCapsAndDefaults,
403 client_.get(), false, printer_name,
404 printing::PrinterSemanticCapsAndDefaults()));
407 bool ServiceUtilityProcessHost::Client::MetafileAvailable(float scale_factor,
408 base::File file) {
409 file.Seek(base::File::FROM_BEGIN, 0);
410 int64 size = file.GetLength();
411 if (size <= 0) {
412 OnRenderPDFPagesToMetafileDone(false);
413 return false;
415 std::vector<char> data(size);
416 if (file.ReadAtCurrentPos(data.data(), data.size()) != size) {
417 OnRenderPDFPagesToMetafileDone(false);
418 return false;
420 printing::Emf emf;
421 if (!emf.InitFromData(data.data(), data.size())) {
422 OnRenderPDFPagesToMetafileDone(false);
423 return false;
425 OnRenderPDFPagesToMetafilePageDone(scale_factor, emf);
426 return true;