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