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"
9 #include "base/command_line.h"
10 #include "base/file_util.h"
11 #include "base/files/file_path.h"
12 #include "base/json/json_reader.h"
13 #include "base/memory/ref_counted.h"
14 #include "base/path_service.h"
15 #include "base/scoped_native_library.h"
16 #include "base/time/time.h"
17 #include "chrome/common/chrome_paths.h"
18 #include "chrome/common/chrome_utility_messages.h"
19 #include "chrome/common/extensions/chrome_extensions_client.h"
20 #include "chrome/common/extensions/update_manifest.h"
21 #include "chrome/common/safe_browsing/zip_analyzer.h"
22 #include "chrome/utility/chrome_content_utility_ipc_whitelist.h"
23 #include "chrome/utility/cloud_print/bitmap_image.h"
24 #include "chrome/utility/cloud_print/pwg_encoder.h"
25 #include "chrome/utility/extensions/unpacker.h"
26 #include "chrome/utility/image_writer/image_writer_handler.h"
27 #include "chrome/utility/profile_import_handler.h"
28 #include "chrome/utility/web_resource_unpacker.h"
29 #include "content/public/child/image_decoder_utils.h"
30 #include "content/public/common/content_paths.h"
31 #include "content/public/common/content_switches.h"
32 #include "content/public/utility/utility_thread.h"
33 #include "courgette/courgette.h"
34 #include "courgette/third_party/bsdiff.h"
35 #include "extensions/common/extension.h"
36 #include "extensions/common/extension_l10n_util.h"
37 #include "extensions/common/manifest.h"
38 #include "media/base/media.h"
39 #include "media/base/media_file_checker.h"
40 #include "printing/page_range.h"
41 #include "printing/pdf_render_settings.h"
42 #include "third_party/skia/include/core/SkBitmap.h"
43 #include "third_party/zlib/google/zip.h"
44 #include "ui/base/ui_base_switches.h"
45 #include "ui/gfx/codec/jpeg_codec.h"
46 #include "ui/gfx/rect.h"
47 #include "ui/gfx/size.h"
50 #include "base/win/iat_patch_function.h"
51 #include "base/win/scoped_handle.h"
52 #include "chrome/common/extensions/api/networking_private/networking_private_crypto.h"
53 #include "chrome/utility/media_galleries/itunes_pref_parser_win.h"
54 #include "components/wifi/wifi_service.h"
55 #include "printing/emf_win.h"
56 #include "ui/gfx/gdi_util.h"
57 #endif // defined(OS_WIN)
59 #if defined(OS_MACOSX)
60 #include "chrome/utility/media_galleries/iphoto_library_parser.h"
61 #endif // defined(OS_MACOSX)
63 #if defined(OS_WIN) || defined(OS_MACOSX)
64 #include "chrome/utility/media_galleries/iapps_xml_utils.h"
65 #include "chrome/utility/media_galleries/itunes_library_parser.h"
66 #include "chrome/utility/media_galleries/picasa_album_table_reader.h"
67 #include "chrome/utility/media_galleries/picasa_albums_indexer.h"
68 #endif // defined(OS_WIN) || defined(OS_MACOSX)
70 #if !defined(OS_ANDROID) && !defined(OS_IOS)
71 #include "chrome/utility/media_galleries/image_metadata_extractor.h"
72 #include "chrome/utility/media_galleries/ipc_data_source.h"
73 #include "chrome/utility/media_galleries/media_metadata_parser.h"
74 #endif // !defined(OS_ANDROID) && !defined(OS_IOS)
76 #if defined(ENABLE_FULL_PRINTING)
77 #include "chrome/common/crash_keys.h"
78 #include "printing/backend/print_backend.h"
81 #if defined(ENABLE_MDNS)
82 #include "chrome/utility/local_discovery/service_discovery_message_handler.h"
89 bool Send(IPC::Message
* message
) {
90 return content::UtilityThread::Get()->Send(message
);
93 void ReleaseProcessIfNeeded() {
94 content::UtilityThread::Get()->ReleaseProcessIfNeeded();
97 class PdfFunctionsBase
{
99 PdfFunctionsBase() : render_pdf_to_bitmap_func_(NULL
),
100 get_pdf_doc_info_func_(NULL
) {}
103 base::FilePath pdf_module_path
;
104 if (!PathService::Get(chrome::FILE_PDF_PLUGIN
, &pdf_module_path
) ||
105 !base::PathExists(pdf_module_path
)) {
109 pdf_lib_
.Reset(base::LoadNativeLibrary(pdf_module_path
, NULL
));
110 if (!pdf_lib_
.is_valid()) {
111 LOG(WARNING
) << "Couldn't load PDF plugin";
115 render_pdf_to_bitmap_func_
=
116 reinterpret_cast<RenderPDFPageToBitmapProc
>(
117 pdf_lib_
.GetFunctionPointer("RenderPDFPageToBitmap"));
118 LOG_IF(WARNING
, !render_pdf_to_bitmap_func_
) <<
119 "Missing RenderPDFPageToBitmap";
121 get_pdf_doc_info_func_
=
122 reinterpret_cast<GetPDFDocInfoProc
>(
123 pdf_lib_
.GetFunctionPointer("GetPDFDocInfo"));
124 LOG_IF(WARNING
, !get_pdf_doc_info_func_
) << "Missing GetPDFDocInfo";
126 if (!render_pdf_to_bitmap_func_
|| !get_pdf_doc_info_func_
||
127 !PlatformInit(pdf_module_path
, pdf_lib_
)) {
134 bool IsValid() const {
135 return pdf_lib_
.is_valid();
139 pdf_lib_
.Reset(NULL
);
142 bool RenderPDFPageToBitmap(const void* pdf_buffer
,
151 if (!render_pdf_to_bitmap_func_
)
153 return render_pdf_to_bitmap_func_(pdf_buffer
, pdf_buffer_size
, page_number
,
154 bitmap_buffer
, bitmap_width
,
155 bitmap_height
, dpi_x
, dpi_y
, autorotate
);
158 bool GetPDFDocInfo(const void* pdf_buffer
,
161 double* max_page_width
) {
162 if (!get_pdf_doc_info_func_
)
164 return get_pdf_doc_info_func_(pdf_buffer
, buffer_size
, page_count
,
169 virtual bool PlatformInit(
170 const base::FilePath
& pdf_module_path
,
171 const base::ScopedNativeLibrary
& pdf_lib
) {
176 // Exported by PDF plugin.
177 typedef bool (*RenderPDFPageToBitmapProc
)(const void* pdf_buffer
,
186 typedef bool (*GetPDFDocInfoProc
)(const void* pdf_buffer
,
187 int buffer_size
, int* page_count
,
188 double* max_page_width
);
190 RenderPDFPageToBitmapProc render_pdf_to_bitmap_func_
;
191 GetPDFDocInfoProc get_pdf_doc_info_func_
;
193 base::ScopedNativeLibrary pdf_lib_
;
194 DISALLOW_COPY_AND_ASSIGN(PdfFunctionsBase
);
198 // The 2 below IAT patch functions are almost identical to the code in
199 // render_process_impl.cc. This is needed to work around specific Windows APIs
200 // used by the Chrome PDF plugin that will fail in the sandbox.
201 static base::win::IATPatchFunction g_iat_patch_createdca
;
202 HDC WINAPI
UtilityProcess_CreateDCAPatch(LPCSTR driver_name
,
205 const DEVMODEA
* init_data
) {
206 if (driver_name
&& (std::string("DISPLAY") == driver_name
)) {
207 // CreateDC fails behind the sandbox, but not CreateCompatibleDC.
208 return CreateCompatibleDC(NULL
);
212 return CreateDCA(driver_name
, device_name
, output
, init_data
);
215 static base::win::IATPatchFunction g_iat_patch_get_font_data
;
216 DWORD WINAPI
UtilityProcess_GetFontDataPatch(
217 HDC hdc
, DWORD table
, DWORD offset
, LPVOID buffer
, DWORD length
) {
218 int rv
= GetFontData(hdc
, table
, offset
, buffer
, length
);
219 if (rv
== GDI_ERROR
&& hdc
) {
220 HFONT font
= static_cast<HFONT
>(GetCurrentObject(hdc
, OBJ_FONT
));
223 if (GetObject(font
, sizeof(LOGFONT
), &logfont
)) {
224 content::UtilityThread::Get()->PreCacheFont(logfont
);
225 rv
= GetFontData(hdc
, table
, offset
, buffer
, length
);
226 content::UtilityThread::Get()->ReleaseCachedFonts();
232 class PdfFunctionsWin
: public PdfFunctionsBase
{
234 PdfFunctionsWin() : render_pdf_to_dc_func_(NULL
) {
238 const base::FilePath
& pdf_module_path
,
239 const base::ScopedNativeLibrary
& pdf_lib
) OVERRIDE
{
240 // Patch the IAT for handling specific APIs known to fail in the sandbox.
241 if (!g_iat_patch_createdca
.is_patched()) {
242 g_iat_patch_createdca
.Patch(pdf_module_path
.value().c_str(),
243 "gdi32.dll", "CreateDCA",
244 UtilityProcess_CreateDCAPatch
);
247 if (!g_iat_patch_get_font_data
.is_patched()) {
248 g_iat_patch_get_font_data
.Patch(pdf_module_path
.value().c_str(),
249 "gdi32.dll", "GetFontData",
250 UtilityProcess_GetFontDataPatch
);
252 render_pdf_to_dc_func_
=
253 reinterpret_cast<RenderPDFPageToDCProc
>(
254 pdf_lib
.GetFunctionPointer("RenderPDFPageToDC"));
255 LOG_IF(WARNING
, !render_pdf_to_dc_func_
) << "Missing RenderPDFPageToDC";
257 return render_pdf_to_dc_func_
!= NULL
;
260 bool RenderPDFPageToDC(const void* pdf_buffer
,
271 bool stretch_to_bounds
,
272 bool keep_aspect_ratio
,
273 bool center_in_bounds
,
275 if (!render_pdf_to_dc_func_
)
277 return render_pdf_to_dc_func_(pdf_buffer
, buffer_size
, page_number
,
278 dc
, dpi_x
, dpi_y
, bounds_origin_x
,
279 bounds_origin_y
, bounds_width
, bounds_height
,
280 fit_to_bounds
, stretch_to_bounds
,
281 keep_aspect_ratio
, center_in_bounds
,
286 // Exported by PDF plugin.
287 typedef bool (*RenderPDFPageToDCProc
)(
288 const void* pdf_buffer
, int buffer_size
, int page_number
, HDC dc
,
289 int dpi_x
, int dpi_y
, int bounds_origin_x
, int bounds_origin_y
,
290 int bounds_width
, int bounds_height
, bool fit_to_bounds
,
291 bool stretch_to_bounds
, bool keep_aspect_ratio
, bool center_in_bounds
,
293 RenderPDFPageToDCProc render_pdf_to_dc_func_
;
295 DISALLOW_COPY_AND_ASSIGN(PdfFunctionsWin
);
298 typedef PdfFunctionsWin PdfFunctions
;
300 typedef PdfFunctionsBase PdfFunctions
;
303 #if !defined(OS_ANDROID) && !defined(OS_IOS)
304 void FinishParseMediaMetadata(
305 metadata::MediaMetadataParser
* parser
,
306 scoped_ptr
<extensions::api::media_galleries::MediaMetadata
> metadata
) {
307 Send(new ChromeUtilityHostMsg_ParseMediaMetadata_Finished(
308 true, *(metadata
->ToValue().get())));
309 ReleaseProcessIfNeeded();
311 #endif // !defined(OS_ANDROID) && !defined(OS_IOS)
313 static base::LazyInstance
<PdfFunctions
> g_pdf_lib
= LAZY_INSTANCE_INITIALIZER
;
317 ChromeContentUtilityClient::ChromeContentUtilityClient()
318 : filter_messages_(false) {
319 #if !defined(OS_ANDROID)
320 handlers_
.push_back(new ProfileImportHandler());
323 #if defined(ENABLE_MDNS)
324 if (CommandLine::ForCurrentProcess()->HasSwitch(
325 switches::kUtilityProcessEnableMDns
)) {
326 handlers_
.push_back(new local_discovery::ServiceDiscoveryMessageHandler());
328 #endif // ENABLE_MDNS
330 handlers_
.push_back(new image_writer::ImageWriterHandler());
333 ChromeContentUtilityClient::~ChromeContentUtilityClient() {
336 void ChromeContentUtilityClient::UtilityThreadStarted() {
337 CommandLine
* command_line
= CommandLine::ForCurrentProcess();
338 std::string lang
= command_line
->GetSwitchValueASCII(switches::kLang
);
340 extension_l10n_util::SetProcessLocale(lang
);
342 if (command_line
->HasSwitch(switches::kUtilityProcessRunningElevated
)) {
343 message_id_whitelist_
.insert(kMessageWhitelist
,
344 kMessageWhitelist
+ kMessageWhitelistSize
);
345 filter_messages_
= true;
349 bool ChromeContentUtilityClient::OnMessageReceived(
350 const IPC::Message
& message
) {
351 if (filter_messages_
&&
352 (message_id_whitelist_
.find(message
.type()) ==
353 message_id_whitelist_
.end())) {
358 IPC_BEGIN_MESSAGE_MAP(ChromeContentUtilityClient
, message
)
359 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_UnpackExtension
, OnUnpackExtension
)
360 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_UnpackWebResource
,
362 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseUpdateManifest
,
363 OnParseUpdateManifest
)
364 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_DecodeImage
, OnDecodeImage
)
365 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_DecodeImageBase64
, OnDecodeImageBase64
)
366 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_RenderPDFPagesToMetafile
,
367 OnRenderPDFPagesToMetafile
)
368 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_RenderPDFPagesToPWGRaster
,
369 OnRenderPDFPagesToPWGRaster
)
370 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_RobustJPEGDecodeImage
,
371 OnRobustJPEGDecodeImage
)
372 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseJSON
, OnParseJSON
)
373 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_GetPrinterCapsAndDefaults
,
374 OnGetPrinterCapsAndDefaults
)
375 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_GetPrinterSemanticCapsAndDefaults
,
376 OnGetPrinterSemanticCapsAndDefaults
)
377 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_PatchFileBsdiff
,
379 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_PatchFileCourgette
,
380 OnPatchFileCourgette
)
381 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_StartupPing
, OnStartupPing
)
382 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_AnalyzeZipFileForDownloadProtection
,
383 OnAnalyzeZipFileForDownloadProtection
)
385 #if !defined(OS_ANDROID) && !defined(OS_IOS)
386 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_CheckMediaFile
, OnCheckMediaFile
)
387 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseMediaMetadata
,
388 OnParseMediaMetadata
)
389 #endif // !defined(OS_ANDROID) && !defined(OS_IOS)
391 #if defined(OS_CHROMEOS)
392 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_CreateZipFile
, OnCreateZipFile
)
393 #endif // defined(OS_CHROMEOS)
396 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseITunesPrefXml
,
397 OnParseITunesPrefXml
)
398 #endif // defined(OS_WIN)
400 #if defined(OS_MACOSX)
401 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseIPhotoLibraryXmlFile
,
402 OnParseIPhotoLibraryXmlFile
)
403 #endif // defined(OS_MACOSX)
405 #if defined(OS_WIN) || defined(OS_MACOSX)
406 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseITunesLibraryXmlFile
,
407 OnParseITunesLibraryXmlFile
)
408 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParsePicasaPMPDatabase
,
409 OnParsePicasaPMPDatabase
)
410 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_IndexPicasaAlbumsContents
,
411 OnIndexPicasaAlbumsContents
)
412 #endif // defined(OS_WIN) || defined(OS_MACOSX)
415 IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_GetAndEncryptWiFiCredentials
,
416 OnGetAndEncryptWiFiCredentials
)
417 #endif // defined(OS_WIN)
419 IPC_MESSAGE_UNHANDLED(handled
= false)
420 IPC_END_MESSAGE_MAP()
422 for (Handlers::iterator it
= handlers_
.begin();
423 !handled
&& it
!= handlers_
.end(); ++it
) {
424 handled
= (*it
)->OnMessageReceived(message
);
431 void ChromeContentUtilityClient::PreSandboxStartup() {
432 #if defined(ENABLE_MDNS)
433 if (CommandLine::ForCurrentProcess()->HasSwitch(
434 switches::kUtilityProcessEnableMDns
)) {
435 local_discovery::ServiceDiscoveryMessageHandler::PreSandboxStartup();
437 #endif // ENABLE_MDNS
439 g_pdf_lib
.Get().Init();
441 #if !defined(OS_ANDROID) && !defined(OS_IOS)
442 // Initialize libexif for image metadata parsing.
443 metadata::ImageMetadataExtractor::InitializeLibrary();
444 #endif // !defined(OS_ANDROID) && !defined(OS_IOS)
446 // Load media libraries for media file validation.
447 base::FilePath media_path
;
448 PathService::Get(content::DIR_MEDIA_LIBS
, &media_path
);
449 if (!media_path
.empty())
450 media::InitializeMediaLibrary(media_path
);
453 void ChromeContentUtilityClient::OnUnpackExtension(
454 const base::FilePath
& extension_path
,
455 const std::string
& extension_id
,
457 int creation_flags
) {
458 CHECK_GT(location
, extensions::Manifest::INVALID_LOCATION
);
459 CHECK_LT(location
, extensions::Manifest::NUM_LOCATIONS
);
460 extensions::ExtensionsClient::Set(
461 extensions::ChromeExtensionsClient::GetInstance());
462 extensions::Unpacker
unpacker(
465 static_cast<extensions::Manifest::Location
>(location
),
467 if (unpacker
.Run() && unpacker
.DumpImagesToFile() &&
468 unpacker
.DumpMessageCatalogsToFile()) {
469 Send(new ChromeUtilityHostMsg_UnpackExtension_Succeeded(
470 *unpacker
.parsed_manifest()));
472 Send(new ChromeUtilityHostMsg_UnpackExtension_Failed(
473 unpacker
.error_message()));
476 ReleaseProcessIfNeeded();
479 void ChromeContentUtilityClient::OnUnpackWebResource(
480 const std::string
& resource_data
) {
482 // TODO(mrc): Add the possibility of a template that controls parsing, and
483 // the ability to download and verify images.
484 WebResourceUnpacker
unpacker(resource_data
);
485 if (unpacker
.Run()) {
486 Send(new ChromeUtilityHostMsg_UnpackWebResource_Succeeded(
487 *unpacker
.parsed_json()));
489 Send(new ChromeUtilityHostMsg_UnpackWebResource_Failed(
490 unpacker
.error_message()));
493 ReleaseProcessIfNeeded();
496 void ChromeContentUtilityClient::OnParseUpdateManifest(const std::string
& xml
) {
497 UpdateManifest manifest
;
498 if (!manifest
.Parse(xml
)) {
499 Send(new ChromeUtilityHostMsg_ParseUpdateManifest_Failed(
502 Send(new ChromeUtilityHostMsg_ParseUpdateManifest_Succeeded(
503 manifest
.results()));
505 ReleaseProcessIfNeeded();
508 void ChromeContentUtilityClient::OnDecodeImage(
509 const std::vector
<unsigned char>& encoded_data
) {
510 const SkBitmap
& decoded_image
= content::DecodeImage(&encoded_data
[0],
512 encoded_data
.size());
513 if (decoded_image
.empty()) {
514 Send(new ChromeUtilityHostMsg_DecodeImage_Failed());
516 Send(new ChromeUtilityHostMsg_DecodeImage_Succeeded(decoded_image
));
518 ReleaseProcessIfNeeded();
521 void ChromeContentUtilityClient::OnDecodeImageBase64(
522 const std::string
& encoded_string
) {
523 std::string decoded_string
;
525 if (!base::Base64Decode(encoded_string
, &decoded_string
)) {
526 Send(new ChromeUtilityHostMsg_DecodeImage_Failed());
530 std::vector
<unsigned char> decoded_vector(decoded_string
.size());
531 for (size_t i
= 0; i
< decoded_string
.size(); ++i
) {
532 decoded_vector
[i
] = static_cast<unsigned char>(decoded_string
[i
]);
535 OnDecodeImage(decoded_vector
);
538 #if defined(OS_CHROMEOS)
539 void ChromeContentUtilityClient::OnCreateZipFile(
540 const base::FilePath
& src_dir
,
541 const std::vector
<base::FilePath
>& src_relative_paths
,
542 const base::FileDescriptor
& dest_fd
) {
543 bool succeeded
= true;
545 // Check sanity of source relative paths. Reject if path is absolute or
546 // contains any attempt to reference a parent directory ("../" tricks).
547 for (std::vector
<base::FilePath
>::const_iterator iter
=
548 src_relative_paths
.begin(); iter
!= src_relative_paths
.end();
550 if (iter
->IsAbsolute() || iter
->ReferencesParent()) {
557 succeeded
= zip::ZipFiles(src_dir
, src_relative_paths
, dest_fd
.fd
);
560 Send(new ChromeUtilityHostMsg_CreateZipFile_Succeeded());
562 Send(new ChromeUtilityHostMsg_CreateZipFile_Failed());
563 ReleaseProcessIfNeeded();
565 #endif // defined(OS_CHROMEOS)
567 void ChromeContentUtilityClient::OnRenderPDFPagesToMetafile(
568 base::PlatformFile pdf_file
,
569 const base::FilePath
& metafile_path
,
570 const printing::PdfRenderSettings
& settings
,
571 const std::vector
<printing::PageRange
>& page_ranges
) {
572 bool succeeded
= false;
574 int highest_rendered_page_number
= 0;
575 double scale_factor
= 1.0;
576 succeeded
= RenderPDFToWinMetafile(pdf_file
,
580 &highest_rendered_page_number
,
583 Send(new ChromeUtilityHostMsg_RenderPDFPagesToMetafile_Succeeded(
584 highest_rendered_page_number
, scale_factor
));
586 #endif // defined(OS_WIN)
588 Send(new ChromeUtilityHostMsg_RenderPDFPagesToMetafile_Failed());
590 ReleaseProcessIfNeeded();
593 void ChromeContentUtilityClient::OnRenderPDFPagesToPWGRaster(
594 IPC::PlatformFileForTransit pdf_transit
,
595 const printing::PdfRenderSettings
& settings
,
596 const printing::PwgRasterSettings
& bitmap_settings
,
597 IPC::PlatformFileForTransit bitmap_transit
) {
598 base::PlatformFile pdf
=
599 IPC::PlatformFileForTransitToPlatformFile(pdf_transit
);
600 base::PlatformFile bitmap
=
601 IPC::PlatformFileForTransitToPlatformFile(bitmap_transit
);
602 if (RenderPDFPagesToPWGRaster(pdf
, settings
, bitmap_settings
, bitmap
)) {
603 Send(new ChromeUtilityHostMsg_RenderPDFPagesToPWGRaster_Succeeded());
605 Send(new ChromeUtilityHostMsg_RenderPDFPagesToPWGRaster_Failed());
607 ReleaseProcessIfNeeded();
611 bool ChromeContentUtilityClient::RenderPDFToWinMetafile(
612 base::PlatformFile pdf_file
,
613 const base::FilePath
& metafile_path
,
614 const printing::PdfRenderSettings
& settings
,
615 const std::vector
<printing::PageRange
>& page_ranges
,
616 int* highest_rendered_page_number
,
617 double* scale_factor
) {
618 *highest_rendered_page_number
= -1;
620 base::win::ScopedHandle
file(pdf_file
);
622 if (!g_pdf_lib
.Get().IsValid())
625 // TODO(sanjeevr): Add a method to the PDF DLL that takes in a file handle
626 // and a page range array. That way we don't need to read the entire PDF into
628 DWORD length
= ::GetFileSize(file
, NULL
);
629 if (length
== INVALID_FILE_SIZE
)
632 std::vector
<uint8
> buffer
;
633 buffer
.resize(length
);
634 DWORD bytes_read
= 0;
635 if (!ReadFile(pdf_file
, &buffer
.front(), length
, &bytes_read
, NULL
) ||
636 (bytes_read
!= length
)) {
640 int total_page_count
= 0;
641 if (!g_pdf_lib
.Get().GetPDFDocInfo(&buffer
.front(), buffer
.size(),
642 &total_page_count
, NULL
)) {
646 printing::Emf metafile
;
647 metafile
.InitToFile(metafile_path
);
648 // We need to scale down DC to fit an entire page into DC available area.
649 // Current metafile is based on screen DC and have current screen size.
650 // Writing outside of those boundaries will result in the cut-off output.
651 // On metafiles (this is the case here), scaling down will still record
652 // original coordinates and we'll be able to print in full resolution.
653 // Before playback we'll need to counter the scaling up that will happen
654 // in the service (print_system_win.cc).
655 *scale_factor
= gfx::CalculatePageScale(metafile
.context(),
656 settings
.area().right(),
657 settings
.area().bottom());
658 gfx::ScaleDC(metafile
.context(), *scale_factor
);
661 std::vector
<printing::PageRange
>::const_iterator iter
;
662 for (iter
= page_ranges
.begin(); iter
!= page_ranges
.end(); ++iter
) {
663 for (int page_number
= iter
->from
; page_number
<= iter
->to
; ++page_number
) {
664 if (page_number
>= total_page_count
)
666 // The underlying metafile is of type Emf and ignores the arguments passed
668 metafile
.StartPage(gfx::Size(), gfx::Rect(), 1);
669 if (g_pdf_lib
.Get().RenderPDFPageToDC(
670 &buffer
.front(), buffer
.size(), page_number
, metafile
.context(),
671 settings
.dpi(), settings
.dpi(), settings
.area().x(),
672 settings
.area().y(), settings
.area().width(),
673 settings
.area().height(), true, false, true, true,
674 settings
.autorotate())) {
675 if (*highest_rendered_page_number
< page_number
)
676 *highest_rendered_page_number
= page_number
;
679 metafile
.FinishPage();
682 metafile
.FinishDocument();
685 #endif // defined(OS_WIN)
687 bool ChromeContentUtilityClient::RenderPDFPagesToPWGRaster(
688 base::PlatformFile pdf_file
,
689 const printing::PdfRenderSettings
& settings
,
690 const printing::PwgRasterSettings
& bitmap_settings
,
691 base::PlatformFile bitmap_file
) {
692 bool autoupdate
= true;
693 if (!g_pdf_lib
.Get().IsValid())
696 base::PlatformFileInfo info
;
697 if (!base::GetPlatformFileInfo(pdf_file
, &info
) || info
.size
<= 0)
700 std::string
data(info
.size
, 0);
701 int data_size
= base::ReadPlatformFile(pdf_file
, 0, &data
[0], data
.size());
702 if (data_size
!= static_cast<int>(data
.size()))
705 int total_page_count
= 0;
706 if (!g_pdf_lib
.Get().GetPDFDocInfo(data
.data(), data
.size(),
707 &total_page_count
, NULL
)) {
711 cloud_print::PwgEncoder encoder
;
712 std::string pwg_header
;
713 encoder
.EncodeDocumentHeader(&pwg_header
);
714 int bytes_written
= base::WritePlatformFileAtCurrentPos(bitmap_file
,
717 if (bytes_written
!= static_cast<int>(pwg_header
.size()))
720 cloud_print::BitmapImage
image(settings
.area().size(),
721 cloud_print::BitmapImage::BGRA
);
722 for (int i
= 0; i
< total_page_count
; ++i
) {
725 if (bitmap_settings
.reverse_page_order
) {
726 page_number
= total_page_count
- 1 - page_number
;
729 if (!g_pdf_lib
.Get().RenderPDFPageToBitmap(data
.data(),
733 image
.size().width(),
734 image
.size().height(),
741 cloud_print::PwgHeaderInfo header_info
;
742 header_info
.dpi
= settings
.dpi();
743 header_info
.total_pages
= total_page_count
;
745 // Transform odd pages.
746 if (page_number
% 2) {
747 switch (bitmap_settings
.odd_page_transform
) {
748 case printing::TRANSFORM_NORMAL
:
750 case printing::TRANSFORM_ROTATE_180
:
751 header_info
.flipx
= true;
752 header_info
.flipy
= true;
754 case printing::TRANSFORM_FLIP_HORIZONTAL
:
755 header_info
.flipx
= true;
757 case printing::TRANSFORM_FLIP_VERTICAL
:
758 header_info
.flipy
= true;
763 if (bitmap_settings
.rotate_all_pages
) {
764 header_info
.flipx
= !header_info
.flipx
;
765 header_info
.flipy
= !header_info
.flipy
;
768 std::string pwg_page
;
769 if (!encoder
.EncodePage(image
, header_info
, &pwg_page
))
771 bytes_written
= base::WritePlatformFileAtCurrentPos(bitmap_file
,
774 if (bytes_written
!= static_cast<int>(pwg_page
.size()))
780 void ChromeContentUtilityClient::OnRobustJPEGDecodeImage(
781 const std::vector
<unsigned char>& encoded_data
) {
782 // Our robust jpeg decoding is using IJG libjpeg.
783 if (gfx::JPEGCodec::JpegLibraryVariant() == gfx::JPEGCodec::IJG_LIBJPEG
) {
784 scoped_ptr
<SkBitmap
> decoded_image(gfx::JPEGCodec::Decode(
785 &encoded_data
[0], encoded_data
.size()));
786 if (!decoded_image
.get() || decoded_image
->empty()) {
787 Send(new ChromeUtilityHostMsg_DecodeImage_Failed());
789 Send(new ChromeUtilityHostMsg_DecodeImage_Succeeded(*decoded_image
));
792 Send(new ChromeUtilityHostMsg_DecodeImage_Failed());
794 ReleaseProcessIfNeeded();
797 void ChromeContentUtilityClient::OnParseJSON(const std::string
& json
) {
800 base::Value
* value
= base::JSONReader::ReadAndReturnError(
801 json
, base::JSON_PARSE_RFC
, &error_code
, &error
);
803 base::ListValue wrapper
;
804 wrapper
.Append(value
);
805 Send(new ChromeUtilityHostMsg_ParseJSON_Succeeded(wrapper
));
807 Send(new ChromeUtilityHostMsg_ParseJSON_Failed(error
));
809 ReleaseProcessIfNeeded();
812 void ChromeContentUtilityClient::OnGetPrinterCapsAndDefaults(
813 const std::string
& printer_name
) {
814 #if defined(ENABLE_FULL_PRINTING)
815 scoped_refptr
<printing::PrintBackend
> print_backend
=
816 printing::PrintBackend::CreateInstance(NULL
);
817 printing::PrinterCapsAndDefaults printer_info
;
819 crash_keys::ScopedPrinterInfo
crash_key(
820 print_backend
->GetPrinterDriverInfo(printer_name
));
822 if (print_backend
->GetPrinterCapsAndDefaults(printer_name
, &printer_info
)) {
823 Send(new ChromeUtilityHostMsg_GetPrinterCapsAndDefaults_Succeeded(
824 printer_name
, printer_info
));
828 Send(new ChromeUtilityHostMsg_GetPrinterCapsAndDefaults_Failed(
831 ReleaseProcessIfNeeded();
834 void ChromeContentUtilityClient::OnGetPrinterSemanticCapsAndDefaults(
835 const std::string
& printer_name
) {
836 #if defined(ENABLE_FULL_PRINTING)
837 scoped_refptr
<printing::PrintBackend
> print_backend
=
838 printing::PrintBackend::CreateInstance(NULL
);
839 printing::PrinterSemanticCapsAndDefaults printer_info
;
841 crash_keys::ScopedPrinterInfo
crash_key(
842 print_backend
->GetPrinterDriverInfo(printer_name
));
844 if (print_backend
->GetPrinterSemanticCapsAndDefaults(printer_name
,
846 Send(new ChromeUtilityHostMsg_GetPrinterSemanticCapsAndDefaults_Succeeded(
847 printer_name
, printer_info
));
851 Send(new ChromeUtilityHostMsg_GetPrinterSemanticCapsAndDefaults_Failed(
854 ReleaseProcessIfNeeded();
857 void ChromeContentUtilityClient::OnPatchFileBsdiff(
858 const base::FilePath
& input_file
,
859 const base::FilePath
& patch_file
,
860 const base::FilePath
& output_file
) {
861 if (input_file
.empty() || patch_file
.empty() || output_file
.empty()) {
862 Send(new ChromeUtilityHostMsg_PatchFile_Failed(-1));
864 const int patch_status
= courgette::ApplyBinaryPatch(input_file
,
867 if (patch_status
!= courgette::OK
)
868 Send(new ChromeUtilityHostMsg_PatchFile_Failed(patch_status
));
870 Send(new ChromeUtilityHostMsg_PatchFile_Succeeded());
872 ReleaseProcessIfNeeded();
875 void ChromeContentUtilityClient::OnPatchFileCourgette(
876 const base::FilePath
& input_file
,
877 const base::FilePath
& patch_file
,
878 const base::FilePath
& output_file
) {
879 if (input_file
.empty() || patch_file
.empty() || output_file
.empty()) {
880 Send(new ChromeUtilityHostMsg_PatchFile_Failed(-1));
882 const int patch_status
= courgette::ApplyEnsemblePatch(
883 input_file
.value().c_str(),
884 patch_file
.value().c_str(),
885 output_file
.value().c_str());
886 if (patch_status
!= courgette::C_OK
)
887 Send(new ChromeUtilityHostMsg_PatchFile_Failed(patch_status
));
889 Send(new ChromeUtilityHostMsg_PatchFile_Succeeded());
891 ReleaseProcessIfNeeded();
894 void ChromeContentUtilityClient::OnStartupPing() {
895 Send(new ChromeUtilityHostMsg_ProcessStarted
);
896 // Don't release the process, we assume further messages are on the way.
899 void ChromeContentUtilityClient::OnAnalyzeZipFileForDownloadProtection(
900 const IPC::PlatformFileForTransit
& zip_file
) {
901 safe_browsing::zip_analyzer::Results results
;
902 safe_browsing::zip_analyzer::AnalyzeZipFile(
903 IPC::PlatformFileForTransitToPlatformFile(zip_file
), &results
);
904 Send(new ChromeUtilityHostMsg_AnalyzeZipFileForDownloadProtection_Finished(
906 ReleaseProcessIfNeeded();
909 #if !defined(OS_ANDROID) && !defined(OS_IOS)
910 void ChromeContentUtilityClient::OnCheckMediaFile(
911 int64 milliseconds_of_decoding
,
912 const IPC::PlatformFileForTransit
& media_file
) {
913 media::MediaFileChecker
checker(
914 base::File(IPC::PlatformFileForTransitToPlatformFile(media_file
)));
915 const bool check_success
= checker
.Start(
916 base::TimeDelta::FromMilliseconds(milliseconds_of_decoding
));
917 Send(new ChromeUtilityHostMsg_CheckMediaFile_Finished(check_success
));
918 ReleaseProcessIfNeeded();
921 void ChromeContentUtilityClient::OnParseMediaMetadata(
922 const std::string
& mime_type
,
924 // Only one IPCDataSource may be created and added to the list of handlers.
925 metadata::IPCDataSource
* source
= new metadata::IPCDataSource(total_size
);
926 handlers_
.push_back(source
);
928 metadata::MediaMetadataParser
* parser
=
929 new metadata::MediaMetadataParser(source
, mime_type
);
930 parser
->Start(base::Bind(&FinishParseMediaMetadata
, base::Owned(parser
)));
932 #endif // !defined(OS_ANDROID) && !defined(OS_IOS)
935 void ChromeContentUtilityClient::OnParseITunesPrefXml(
936 const std::string
& itunes_xml_data
) {
937 base::FilePath
library_path(
938 itunes::FindLibraryLocationInPrefXml(itunes_xml_data
));
939 Send(new ChromeUtilityHostMsg_GotITunesDirectory(library_path
));
940 ReleaseProcessIfNeeded();
942 #endif // defined(OS_WIN)
944 #if defined(OS_MACOSX)
945 void ChromeContentUtilityClient::OnParseIPhotoLibraryXmlFile(
946 const IPC::PlatformFileForTransit
& iphoto_library_file
) {
947 iphoto::IPhotoLibraryParser parser
;
948 base::PlatformFile file
=
949 IPC::PlatformFileForTransitToPlatformFile(iphoto_library_file
);
950 bool result
= parser
.Parse(iapps::ReadPlatformFileAsString(file
));
951 Send(new ChromeUtilityHostMsg_GotIPhotoLibrary(result
, parser
.library()));
952 ReleaseProcessIfNeeded();
954 #endif // defined(OS_MACOSX)
956 #if defined(OS_WIN) || defined(OS_MACOSX)
957 void ChromeContentUtilityClient::OnParseITunesLibraryXmlFile(
958 const IPC::PlatformFileForTransit
& itunes_library_file
) {
959 itunes::ITunesLibraryParser parser
;
960 base::PlatformFile file
=
961 IPC::PlatformFileForTransitToPlatformFile(itunes_library_file
);
962 bool result
= parser
.Parse(iapps::ReadPlatformFileAsString(file
));
963 Send(new ChromeUtilityHostMsg_GotITunesLibrary(result
, parser
.library()));
964 ReleaseProcessIfNeeded();
967 void ChromeContentUtilityClient::OnParsePicasaPMPDatabase(
968 const picasa::AlbumTableFilesForTransit
& album_table_files
) {
969 picasa::AlbumTableFiles files
;
970 files
.indicator_file
=
971 IPC::PlatformFileForTransitToFile(album_table_files
.indicator_file
);
972 files
.category_file
=
973 IPC::PlatformFileForTransitToFile(album_table_files
.category_file
);
975 IPC::PlatformFileForTransitToFile(album_table_files
.date_file
);
976 files
.filename_file
=
977 IPC::PlatformFileForTransitToFile(album_table_files
.filename_file
);
979 IPC::PlatformFileForTransitToFile(album_table_files
.name_file
);
981 IPC::PlatformFileForTransitToFile(album_table_files
.token_file
);
983 IPC::PlatformFileForTransitToFile(album_table_files
.uid_file
);
985 picasa::PicasaAlbumTableReader
reader(files
.Pass());
986 bool parse_success
= reader
.Init();
987 Send(new ChromeUtilityHostMsg_ParsePicasaPMPDatabase_Finished(
991 ReleaseProcessIfNeeded();
994 void ChromeContentUtilityClient::OnIndexPicasaAlbumsContents(
995 const picasa::AlbumUIDSet
& album_uids
,
996 const std::vector
<picasa::FolderINIContents
>& folders_inis
) {
997 picasa::PicasaAlbumsIndexer
indexer(album_uids
);
998 indexer
.ParseFolderINI(folders_inis
);
1000 Send(new ChromeUtilityHostMsg_IndexPicasaAlbumsContents_Finished(
1001 indexer
.albums_images()));
1002 ReleaseProcessIfNeeded();
1004 #endif // defined(OS_WIN) || defined(OS_MACOSX)
1007 void ChromeContentUtilityClient::OnGetAndEncryptWiFiCredentials(
1008 const std::string
& network_guid
,
1009 const std::vector
<uint8
>& public_key
) {
1010 scoped_ptr
<wifi::WiFiService
> wifi_service(wifi::WiFiService::Create());
1011 wifi_service
->Initialize(NULL
);
1013 std::string key_data
;
1015 wifi_service
->GetKeyFromSystem(network_guid
, &key_data
, &error
);
1017 std::vector
<uint8
> ciphertext
;
1018 bool success
= error
.empty() && !key_data
.empty();
1020 NetworkingPrivateCrypto crypto
;
1021 success
= crypto
.EncryptByteString(public_key
, key_data
, &ciphertext
);
1024 Send(new ChromeUtilityHostMsg_GotEncryptedWiFiCredentials(ciphertext
,
1027 #endif // defined(OS_WIN)
1029 } // namespace chrome