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. 4 5 #include "chrome/utility/chrome_content_utility_client.h" 6 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/files/file_path.h" 12 #include "base/json/json_reader.h" 13 #include "base/memory/ref_counted.h" 14 #include "base/memory/scoped_ptr.h" 15 #include "base/path_service.h" 16 #include "base/scoped_native_library.h" 17 #include "base/time/time.h" 18 #include "chrome/common/chrome_paths.h" 19 #include "chrome/common/chrome_utility_messages.h" 20 #include "chrome/common/extensions/chrome_extensions_client.h" 21 #include "chrome/common/extensions/extension_l10n_util.h" 22 #include "chrome/common/extensions/update_manifest.h" 23 #include "chrome/common/safe_browsing/zip_analyzer.h" 24 #include "chrome/utility/cloud_print/bitmap_image.h" 25 #include "chrome/utility/cloud_print/pwg_encoder.h" 26 #include "chrome/utility/extensions/unpacker.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/utility/utility_thread.h" 32 #include "extensions/common/extension.h" 33 #include "extensions/common/manifest.h" 34 #include "media/base/media.h" 35 #include "media/base/media_file_checker.h" 36 #include "printing/page_range.h" 37 #include "printing/pdf_render_settings.h" 38 #include "third_party/skia/include/core/SkBitmap.h" 39 #include "third_party/zlib/google/zip.h" 40 #include "ui/base/ui_base_switches.h" 41 #include "ui/gfx/codec/jpeg_codec.h" 42 #include "ui/gfx/rect.h" 43 #include "ui/gfx/size.h" 44 45 #if defined(OS_WIN) 46 #include "base/win/iat_patch_function.h" 47 #include "base/win/scoped_handle.h" 48 #include "chrome/utility/media_galleries/itunes_pref_parser_win.h" 49 #include "printing/emf_win.h" 50 #include "ui/gfx/gdi_util.h" 51 #endif // defined(OS_WIN) 52 53 #if defined(OS_MACOSX) 54 #include "chrome/utility/media_galleries/iphoto_library_parser.h" 55 #endif // defined(OS_MACOSX) 56 57 #if defined(OS_WIN) || defined(OS_MACOSX) 58 #include "chrome/utility/media_galleries/iapps_xml_utils.h" 59 #include "chrome/utility/media_galleries/itunes_library_parser.h" 60 #include "chrome/utility/media_galleries/picasa_album_table_reader.h" 61 #include "chrome/utility/media_galleries/picasa_albums_indexer.h" 62 #endif // defined(OS_WIN) || defined(OS_MACOSX) 63 64 #if defined(ENABLE_FULL_PRINTING) 65 #include "chrome/common/crash_keys.h" 66 #include "printing/backend/print_backend.h" 67 #endif 68 69 #if defined(ENABLE_MDNS) 70 #include "chrome/utility/local_discovery/service_discovery_message_handler.h" 71 #include "content/public/common/content_switches.h" 72 #endif // ENABLE_MDNS 73 74 namespace chrome { 75 76 namespace { 77 78 bool Send(IPC::Message* message) { 79 return content::UtilityThread::Get()->Send(message); 80 } 81 82 void ReleaseProcessIfNeeded() { 83 content::UtilityThread::Get()->ReleaseProcessIfNeeded(); 84 } 85 86 class PdfFunctionsBase { 87 public: 88 PdfFunctionsBase() : render_pdf_to_bitmap_func_(NULL), 89 get_pdf_doc_info_func_(NULL) {} 90 91 bool Init() { 92 base::FilePath pdf_module_path; 93 if (!PathService::Get(chrome::FILE_PDF_PLUGIN, &pdf_module_path) || 94 !base::PathExists(pdf_module_path)) { 95 return false; 96 } 97 98 pdf_lib_.Reset(base::LoadNativeLibrary(pdf_module_path, NULL)); 99 if (!pdf_lib_.is_valid()) { 100 LOG(WARNING) << "Couldn't load PDF plugin"; 101 return false; 102 } 103 104 render_pdf_to_bitmap_func_ = 105 reinterpret_cast<RenderPDFPageToBitmapProc>( 106 pdf_lib_.GetFunctionPointer("RenderPDFPageToBitmap")); 107 LOG_IF(WARNING, !render_pdf_to_bitmap_func_) << 108 "Missing RenderPDFPageToBitmap"; 109 110 get_pdf_doc_info_func_ = 111 reinterpret_cast<GetPDFDocInfoProc>( 112 pdf_lib_.GetFunctionPointer("GetPDFDocInfo")); 113 LOG_IF(WARNING, !get_pdf_doc_info_func_) << "Missing GetPDFDocInfo"; 114 115 if (!render_pdf_to_bitmap_func_ || !get_pdf_doc_info_func_ || 116 !PlatformInit(pdf_module_path, pdf_lib_)) { 117 Reset(); 118 } 119 120 return IsValid(); 121 } 122 123 bool IsValid() const { 124 return pdf_lib_.is_valid(); 125 } 126 127 void Reset() { 128 pdf_lib_.Reset(NULL); 129 } 130 131 bool RenderPDFPageToBitmap(const void* pdf_buffer, 132 int pdf_buffer_size, 133 int page_number, 134 void* bitmap_buffer, 135 int bitmap_width, 136 int bitmap_height, 137 int dpi_x, 138 int dpi_y, 139 bool autorotate) { 140 if (!render_pdf_to_bitmap_func_) 141 return false; 142 return render_pdf_to_bitmap_func_(pdf_buffer, pdf_buffer_size, page_number, 143 bitmap_buffer, bitmap_width, 144 bitmap_height, dpi_x, dpi_y, autorotate); 145 } 146 147 bool GetPDFDocInfo(const void* pdf_buffer, 148 int buffer_size, 149 int* page_count, 150 double* max_page_width) { 151 if (!get_pdf_doc_info_func_) 152 return false; 153 return get_pdf_doc_info_func_(pdf_buffer, buffer_size, page_count, 154 max_page_width); 155 } 156 157 protected: 158 virtual bool PlatformInit( 159 const base::FilePath& pdf_module_path, 160 const base::ScopedNativeLibrary& pdf_lib) { 161 return true; 162 }; 163 164 private: 165 // Exported by PDF plugin. 166 typedef bool (*RenderPDFPageToBitmapProc)(const void* pdf_buffer, 167 int pdf_buffer_size, 168 int page_number, 169 void* bitmap_buffer, 170 int bitmap_width, 171 int bitmap_height, 172 int dpi_x, 173 int dpi_y, 174 bool autorotate); 175 typedef bool (*GetPDFDocInfoProc)(const void* pdf_buffer, 176 int buffer_size, int* page_count, 177 double* max_page_width); 178 179 RenderPDFPageToBitmapProc render_pdf_to_bitmap_func_; 180 GetPDFDocInfoProc get_pdf_doc_info_func_; 181 182 base::ScopedNativeLibrary pdf_lib_; 183 DISALLOW_COPY_AND_ASSIGN(PdfFunctionsBase); 184 }; 185 186 #if defined(OS_WIN) 187 // The 2 below IAT patch functions are almost identical to the code in 188 // render_process_impl.cc. This is needed to work around specific Windows APIs 189 // used by the Chrome PDF plugin that will fail in the sandbox. 190 static base::win::IATPatchFunction g_iat_patch_createdca; 191 HDC WINAPI UtilityProcess_CreateDCAPatch(LPCSTR driver_name, 192 LPCSTR device_name, 193 LPCSTR output, 194 const DEVMODEA* init_data) { 195 if (driver_name && (std::string("DISPLAY") == driver_name)) { 196 // CreateDC fails behind the sandbox, but not CreateCompatibleDC. 197 return CreateCompatibleDC(NULL); 198 } 199 200 NOTREACHED(); 201 return CreateDCA(driver_name, device_name, output, init_data); 202 } 203 204 static base::win::IATPatchFunction g_iat_patch_get_font_data; 205 DWORD WINAPI UtilityProcess_GetFontDataPatch( 206 HDC hdc, DWORD table, DWORD offset, LPVOID buffer, DWORD length) { 207 int rv = GetFontData(hdc, table, offset, buffer, length); 208 if (rv == GDI_ERROR && hdc) { 209 HFONT font = static_cast<HFONT>(GetCurrentObject(hdc, OBJ_FONT)); 210 211 LOGFONT logfont; 212 if (GetObject(font, sizeof(LOGFONT), &logfont)) { 213 content::UtilityThread::Get()->PreCacheFont(logfont); 214 rv = GetFontData(hdc, table, offset, buffer, length); 215 content::UtilityThread::Get()->ReleaseCachedFonts(); 216 } 217 } 218 return rv; 219 } 220 221 class PdfFunctionsWin : public PdfFunctionsBase { 222 public: 223 PdfFunctionsWin() : render_pdf_to_dc_func_(NULL) { 224 } 225 226 bool PlatformInit( 227 const base::FilePath& pdf_module_path, 228 const base::ScopedNativeLibrary& pdf_lib) OVERRIDE { 229 // Patch the IAT for handling specific APIs known to fail in the sandbox. 230 if (!g_iat_patch_createdca.is_patched()) { 231 g_iat_patch_createdca.Patch(pdf_module_path.value().c_str(), 232 "gdi32.dll", "CreateDCA", 233 UtilityProcess_CreateDCAPatch); 234 } 235 236 if (!g_iat_patch_get_font_data.is_patched()) { 237 g_iat_patch_get_font_data.Patch(pdf_module_path.value().c_str(), 238 "gdi32.dll", "GetFontData", 239 UtilityProcess_GetFontDataPatch); 240 } 241 render_pdf_to_dc_func_ = 242 reinterpret_cast<RenderPDFPageToDCProc>( 243 pdf_lib.GetFunctionPointer("RenderPDFPageToDC")); 244 LOG_IF(WARNING, !render_pdf_to_dc_func_) << "Missing RenderPDFPageToDC"; 245 246 return render_pdf_to_dc_func_ != NULL; 247 } 248 249 bool RenderPDFPageToDC(const void* pdf_buffer, 250 int buffer_size, 251 int page_number, 252 HDC dc, 253 int dpi_x, 254 int dpi_y, 255 int bounds_origin_x, 256 int bounds_origin_y, 257 int bounds_width, 258 int bounds_height, 259 bool fit_to_bounds, 260 bool stretch_to_bounds, 261 bool keep_aspect_ratio, 262 bool center_in_bounds, 263 bool autorotate) { 264 if (!render_pdf_to_dc_func_) 265 return false; 266 return render_pdf_to_dc_func_(pdf_buffer, buffer_size, page_number, 267 dc, dpi_x, dpi_y, bounds_origin_x, 268 bounds_origin_y, bounds_width, bounds_height, 269 fit_to_bounds, stretch_to_bounds, 270 keep_aspect_ratio, center_in_bounds, 271 autorotate); 272 } 273 274 private: 275 // Exported by PDF plugin. 276 typedef bool (*RenderPDFPageToDCProc)( 277 const void* pdf_buffer, int buffer_size, int page_number, HDC dc, 278 int dpi_x, int dpi_y, int bounds_origin_x, int bounds_origin_y, 279 int bounds_width, int bounds_height, bool fit_to_bounds, 280 bool stretch_to_bounds, bool keep_aspect_ratio, bool center_in_bounds, 281 bool autorotate); 282 RenderPDFPageToDCProc render_pdf_to_dc_func_; 283 284 DISALLOW_COPY_AND_ASSIGN(PdfFunctionsWin); 285 }; 286 287 typedef PdfFunctionsWin PdfFunctions; 288 #else // OS_WIN 289 typedef PdfFunctionsBase PdfFunctions; 290 #endif // OS_WIN 291 292 static base::LazyInstance<PdfFunctions> g_pdf_lib = LAZY_INSTANCE_INITIALIZER; 293 294 } // namespace 295 296 ChromeContentUtilityClient::ChromeContentUtilityClient() { 297 #if !defined(OS_ANDROID) 298 handlers_.push_back(new ProfileImportHandler()); 299 #endif // OS_ANDROID 300 301 #if defined(ENABLE_MDNS) 302 if (CommandLine::ForCurrentProcess()->HasSwitch( 303 switches::kUtilityProcessEnableMDns)) { 304 handlers_.push_back(new local_discovery::ServiceDiscoveryMessageHandler()); 305 } 306 #endif // ENABLE_MDNS 307 } 308 309 ChromeContentUtilityClient::~ChromeContentUtilityClient() { 310 } 311 312 void ChromeContentUtilityClient::UtilityThreadStarted() { 313 CommandLine* command_line = CommandLine::ForCurrentProcess(); 314 std::string lang = command_line->GetSwitchValueASCII(switches::kLang); 315 if (!lang.empty()) 316 extension_l10n_util::SetProcessLocale(lang); 317 } 318 319 bool ChromeContentUtilityClient::OnMessageReceived( 320 const IPC::Message& message) { 321 bool handled = true; 322 IPC_BEGIN_MESSAGE_MAP(ChromeContentUtilityClient, message) 323 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_UnpackExtension, OnUnpackExtension) 324 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_UnpackWebResource, 325 OnUnpackWebResource) 326 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseUpdateManifest, 327 OnParseUpdateManifest) 328 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_DecodeImage, OnDecodeImage) 329 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_DecodeImageBase64, OnDecodeImageBase64) 330 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_RenderPDFPagesToMetafile, 331 OnRenderPDFPagesToMetafile) 332 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_RenderPDFPagesToPWGRaster, 333 OnRenderPDFPagesToPWGRaster) 334 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_RobustJPEGDecodeImage, 335 OnRobustJPEGDecodeImage) 336 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseJSON, OnParseJSON) 337 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_GetPrinterCapsAndDefaults, 338 OnGetPrinterCapsAndDefaults) 339 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_StartupPing, OnStartupPing) 340 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_AnalyzeZipFileForDownloadProtection, 341 OnAnalyzeZipFileForDownloadProtection) 342 343 #if !defined(OS_ANDROID) && !defined(OS_IOS) 344 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_CheckMediaFile, OnCheckMediaFile) 345 #endif // !defined(OS_ANDROID) && !defined(OS_IOS) 346 347 #if defined(OS_CHROMEOS) 348 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_CreateZipFile, OnCreateZipFile) 349 #endif // defined(OS_CHROMEOS) 350 351 #if defined(OS_WIN) 352 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseITunesPrefXml, 353 OnParseITunesPrefXml) 354 #endif // defined(OS_WIN) 355 356 #if defined(OS_MACOSX) 357 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseIPhotoLibraryXmlFile, 358 OnParseIPhotoLibraryXmlFile) 359 #endif // defined(OS_MACOSX) 360 361 #if defined(OS_WIN) || defined(OS_MACOSX) 362 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseITunesLibraryXmlFile, 363 OnParseITunesLibraryXmlFile) 364 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParsePicasaPMPDatabase, 365 OnParsePicasaPMPDatabase) 366 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_IndexPicasaAlbumsContents, 367 OnIndexPicasaAlbumsContents) 368 #endif // defined(OS_WIN) || defined(OS_MACOSX) 369 370 IPC_MESSAGE_UNHANDLED(handled = false) 371 IPC_END_MESSAGE_MAP() 372 373 for (Handlers::iterator it = handlers_.begin(); 374 !handled && it != handlers_.end(); ++it) { 375 handled = (*it)->OnMessageReceived(message); 376 } 377 378 return handled; 379 } 380 381 // static 382 void ChromeContentUtilityClient::PreSandboxStartup() { 383 #if defined(ENABLE_MDNS) 384 local_discovery::ServiceDiscoveryMessageHandler::PreSandboxStartup(); 385 #endif // ENABLE_MDNS 386 387 g_pdf_lib.Get().Init(); 388 389 // Load media libraries for media file validation. 390 base::FilePath media_path; 391 PathService::Get(content::DIR_MEDIA_LIBS, &media_path); 392 if (!media_path.empty()) 393 media::InitializeMediaLibrary(media_path); 394 } 395 396 void ChromeContentUtilityClient::OnUnpackExtension( 397 const base::FilePath& extension_path, 398 const std::string& extension_id, 399 int location, 400 int creation_flags) { 401 CHECK_GT(location, extensions::Manifest::INVALID_LOCATION); 402 CHECK_LT(location, extensions::Manifest::NUM_LOCATIONS); 403 extensions::ExtensionsClient::Set( 404 extensions::ChromeExtensionsClient::GetInstance()); 405 extensions::Unpacker unpacker( 406 extension_path, 407 extension_id, 408 static_cast<extensions::Manifest::Location>(location), 409 creation_flags); 410 if (unpacker.Run() && unpacker.DumpImagesToFile() && 411 unpacker.DumpMessageCatalogsToFile()) { 412 Send(new ChromeUtilityHostMsg_UnpackExtension_Succeeded( 413 *unpacker.parsed_manifest())); 414 } else { 415 Send(new ChromeUtilityHostMsg_UnpackExtension_Failed( 416 unpacker.error_message())); 417 } 418 419 ReleaseProcessIfNeeded(); 420 } 421 422 void ChromeContentUtilityClient::OnUnpackWebResource( 423 const std::string& resource_data) { 424 // Parse json data. 425 // TODO(mrc): Add the possibility of a template that controls parsing, and 426 // the ability to download and verify images. 427 WebResourceUnpacker unpacker(resource_data); 428 if (unpacker.Run()) { 429 Send(new ChromeUtilityHostMsg_UnpackWebResource_Succeeded( 430 *unpacker.parsed_json())); 431 } else { 432 Send(new ChromeUtilityHostMsg_UnpackWebResource_Failed( 433 unpacker.error_message())); 434 } 435 436 ReleaseProcessIfNeeded(); 437 } 438 439 void ChromeContentUtilityClient::OnParseUpdateManifest(const std::string& xml) { 440 UpdateManifest manifest; 441 if (!manifest.Parse(xml)) { 442 Send(new ChromeUtilityHostMsg_ParseUpdateManifest_Failed( 443 manifest.errors())); 444 } else { 445 Send(new ChromeUtilityHostMsg_ParseUpdateManifest_Succeeded( 446 manifest.results())); 447 } 448 ReleaseProcessIfNeeded(); 449 } 450 451 void ChromeContentUtilityClient::OnDecodeImage( 452 const std::vector<unsigned char>& encoded_data) { 453 const SkBitmap& decoded_image = content::DecodeImage(&encoded_data[0], 454 gfx::Size(), 455 encoded_data.size()); 456 if (decoded_image.empty()) { 457 Send(new ChromeUtilityHostMsg_DecodeImage_Failed()); 458 } else { 459 Send(new ChromeUtilityHostMsg_DecodeImage_Succeeded(decoded_image)); 460 } 461 ReleaseProcessIfNeeded(); 462 } 463 464 void ChromeContentUtilityClient::OnDecodeImageBase64( 465 const std::string& encoded_string) { 466 std::string decoded_string; 467 468 if (!base::Base64Decode(encoded_string, &decoded_string)) { 469 Send(new ChromeUtilityHostMsg_DecodeImage_Failed()); 470 return; 471 } 472 473 std::vector<unsigned char> decoded_vector(decoded_string.size()); 474 for (size_t i = 0; i < decoded_string.size(); ++i) { 475 decoded_vector[i] = static_cast<unsigned char>(decoded_string[i]); 476 } 477 478 OnDecodeImage(decoded_vector); 479 } 480 481 #if defined(OS_CHROMEOS) 482 void ChromeContentUtilityClient::OnCreateZipFile( 483 const base::FilePath& src_dir, 484 const std::vector<base::FilePath>& src_relative_paths, 485 const base::FileDescriptor& dest_fd) { 486 bool succeeded = true; 487 488 // Check sanity of source relative paths. Reject if path is absolute or 489 // contains any attempt to reference a parent directory ("../" tricks). 490 for (std::vector<base::FilePath>::const_iterator iter = 491 src_relative_paths.begin(); iter != src_relative_paths.end(); 492 ++iter) { 493 if (iter->IsAbsolute() || iter->ReferencesParent()) { 494 succeeded = false; 495 break; 496 } 497 } 498 499 if (succeeded) 500 succeeded = zip::ZipFiles(src_dir, src_relative_paths, dest_fd.fd); 501 502 if (succeeded) 503 Send(new ChromeUtilityHostMsg_CreateZipFile_Succeeded()); 504 else 505 Send(new ChromeUtilityHostMsg_CreateZipFile_Failed()); 506 ReleaseProcessIfNeeded(); 507 } 508 #endif // defined(OS_CHROMEOS) 509 510 void ChromeContentUtilityClient::OnRenderPDFPagesToMetafile( 511 base::PlatformFile pdf_file, 512 const base::FilePath& metafile_path, 513 const printing::PdfRenderSettings& settings, 514 const std::vector<printing::PageRange>& page_ranges) { 515 bool succeeded = false; 516 #if defined(OS_WIN) 517 int highest_rendered_page_number = 0; 518 double scale_factor = 1.0; 519 succeeded = RenderPDFToWinMetafile(pdf_file, 520 metafile_path, 521 settings, 522 page_ranges, 523 &highest_rendered_page_number, 524 &scale_factor); 525 if (succeeded) { 526 Send(new ChromeUtilityHostMsg_RenderPDFPagesToMetafile_Succeeded( 527 highest_rendered_page_number, scale_factor)); 528 } 529 #endif // defined(OS_WIN) 530 if (!succeeded) { 531 Send(new ChromeUtilityHostMsg_RenderPDFPagesToMetafile_Failed()); 532 } 533 ReleaseProcessIfNeeded(); 534 } 535 536 void ChromeContentUtilityClient::OnRenderPDFPagesToPWGRaster( 537 IPC::PlatformFileForTransit pdf_transit, 538 const printing::PdfRenderSettings& settings, 539 IPC::PlatformFileForTransit bitmap_transit) { 540 base::PlatformFile pdf = 541 IPC::PlatformFileForTransitToPlatformFile(pdf_transit); 542 base::PlatformFile bitmap = 543 IPC::PlatformFileForTransitToPlatformFile(bitmap_transit); 544 if (RenderPDFPagesToPWGRaster(pdf, settings, bitmap)) { 545 Send(new ChromeUtilityHostMsg_RenderPDFPagesToPWGRaster_Succeeded()); 546 } else { 547 Send(new ChromeUtilityHostMsg_RenderPDFPagesToPWGRaster_Failed()); 548 } 549 ReleaseProcessIfNeeded(); 550 } 551 552 #if defined(OS_WIN) 553 bool ChromeContentUtilityClient::RenderPDFToWinMetafile( 554 base::PlatformFile pdf_file, 555 const base::FilePath& metafile_path, 556 const printing::PdfRenderSettings& settings, 557 const std::vector<printing::PageRange>& page_ranges, 558 int* highest_rendered_page_number, 559 double* scale_factor) { 560 *highest_rendered_page_number = -1; 561 *scale_factor = 1.0; 562 base::win::ScopedHandle file(pdf_file); 563 564 if (!g_pdf_lib.Get().IsValid()) 565 return false; 566 567 // TODO(sanjeevr): Add a method to the PDF DLL that takes in a file handle 568 // and a page range array. That way we don't need to read the entire PDF into 569 // memory. 570 DWORD length = ::GetFileSize(file, NULL); 571 if (length == INVALID_FILE_SIZE) 572 return false; 573 574 std::vector<uint8> buffer; 575 buffer.resize(length); 576 DWORD bytes_read = 0; 577 if (!ReadFile(pdf_file, &buffer.front(), length, &bytes_read, NULL) || 578 (bytes_read != length)) { 579 return false; 580 } 581 582 int total_page_count = 0; 583 if (!g_pdf_lib.Get().GetPDFDocInfo(&buffer.front(), buffer.size(), 584 &total_page_count, NULL)) { 585 return false; 586 } 587 588 printing::Emf metafile; 589 metafile.InitToFile(metafile_path); 590 // We need to scale down DC to fit an entire page into DC available area. 591 // Current metafile is based on screen DC and have current screen size. 592 // Writing outside of those boundaries will result in the cut-off output. 593 // On metafiles (this is the case here), scaling down will still record 594 // original coordinates and we'll be able to print in full resolution. 595 // Before playback we'll need to counter the scaling up that will happen 596 // in the service (print_system_win.cc). 597 *scale_factor = gfx::CalculatePageScale(metafile.context(), 598 settings.area().right(), 599 settings.area().bottom()); 600 gfx::ScaleDC(metafile.context(), *scale_factor); 601 602 bool ret = false; 603 std::vector<printing::PageRange>::const_iterator iter; 604 for (iter = page_ranges.begin(); iter != page_ranges.end(); ++iter) { 605 for (int page_number = iter->from; page_number <= iter->to; ++page_number) { 606 if (page_number >= total_page_count) 607 break; 608 // The underlying metafile is of type Emf and ignores the arguments passed 609 // to StartPage. 610 metafile.StartPage(gfx::Size(), gfx::Rect(), 1); 611 if (g_pdf_lib.Get().RenderPDFPageToDC( 612 &buffer.front(), buffer.size(), page_number, metafile.context(), 613 settings.dpi(), settings.dpi(), settings.area().x(), 614 settings.area().y(), settings.area().width(), 615 settings.area().height(), true, false, true, true, 616 settings.autorotate())) { 617 if (*highest_rendered_page_number < page_number) 618 *highest_rendered_page_number = page_number; 619 ret = true; 620 } 621 metafile.FinishPage(); 622 } 623 } 624 metafile.FinishDocument(); 625 return ret; 626 } 627 #endif // defined(OS_WIN) 628 629 bool ChromeContentUtilityClient::RenderPDFPagesToPWGRaster( 630 base::PlatformFile pdf_file, 631 const printing::PdfRenderSettings& settings, 632 base::PlatformFile bitmap_file) { 633 bool autoupdate = true; 634 if (!g_pdf_lib.Get().IsValid()) 635 return false; 636 637 base::PlatformFileInfo info; 638 if (!base::GetPlatformFileInfo(pdf_file, &info) || info.size <= 0) 639 return false; 640 641 std::string data(info.size, 0); 642 int data_size = base::ReadPlatformFile(pdf_file, 0, &data[0], data.size()); 643 if (data_size != static_cast<int>(data.size())) 644 return false; 645 646 int total_page_count = 0; 647 if (!g_pdf_lib.Get().GetPDFDocInfo(data.data(), data.size(), 648 &total_page_count, NULL)) { 649 return false; 650 } 651 652 cloud_print::PwgEncoder encoder; 653 std::string pwg_header; 654 encoder.EncodeDocumentHeader(&pwg_header); 655 int bytes_written = base::WritePlatformFileAtCurrentPos(bitmap_file, 656 pwg_header.data(), 657 pwg_header.size()); 658 if (bytes_written != static_cast<int>(pwg_header.size())) 659 return false; 660 661 cloud_print::BitmapImage image(settings.area().size(), 662 cloud_print::BitmapImage::BGRA); 663 for (int i = 0; i < total_page_count; ++i) { 664 if (!g_pdf_lib.Get().RenderPDFPageToBitmap( 665 data.data(), data.size(), i, image.pixel_data(), 666 image.size().width(), image.size().height(), settings.dpi(), 667 settings.dpi(), autoupdate)) { 668 return false; 669 } 670 std::string pwg_page; 671 if (!encoder.EncodePage(image, settings.dpi(), total_page_count, &pwg_page)) 672 return false; 673 bytes_written = base::WritePlatformFileAtCurrentPos(bitmap_file, 674 pwg_page.data(), 675 pwg_page.size()); 676 if (bytes_written != static_cast<int>(pwg_page.size())) 677 return false; 678 } 679 return true; 680 } 681 682 void ChromeContentUtilityClient::OnRobustJPEGDecodeImage( 683 const std::vector<unsigned char>& encoded_data) { 684 // Our robust jpeg decoding is using IJG libjpeg. 685 if (gfx::JPEGCodec::JpegLibraryVariant() == gfx::JPEGCodec::IJG_LIBJPEG) { 686 scoped_ptr<SkBitmap> decoded_image(gfx::JPEGCodec::Decode( 687 &encoded_data[0], encoded_data.size())); 688 if (!decoded_image.get() || decoded_image->empty()) { 689 Send(new ChromeUtilityHostMsg_DecodeImage_Failed()); 690 } else { 691 Send(new ChromeUtilityHostMsg_DecodeImage_Succeeded(*decoded_image)); 692 } 693 } else { 694 Send(new ChromeUtilityHostMsg_DecodeImage_Failed()); 695 } 696 ReleaseProcessIfNeeded(); 697 } 698 699 void ChromeContentUtilityClient::OnParseJSON(const std::string& json) { 700 int error_code; 701 std::string error; 702 base::Value* value = base::JSONReader::ReadAndReturnError( 703 json, base::JSON_PARSE_RFC, &error_code, &error); 704 if (value) { 705 base::ListValue wrapper; 706 wrapper.Append(value); 707 Send(new ChromeUtilityHostMsg_ParseJSON_Succeeded(wrapper)); 708 } else { 709 Send(new ChromeUtilityHostMsg_ParseJSON_Failed(error)); 710 } 711 ReleaseProcessIfNeeded(); 712 } 713 714 void ChromeContentUtilityClient::OnGetPrinterCapsAndDefaults( 715 const std::string& printer_name) { 716 #if defined(ENABLE_FULL_PRINTING) 717 scoped_refptr<printing::PrintBackend> print_backend = 718 printing::PrintBackend::CreateInstance(NULL); 719 printing::PrinterCapsAndDefaults printer_info; 720 721 crash_keys::ScopedPrinterInfo crash_key( 722 print_backend->GetPrinterDriverInfo(printer_name)); 723 724 if (print_backend->GetPrinterCapsAndDefaults(printer_name, &printer_info)) { 725 Send(new ChromeUtilityHostMsg_GetPrinterCapsAndDefaults_Succeeded( 726 printer_name, printer_info)); 727 } else // NOLINT 728 #endif 729 { 730 Send(new ChromeUtilityHostMsg_GetPrinterCapsAndDefaults_Failed( 731 printer_name)); 732 } 733 ReleaseProcessIfNeeded(); 734 } 735 736 void ChromeContentUtilityClient::OnStartupPing() { 737 Send(new ChromeUtilityHostMsg_ProcessStarted); 738 // Don't release the process, we assume further messages are on the way. 739 } 740 741 void ChromeContentUtilityClient::OnAnalyzeZipFileForDownloadProtection( 742 const IPC::PlatformFileForTransit& zip_file) { 743 safe_browsing::zip_analyzer::Results results; 744 safe_browsing::zip_analyzer::AnalyzeZipFile( 745 IPC::PlatformFileForTransitToPlatformFile(zip_file), &results); 746 Send(new ChromeUtilityHostMsg_AnalyzeZipFileForDownloadProtection_Finished( 747 results)); 748 ReleaseProcessIfNeeded(); 749 } 750 751 #if !defined(OS_ANDROID) && !defined(OS_IOS) 752 void ChromeContentUtilityClient::OnCheckMediaFile( 753 int64 milliseconds_of_decoding, 754 const IPC::PlatformFileForTransit& media_file) { 755 media::MediaFileChecker 756 checker(IPC::PlatformFileForTransitToPlatformFile(media_file)); 757 const bool check_success = checker.Start( 758 base::TimeDelta::FromMilliseconds(milliseconds_of_decoding)); 759 Send(new ChromeUtilityHostMsg_CheckMediaFile_Finished(check_success)); 760 ReleaseProcessIfNeeded(); 761 } 762 #endif // !defined(OS_ANDROID) && !defined(OS_IOS) 763 764 #if defined(OS_WIN) 765 void ChromeContentUtilityClient::OnParseITunesPrefXml( 766 const std::string& itunes_xml_data) { 767 base::FilePath library_path( 768 itunes::FindLibraryLocationInPrefXml(itunes_xml_data)); 769 Send(new ChromeUtilityHostMsg_GotITunesDirectory(library_path)); 770 ReleaseProcessIfNeeded(); 771 } 772 #endif // defined(OS_WIN) 773 774 #if defined(OS_MACOSX) 775 void ChromeContentUtilityClient::OnParseIPhotoLibraryXmlFile( 776 const IPC::PlatformFileForTransit& iphoto_library_file) { 777 iphoto::IPhotoLibraryParser parser; 778 base::PlatformFile file = 779 IPC::PlatformFileForTransitToPlatformFile(iphoto_library_file); 780 bool result = parser.Parse(iapps::ReadPlatformFileAsString(file)); 781 Send(new ChromeUtilityHostMsg_GotIPhotoLibrary(result, parser.library())); 782 ReleaseProcessIfNeeded(); 783 } 784 #endif // defined(OS_MACOSX) 785 786 #if defined(OS_WIN) || defined(OS_MACOSX) 787 void ChromeContentUtilityClient::OnParseITunesLibraryXmlFile( 788 const IPC::PlatformFileForTransit& itunes_library_file) { 789 itunes::ITunesLibraryParser parser; 790 base::PlatformFile file = 791 IPC::PlatformFileForTransitToPlatformFile(itunes_library_file); 792 bool result = parser.Parse(iapps::ReadPlatformFileAsString(file)); 793 Send(new ChromeUtilityHostMsg_GotITunesLibrary(result, parser.library())); 794 ReleaseProcessIfNeeded(); 795 } 796 797 void ChromeContentUtilityClient::OnParsePicasaPMPDatabase( 798 const picasa::AlbumTableFilesForTransit& album_table_files) { 799 picasa::AlbumTableFiles files; 800 files.indicator_file = IPC::PlatformFileForTransitToPlatformFile( 801 album_table_files.indicator_file); 802 files.category_file = IPC::PlatformFileForTransitToPlatformFile( 803 album_table_files.category_file); 804 files.date_file = IPC::PlatformFileForTransitToPlatformFile( 805 album_table_files.date_file); 806 files.filename_file = IPC::PlatformFileForTransitToPlatformFile( 807 album_table_files.filename_file); 808 files.name_file = IPC::PlatformFileForTransitToPlatformFile( 809 album_table_files.name_file); 810 files.token_file = IPC::PlatformFileForTransitToPlatformFile( 811 album_table_files.token_file); 812 files.uid_file = IPC::PlatformFileForTransitToPlatformFile( 813 album_table_files.uid_file); 814 815 picasa::PicasaAlbumTableReader reader(files); 816 bool parse_success = reader.Init(); 817 Send(new ChromeUtilityHostMsg_ParsePicasaPMPDatabase_Finished( 818 parse_success, 819 reader.albums(), 820 reader.folders())); 821 ReleaseProcessIfNeeded(); 822 } 823 824 void ChromeContentUtilityClient::OnIndexPicasaAlbumsContents( 825 const picasa::AlbumUIDSet& album_uids, 826 const std::vector<picasa::FolderINIContents>& folders_inis) { 827 picasa::PicasaAlbumsIndexer indexer(album_uids); 828 indexer.ParseFolderINI(folders_inis); 829 830 Send(new ChromeUtilityHostMsg_IndexPicasaAlbumsContents_Finished( 831 indexer.albums_images())); 832 ReleaseProcessIfNeeded(); 833 } 834 #endif // defined(OS_WIN) || defined(OS_MACOSX) 835 836 } // namespace chrome 837