Adding myself as an owner to chrome/android.
[chromium-blink-merge.git] / chrome / utility / chrome_content_utility_client.cc
blobd26063175d59132f4c7ef592428ade3f3cf1f2bc
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/utility/chrome_content_utility_client.h"
7 #include "base/base64.h"
8 #include "base/bind.h"
9 #include "base/command_line.h"
10 #include "base/file_util.h"
11 #include "base/json/json_reader.h"
12 #include "base/memory/ref_counted.h"
13 #include "base/message_loop_proxy.h"
14 #include "base/threading/thread.h"
15 #include "chrome/browser/importer/importer.h"
16 #include "chrome/browser/importer/profile_import_process_messages.h"
17 #include "chrome/common/child_process_logging.h"
18 #include "chrome/common/chrome_paths.h"
19 #include "chrome/common/chrome_utility_messages.h"
20 #include "chrome/common/extensions/api/extension_action/browser_action_handler.h"
21 #include "chrome/common/extensions/api/extension_action/page_action_handler.h"
22 #include "chrome/common/extensions/api/i18n/default_locale_handler.h"
23 #include "chrome/common/extensions/api/icons/icons_handler.h"
24 #include "chrome/common/extensions/api/plugins/plugins_handler.h"
25 #include "chrome/common/extensions/api/themes/theme_handler.h"
26 #include "chrome/common/extensions/background_info.h"
27 #include "chrome/common/extensions/extension.h"
28 #include "chrome/common/extensions/extension_l10n_util.h"
29 #include "chrome/common/extensions/incognito_handler.h"
30 #include "chrome/common/extensions/manifest.h"
31 #include "chrome/common/extensions/unpacker.h"
32 #include "chrome/common/extensions/update_manifest.h"
33 #include "chrome/common/safe_browsing/zip_analyzer.h"
34 #include "chrome/common/web_resource/web_resource_unpacker.h"
35 #include "chrome/common/zip.h"
36 #include "chrome/utility/profile_import_handler.h"
37 #include "content/public/utility/utility_thread.h"
38 #include "printing/backend/print_backend.h"
39 #include "printing/page_range.h"
40 #include "third_party/skia/include/core/SkBitmap.h"
41 #include "ui/base/ui_base_switches.h"
42 #include "ui/gfx/codec/jpeg_codec.h"
43 #include "ui/gfx/rect.h"
44 #include "webkit/glue/image_decoder.h"
46 #if defined(OS_WIN)
47 #include "base/path_service.h"
48 #include "base/win/iat_patch_function.h"
49 #include "base/win/scoped_handle.h"
50 #include "content/public/common/content_switches.h"
51 #include "printing/emf_win.h"
52 #include "ui/gfx/gdi_util.h"
53 #endif // defined(OS_WIN)
55 namespace {
57 // Explicitly register all ManifestHandlers needed in the utility process.
58 void RegisterExtensionManifestHandlers() {
59 (new extensions::BackgroundManifestHandler)->Register();
60 (new extensions::BrowserActionHandler)->Register();
61 (new extensions::DefaultLocaleHandler)->Register();
62 (new extensions::IconsHandler)->Register();
63 (new extensions::PageActionHandler)->Register();
64 (new extensions::ThemeHandler)->Register();
65 (new extensions::PluginsHandler)->Register();
66 (new extensions::IncognitoHandler)->Register();
69 } // namespace
71 namespace chrome {
73 ChromeContentUtilityClient::ChromeContentUtilityClient() {
74 #if !defined(OS_ANDROID)
75 import_handler_.reset(new ProfileImportHandler());
76 #endif
79 ChromeContentUtilityClient::~ChromeContentUtilityClient() {
82 void ChromeContentUtilityClient::UtilityThreadStarted() {
83 #if defined(OS_WIN)
84 // Load the pdf plugin before the sandbox is turned on. This is for Windows
85 // only because we need this DLL only on Windows.
86 base::FilePath pdf;
87 if (PathService::Get(chrome::FILE_PDF_PLUGIN, &pdf) &&
88 file_util::PathExists(pdf)) {
89 bool rv = !!LoadLibrary(pdf.value().c_str());
90 DCHECK(rv) << "Couldn't load PDF plugin";
92 #endif
94 CommandLine* command_line = CommandLine::ForCurrentProcess();
95 std::string lang = command_line->GetSwitchValueASCII(switches::kLang);
96 if (!lang.empty())
97 extension_l10n_util::SetProcessLocale(lang);
100 bool ChromeContentUtilityClient::OnMessageReceived(
101 const IPC::Message& message) {
102 bool handled = true;
103 IPC_BEGIN_MESSAGE_MAP(ChromeContentUtilityClient, message)
104 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_UnpackExtension, OnUnpackExtension)
105 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_UnpackWebResource,
106 OnUnpackWebResource)
107 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseUpdateManifest,
108 OnParseUpdateManifest)
109 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_DecodeImage, OnDecodeImage)
110 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_DecodeImageBase64, OnDecodeImageBase64)
111 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_RenderPDFPagesToMetafile,
112 OnRenderPDFPagesToMetafile)
113 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_RobustJPEGDecodeImage,
114 OnRobustJPEGDecodeImage)
115 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseJSON, OnParseJSON)
116 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_GetPrinterCapsAndDefaults,
117 OnGetPrinterCapsAndDefaults)
118 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_StartupPing, OnStartupPing)
119 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_AnalyzeZipFileForDownloadProtection,
120 OnAnalyzeZipFileForDownloadProtection)
122 #if defined(OS_CHROMEOS)
123 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_CreateZipFile, OnCreateZipFile)
124 #endif // defined(OS_CHROMEOS)
126 IPC_MESSAGE_UNHANDLED(handled = false)
127 IPC_END_MESSAGE_MAP()
129 #if !defined(OS_ANDROID)
130 if (!handled)
131 handled = import_handler_->OnMessageReceived(message);
132 #endif
134 return handled;
137 bool ChromeContentUtilityClient::Send(IPC::Message* message) {
138 return content::UtilityThread::Get()->Send(message);
141 void ChromeContentUtilityClient::OnUnpackExtension(
142 const base::FilePath& extension_path,
143 const std::string& extension_id,
144 int location,
145 int creation_flags) {
146 CHECK(location > extensions::Manifest::INVALID_LOCATION);
147 CHECK(location < extensions::Manifest::NUM_LOCATIONS);
148 RegisterExtensionManifestHandlers();
149 extensions::Unpacker unpacker(
150 extension_path,
151 extension_id,
152 static_cast<extensions::Manifest::Location>(location),
153 creation_flags);
154 if (unpacker.Run() && unpacker.DumpImagesToFile() &&
155 unpacker.DumpMessageCatalogsToFile()) {
156 Send(new ChromeUtilityHostMsg_UnpackExtension_Succeeded(
157 *unpacker.parsed_manifest()));
158 } else {
159 Send(new ChromeUtilityHostMsg_UnpackExtension_Failed(
160 unpacker.error_message()));
163 content::UtilityThread::Get()->ReleaseProcessIfNeeded();
166 void ChromeContentUtilityClient::OnUnpackWebResource(
167 const std::string& resource_data) {
168 // Parse json data.
169 // TODO(mrc): Add the possibility of a template that controls parsing, and
170 // the ability to download and verify images.
171 WebResourceUnpacker unpacker(resource_data);
172 if (unpacker.Run()) {
173 Send(new ChromeUtilityHostMsg_UnpackWebResource_Succeeded(
174 *unpacker.parsed_json()));
175 } else {
176 Send(new ChromeUtilityHostMsg_UnpackWebResource_Failed(
177 unpacker.error_message()));
180 content::UtilityThread::Get()->ReleaseProcessIfNeeded();
183 void ChromeContentUtilityClient::OnParseUpdateManifest(const std::string& xml) {
184 UpdateManifest manifest;
185 if (!manifest.Parse(xml)) {
186 Send(new ChromeUtilityHostMsg_ParseUpdateManifest_Failed(
187 manifest.errors()));
188 } else {
189 Send(new ChromeUtilityHostMsg_ParseUpdateManifest_Succeeded(
190 manifest.results()));
192 content::UtilityThread::Get()->ReleaseProcessIfNeeded();
195 void ChromeContentUtilityClient::OnDecodeImage(
196 const std::vector<unsigned char>& encoded_data) {
197 webkit_glue::ImageDecoder decoder;
198 const SkBitmap& decoded_image = decoder.Decode(&encoded_data[0],
199 encoded_data.size());
200 if (decoded_image.empty()) {
201 Send(new ChromeUtilityHostMsg_DecodeImage_Failed());
202 } else {
203 Send(new ChromeUtilityHostMsg_DecodeImage_Succeeded(decoded_image));
205 content::UtilityThread::Get()->ReleaseProcessIfNeeded();
208 void ChromeContentUtilityClient::OnDecodeImageBase64(
209 const std::string& encoded_string) {
210 std::string decoded_string;
212 if (!base::Base64Decode(encoded_string, &decoded_string)) {
213 Send(new ChromeUtilityHostMsg_DecodeImage_Failed());
214 return;
217 std::vector<unsigned char> decoded_vector(decoded_string.size());
218 for (size_t i = 0; i < decoded_string.size(); ++i) {
219 decoded_vector[i] = static_cast<unsigned char>(decoded_string[i]);
222 OnDecodeImage(decoded_vector);
225 #if defined(OS_CHROMEOS)
226 void ChromeContentUtilityClient::OnCreateZipFile(
227 const base::FilePath& src_dir,
228 const std::vector<base::FilePath>& src_relative_paths,
229 const base::FileDescriptor& dest_fd) {
230 bool succeeded = true;
232 // Check sanity of source relative paths. Reject if path is absolute or
233 // contains any attempt to reference a parent directory ("../" tricks).
234 for (std::vector<base::FilePath>::const_iterator iter =
235 src_relative_paths.begin(); iter != src_relative_paths.end();
236 ++iter) {
237 if (iter->IsAbsolute() || iter->ReferencesParent()) {
238 succeeded = false;
239 break;
243 if (succeeded)
244 succeeded = zip::ZipFiles(src_dir, src_relative_paths, dest_fd.fd);
246 if (succeeded)
247 Send(new ChromeUtilityHostMsg_CreateZipFile_Succeeded());
248 else
249 Send(new ChromeUtilityHostMsg_CreateZipFile_Failed());
250 content::UtilityThread::Get()->ReleaseProcessIfNeeded();
252 #endif // defined(OS_CHROMEOS)
254 void ChromeContentUtilityClient::OnRenderPDFPagesToMetafile(
255 base::PlatformFile pdf_file,
256 const base::FilePath& metafile_path,
257 const printing::PdfRenderSettings& pdf_render_settings,
258 const std::vector<printing::PageRange>& page_ranges) {
259 bool succeeded = false;
260 #if defined(OS_WIN)
261 int highest_rendered_page_number = 0;
262 double scale_factor = 1.0;
263 succeeded = RenderPDFToWinMetafile(pdf_file,
264 metafile_path,
265 pdf_render_settings.area(),
266 pdf_render_settings.dpi(),
267 pdf_render_settings.autorotate(),
268 page_ranges,
269 &highest_rendered_page_number,
270 &scale_factor);
271 if (succeeded) {
272 Send(new ChromeUtilityHostMsg_RenderPDFPagesToMetafile_Succeeded(
273 highest_rendered_page_number, scale_factor));
275 #endif // defined(OS_WIN)
276 if (!succeeded) {
277 Send(new ChromeUtilityHostMsg_RenderPDFPagesToMetafile_Failed());
279 content::UtilityThread::Get()->ReleaseProcessIfNeeded();
282 #if defined(OS_WIN)
283 // Exported by pdf.dll
284 typedef bool (*RenderPDFPageToDCProc)(
285 const unsigned char* pdf_buffer, int buffer_size, int page_number, HDC dc,
286 int dpi_x, int dpi_y, int bounds_origin_x, int bounds_origin_y,
287 int bounds_width, int bounds_height, bool fit_to_bounds,
288 bool stretch_to_bounds, bool keep_aspect_ratio, bool center_in_bounds,
289 bool autorotate);
291 typedef bool (*GetPDFDocInfoProc)(const unsigned char* pdf_buffer,
292 int buffer_size, int* page_count,
293 double* max_page_width);
295 // The 2 below IAT patch functions are almost identical to the code in
296 // render_process_impl.cc. This is needed to work around specific Windows APIs
297 // used by the Chrome PDF plugin that will fail in the sandbox.
298 static base::win::IATPatchFunction g_iat_patch_createdca;
299 HDC WINAPI UtilityProcess_CreateDCAPatch(LPCSTR driver_name,
300 LPCSTR device_name,
301 LPCSTR output,
302 const DEVMODEA* init_data) {
303 if (driver_name &&
304 (std::string("DISPLAY") == std::string(driver_name)))
305 // CreateDC fails behind the sandbox, but not CreateCompatibleDC.
306 return CreateCompatibleDC(NULL);
308 NOTREACHED();
309 return CreateDCA(driver_name, device_name, output, init_data);
312 static base::win::IATPatchFunction g_iat_patch_get_font_data;
313 DWORD WINAPI UtilityProcess_GetFontDataPatch(
314 HDC hdc, DWORD table, DWORD offset, LPVOID buffer, DWORD length) {
315 int rv = GetFontData(hdc, table, offset, buffer, length);
316 if (rv == GDI_ERROR && hdc) {
317 HFONT font = static_cast<HFONT>(GetCurrentObject(hdc, OBJ_FONT));
319 LOGFONT logfont;
320 if (GetObject(font, sizeof(LOGFONT), &logfont)) {
321 std::vector<char> font_data;
322 content::UtilityThread::Get()->PreCacheFont(logfont);
323 rv = GetFontData(hdc, table, offset, buffer, length);
324 content::UtilityThread::Get()->ReleaseCachedFonts();
327 return rv;
330 bool ChromeContentUtilityClient::RenderPDFToWinMetafile(
331 base::PlatformFile pdf_file,
332 const base::FilePath& metafile_path,
333 const gfx::Rect& render_area,
334 int render_dpi,
335 bool autorotate,
336 const std::vector<printing::PageRange>& page_ranges,
337 int* highest_rendered_page_number,
338 double* scale_factor) {
339 *highest_rendered_page_number = -1;
340 *scale_factor = 1.0;
341 base::win::ScopedHandle file(pdf_file);
342 base::FilePath pdf_module_path;
343 PathService::Get(chrome::FILE_PDF_PLUGIN, &pdf_module_path);
344 HMODULE pdf_module = GetModuleHandle(pdf_module_path.value().c_str());
345 if (!pdf_module)
346 return false;
348 RenderPDFPageToDCProc render_proc =
349 reinterpret_cast<RenderPDFPageToDCProc>(
350 GetProcAddress(pdf_module, "RenderPDFPageToDC"));
351 if (!render_proc)
352 return false;
354 GetPDFDocInfoProc get_info_proc = reinterpret_cast<GetPDFDocInfoProc>(
355 GetProcAddress(pdf_module, "GetPDFDocInfo"));
356 if (!get_info_proc)
357 return false;
359 // Patch the IAT for handling specific APIs known to fail in the sandbox.
360 if (!g_iat_patch_createdca.is_patched())
361 g_iat_patch_createdca.Patch(pdf_module_path.value().c_str(),
362 "gdi32.dll", "CreateDCA",
363 UtilityProcess_CreateDCAPatch);
365 if (!g_iat_patch_get_font_data.is_patched())
366 g_iat_patch_get_font_data.Patch(pdf_module_path.value().c_str(),
367 "gdi32.dll", "GetFontData",
368 UtilityProcess_GetFontDataPatch);
370 // TODO(sanjeevr): Add a method to the PDF DLL that takes in a file handle
371 // and a page range array. That way we don't need to read the entire PDF into
372 // memory.
373 DWORD length = ::GetFileSize(file, NULL);
374 if (length == INVALID_FILE_SIZE)
375 return false;
377 std::vector<uint8> buffer;
378 buffer.resize(length);
379 DWORD bytes_read = 0;
380 if (!ReadFile(pdf_file, &buffer.front(), length, &bytes_read, NULL) ||
381 (bytes_read != length))
382 return false;
384 int total_page_count = 0;
385 if (!get_info_proc(&buffer.front(), buffer.size(), &total_page_count, NULL))
386 return false;
388 printing::Emf metafile;
389 metafile.InitToFile(metafile_path);
390 // We need to scale down DC to fit an entire page into DC available area.
391 // Current metafile is based on screen DC and have current screen size.
392 // Writing outside of those boundaries will result in the cut-off output.
393 // On metafiles (this is the case here), scaling down will still record
394 // original coordinates and we'll be able to print in full resolution.
395 // Before playback we'll need to counter the scaling up that will happen
396 // in the service (print_system_win.cc).
397 *scale_factor = gfx::CalculatePageScale(metafile.context(),
398 render_area.right(),
399 render_area.bottom());
400 gfx::ScaleDC(metafile.context(), *scale_factor);
402 bool ret = false;
403 std::vector<printing::PageRange>::const_iterator iter;
404 for (iter = page_ranges.begin(); iter != page_ranges.end(); ++iter) {
405 for (int page_number = iter->from; page_number <= iter->to; ++page_number) {
406 if (page_number >= total_page_count)
407 break;
408 // The underlying metafile is of type Emf and ignores the arguments passed
409 // to StartPage.
410 metafile.StartPage(gfx::Size(), gfx::Rect(), 1);
411 if (render_proc(&buffer.front(), buffer.size(), page_number,
412 metafile.context(), render_dpi, render_dpi,
413 render_area.x(), render_area.y(), render_area.width(),
414 render_area.height(), true, false, true, true,
415 autorotate))
416 if (*highest_rendered_page_number < page_number)
417 *highest_rendered_page_number = page_number;
418 ret = true;
419 metafile.FinishPage();
422 metafile.FinishDocument();
423 return ret;
425 #endif // defined(OS_WIN)
427 void ChromeContentUtilityClient::OnRobustJPEGDecodeImage(
428 const std::vector<unsigned char>& encoded_data) {
429 // Our robust jpeg decoding is using IJG libjpeg.
430 if (gfx::JPEGCodec::JpegLibraryVariant() == gfx::JPEGCodec::IJG_LIBJPEG) {
431 scoped_ptr<SkBitmap> decoded_image(gfx::JPEGCodec::Decode(
432 &encoded_data[0], encoded_data.size()));
433 if (!decoded_image.get() || decoded_image->empty()) {
434 Send(new ChromeUtilityHostMsg_DecodeImage_Failed());
435 } else {
436 Send(new ChromeUtilityHostMsg_DecodeImage_Succeeded(*decoded_image));
438 } else {
439 Send(new ChromeUtilityHostMsg_DecodeImage_Failed());
441 content::UtilityThread::Get()->ReleaseProcessIfNeeded();
444 void ChromeContentUtilityClient::OnParseJSON(const std::string& json) {
445 int error_code;
446 std::string error;
447 Value* value = base::JSONReader::ReadAndReturnError(
448 json, base::JSON_PARSE_RFC, &error_code, &error);
449 if (value) {
450 ListValue wrapper;
451 wrapper.Append(value);
452 Send(new ChromeUtilityHostMsg_ParseJSON_Succeeded(wrapper));
453 } else {
454 Send(new ChromeUtilityHostMsg_ParseJSON_Failed(error));
456 content::UtilityThread::Get()->ReleaseProcessIfNeeded();
459 void ChromeContentUtilityClient::OnGetPrinterCapsAndDefaults(
460 const std::string& printer_name) {
461 #if defined(ENABLE_PRINTING)
462 scoped_refptr<printing::PrintBackend> print_backend =
463 printing::PrintBackend::CreateInstance(NULL);
464 printing::PrinterCapsAndDefaults printer_info;
466 child_process_logging::ScopedPrinterInfoSetter prn_info(
467 print_backend->GetPrinterDriverInfo(printer_name));
469 if (print_backend->GetPrinterCapsAndDefaults(printer_name, &printer_info)) {
470 Send(new ChromeUtilityHostMsg_GetPrinterCapsAndDefaults_Succeeded(
471 printer_name, printer_info));
472 } else
473 #endif
475 Send(new ChromeUtilityHostMsg_GetPrinterCapsAndDefaults_Failed(
476 printer_name));
478 content::UtilityThread::Get()->ReleaseProcessIfNeeded();
481 void ChromeContentUtilityClient::OnStartupPing() {
482 Send(new ChromeUtilityHostMsg_ProcessStarted);
483 // Don't release the process, we assume further messages are on the way.
486 void ChromeContentUtilityClient::OnAnalyzeZipFileForDownloadProtection(
487 IPC::PlatformFileForTransit zip_file) {
488 safe_browsing::zip_analyzer::Results results;
489 safe_browsing::zip_analyzer::AnalyzeZipFile(
490 IPC::PlatformFileForTransitToPlatformFile(zip_file), &results);
491 Send(new ChromeUtilityHostMsg_AnalyzeZipFileForDownloadProtection_Finished(
492 results));
493 content::UtilityThread::Get()->ReleaseProcessIfNeeded();
496 } // namespace chrome