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/command_line.h"
8 #include "base/files/file_path.h"
9 #include "base/json/json_reader.h"
10 #include "base/memory/ref_counted.h"
11 #include "base/time/time.h"
12 #include "chrome/common/chrome_utility_messages.h"
13 #include "chrome/common/safe_browsing/zip_analyzer.h"
14 #include "chrome/utility/chrome_content_utility_ipc_whitelist.h"
15 #include "chrome/utility/utility_message_handler.h"
16 #include "content/public/child/image_decoder_utils.h"
17 #include "content/public/common/content_switches.h"
18 #include "content/public/utility/utility_thread.h"
19 #include "courgette/courgette.h"
20 #include "courgette/third_party/bsdiff.h"
21 #include "ipc/ipc_channel.h"
22 #include "skia/ext/image_operations.h"
23 #include "third_party/skia/include/core/SkBitmap.h"
24 #include "third_party/zlib/google/zip.h"
25 #include "ui/gfx/codec/jpeg_codec.h"
26 #include "ui/gfx/geometry/size.h"
28 #if !defined(OS_ANDROID)
29 #include "chrome/utility/profile_import_handler.h"
33 #include "chrome/utility/font_cache_handler_win.h"
34 #include "chrome/utility/shell_handler_win.h"
37 #if defined(ENABLE_EXTENSIONS)
38 #include "chrome/common/extensions/chrome_utility_extensions_messages.h"
39 #include "chrome/utility/extensions/extensions_handler.h"
40 #include "chrome/utility/image_writer/image_writer_handler.h"
41 #include "chrome/utility/media_galleries/ipc_data_source.h"
42 #include "chrome/utility/media_galleries/media_metadata_parser.h"
45 #if defined(ENABLE_PRINT_PREVIEW) || defined(OS_WIN)
46 #include "chrome/utility/printing_handler.h"
49 #if defined(ENABLE_MDNS)
50 #include "chrome/utility/local_discovery/service_discovery_message_handler.h"
55 bool Send(IPC::Message
* message
) {
56 return content::UtilityThread::Get()->Send(message
);
59 void ReleaseProcessIfNeeded() {
60 content::UtilityThread::Get()->ReleaseProcessIfNeeded();
63 #if defined(ENABLE_EXTENSIONS)
64 void FinishParseMediaMetadata(
65 metadata::MediaMetadataParser
* /* parser */,
66 const extensions::api::media_galleries::MediaMetadata
& metadata
,
67 const std::vector
<metadata::AttachedImage
>& attached_images
) {
68 Send(new ChromeUtilityHostMsg_ParseMediaMetadata_Finished(
69 true, *metadata
.ToValue(), attached_images
));
70 ReleaseProcessIfNeeded();
76 int64_t ChromeContentUtilityClient::max_ipc_message_size_
=
77 IPC::Channel::kMaximumMessageSize
;
79 ChromeContentUtilityClient::ChromeContentUtilityClient()
80 : filter_messages_(false) {
81 #if !defined(OS_ANDROID)
82 handlers_
.push_back(new ProfileImportHandler());
85 #if defined(ENABLE_EXTENSIONS)
86 handlers_
.push_back(new extensions::ExtensionsHandler());
87 handlers_
.push_back(new image_writer::ImageWriterHandler());
90 #if defined(ENABLE_PRINT_PREVIEW) || defined(OS_WIN)
91 handlers_
.push_back(new PrintingHandler());
94 #if defined(ENABLE_MDNS)
95 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
96 switches::kUtilityProcessEnableMDns
)) {
97 handlers_
.push_back(new local_discovery::ServiceDiscoveryMessageHandler());
102 handlers_
.push_back(new ShellHandler());
103 handlers_
.push_back(new FontCacheHandler());
107 ChromeContentUtilityClient::~ChromeContentUtilityClient() {
110 void ChromeContentUtilityClient::UtilityThreadStarted() {
111 #if defined(ENABLE_EXTENSIONS)
112 extensions::UtilityHandler::UtilityThreadStarted();
115 if (kMessageWhitelistSize
> 0) {
116 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
117 if (command_line
->HasSwitch(switches::kUtilityProcessRunningElevated
)) {
118 message_id_whitelist_
.insert(kMessageWhitelist
,
119 kMessageWhitelist
+ kMessageWhitelistSize
);
120 filter_messages_
= true;
125 bool ChromeContentUtilityClient::OnMessageReceived(
126 const IPC::Message
& message
) {
127 if (filter_messages_
&& !ContainsKey(message_id_whitelist_
, message
.type()))
131 IPC_BEGIN_MESSAGE_MAP(ChromeContentUtilityClient
, message
)
132 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_DecodeImage
, OnDecodeImage
)
133 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_RobustJPEGDecodeImage
,
134 OnRobustJPEGDecodeImage
)
135 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseJSON
, OnParseJSON
)
136 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_PatchFileBsdiff
,
138 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_PatchFileCourgette
,
139 OnPatchFileCourgette
)
140 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_StartupPing
, OnStartupPing
)
141 #if defined(FULL_SAFE_BROWSING)
142 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_AnalyzeZipFileForDownloadProtection
,
143 OnAnalyzeZipFileForDownloadProtection
)
145 #if defined(ENABLE_EXTENSIONS)
146 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseMediaMetadata
,
147 OnParseMediaMetadata
)
149 #if defined(OS_CHROMEOS)
150 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_CreateZipFile
, OnCreateZipFile
)
152 IPC_MESSAGE_UNHANDLED(handled
= false)
153 IPC_END_MESSAGE_MAP()
155 for (Handlers::iterator it
= handlers_
.begin();
156 !handled
&& it
!= handlers_
.end(); ++it
) {
157 handled
= (*it
)->OnMessageReceived(message
);
164 void ChromeContentUtilityClient::PreSandboxStartup() {
165 #if defined(ENABLE_EXTENSIONS)
166 extensions::ExtensionsHandler::PreSandboxStartup();
169 #if defined(ENABLE_MDNS)
170 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
171 switches::kUtilityProcessEnableMDns
)) {
172 local_discovery::ServiceDiscoveryMessageHandler::PreSandboxStartup();
174 #endif // ENABLE_MDNS
178 SkBitmap
ChromeContentUtilityClient::DecodeImage(
179 const std::vector
<unsigned char>& encoded_data
, bool shrink_to_fit
) {
180 SkBitmap decoded_image
= content::DecodeImage(&encoded_data
[0],
182 encoded_data
.size());
184 int64_t struct_size
= sizeof(ChromeUtilityHostMsg_DecodeImage_Succeeded
);
185 int64_t image_size
= decoded_image
.computeSize64();
187 while (struct_size
+ (image_size
>> 2*halves
) > max_ipc_message_size_
)
191 // If decoded image is too large for IPC message, shrink it by halves.
192 // This prevents quality loss, and should never overshrink on displays
193 // smaller than 3600x2400.
194 // TODO (Issue 416916): Instead of shrinking, return via shared memory
195 decoded_image
= skia::ImageOperations::Resize(
196 decoded_image
, skia::ImageOperations::RESIZE_LANCZOS3
,
197 decoded_image
.width() >> halves
, decoded_image
.height() >> halves
);
199 // Image too big for IPC message, but caller didn't request resize;
200 // pre-delete image so DecodeImageAndSend() will send an error.
201 decoded_image
.reset();
202 LOG(ERROR
) << "Decoded image too large for IPC message";
206 return decoded_image
;
210 void ChromeContentUtilityClient::DecodeImageAndSend(
211 const std::vector
<unsigned char>& encoded_data
, bool shrink_to_fit
){
212 SkBitmap decoded_image
= DecodeImage(encoded_data
, shrink_to_fit
);
214 if (decoded_image
.empty()) {
215 Send(new ChromeUtilityHostMsg_DecodeImage_Failed());
217 Send(new ChromeUtilityHostMsg_DecodeImage_Succeeded(decoded_image
));
219 ReleaseProcessIfNeeded();
222 void ChromeContentUtilityClient::OnDecodeImage(
223 const std::vector
<unsigned char>& encoded_data
, bool shrink_to_fit
) {
224 DecodeImageAndSend(encoded_data
, shrink_to_fit
);
227 #if defined(OS_CHROMEOS)
228 void ChromeContentUtilityClient::OnCreateZipFile(
229 const base::FilePath
& src_dir
,
230 const std::vector
<base::FilePath
>& src_relative_paths
,
231 const base::FileDescriptor
& dest_fd
) {
232 // dest_fd should be closed in the function. See ipc/ipc_message_util.h for
234 base::ScopedFD
fd_closer(dest_fd
.fd
);
235 bool succeeded
= true;
237 // Check sanity of source relative paths. Reject if path is absolute or
238 // contains any attempt to reference a parent directory ("../" tricks).
239 for (std::vector
<base::FilePath
>::const_iterator iter
=
240 src_relative_paths
.begin(); iter
!= src_relative_paths
.end();
242 if (iter
->IsAbsolute() || iter
->ReferencesParent()) {
249 succeeded
= zip::ZipFiles(src_dir
, src_relative_paths
, dest_fd
.fd
);
252 Send(new ChromeUtilityHostMsg_CreateZipFile_Succeeded());
254 Send(new ChromeUtilityHostMsg_CreateZipFile_Failed());
255 ReleaseProcessIfNeeded();
257 #endif // defined(OS_CHROMEOS)
259 void ChromeContentUtilityClient::OnRobustJPEGDecodeImage(
260 const std::vector
<unsigned char>& encoded_data
) {
261 // Our robust jpeg decoding is using IJG libjpeg.
262 if (gfx::JPEGCodec::JpegLibraryVariant() == gfx::JPEGCodec::IJG_LIBJPEG
&&
263 !encoded_data
.empty()) {
264 scoped_ptr
<SkBitmap
> decoded_image(gfx::JPEGCodec::Decode(
265 &encoded_data
[0], encoded_data
.size()));
266 if (!decoded_image
.get() || decoded_image
->empty()) {
267 Send(new ChromeUtilityHostMsg_DecodeImage_Failed());
269 Send(new ChromeUtilityHostMsg_DecodeImage_Succeeded(*decoded_image
));
272 Send(new ChromeUtilityHostMsg_DecodeImage_Failed());
274 ReleaseProcessIfNeeded();
277 void ChromeContentUtilityClient::OnParseJSON(const std::string
& json
) {
280 base::Value
* value
= base::JSONReader::ReadAndReturnError(
281 json
, base::JSON_PARSE_RFC
, &error_code
, &error
);
283 base::ListValue wrapper
;
284 wrapper
.Append(value
);
285 Send(new ChromeUtilityHostMsg_ParseJSON_Succeeded(wrapper
));
287 Send(new ChromeUtilityHostMsg_ParseJSON_Failed(error
));
289 ReleaseProcessIfNeeded();
292 void ChromeContentUtilityClient::OnPatchFileBsdiff(
293 const base::FilePath
& input_file
,
294 const base::FilePath
& patch_file
,
295 const base::FilePath
& output_file
) {
296 if (input_file
.empty() || patch_file
.empty() || output_file
.empty()) {
297 Send(new ChromeUtilityHostMsg_PatchFile_Finished(-1));
299 const int patch_status
= courgette::ApplyBinaryPatch(input_file
,
302 Send(new ChromeUtilityHostMsg_PatchFile_Finished(patch_status
));
304 ReleaseProcessIfNeeded();
307 void ChromeContentUtilityClient::OnPatchFileCourgette(
308 const base::FilePath
& input_file
,
309 const base::FilePath
& patch_file
,
310 const base::FilePath
& output_file
) {
311 if (input_file
.empty() || patch_file
.empty() || output_file
.empty()) {
312 Send(new ChromeUtilityHostMsg_PatchFile_Finished(-1));
314 const int patch_status
= courgette::ApplyEnsemblePatch(
315 input_file
.value().c_str(),
316 patch_file
.value().c_str(),
317 output_file
.value().c_str());
318 Send(new ChromeUtilityHostMsg_PatchFile_Finished(patch_status
));
320 ReleaseProcessIfNeeded();
323 void ChromeContentUtilityClient::OnStartupPing() {
324 Send(new ChromeUtilityHostMsg_ProcessStarted
);
325 // Don't release the process, we assume further messages are on the way.
328 #if defined(FULL_SAFE_BROWSING)
329 void ChromeContentUtilityClient::OnAnalyzeZipFileForDownloadProtection(
330 const IPC::PlatformFileForTransit
& zip_file
) {
331 safe_browsing::zip_analyzer::Results results
;
332 safe_browsing::zip_analyzer::AnalyzeZipFile(
333 IPC::PlatformFileForTransitToFile(zip_file
), &results
);
334 Send(new ChromeUtilityHostMsg_AnalyzeZipFileForDownloadProtection_Finished(
336 ReleaseProcessIfNeeded();
340 #if defined(ENABLE_EXTENSIONS)
341 // TODO(thestig): Try to move this to
342 // chrome/utility/extensions/extensions_handler.cc.
343 void ChromeContentUtilityClient::OnParseMediaMetadata(
344 const std::string
& mime_type
, int64 total_size
, bool get_attached_images
) {
345 // Only one IPCDataSource may be created and added to the list of handlers.
346 metadata::IPCDataSource
* source
= new metadata::IPCDataSource(total_size
);
347 handlers_
.push_back(source
);
349 metadata::MediaMetadataParser
* parser
= new metadata::MediaMetadataParser(
350 source
, mime_type
, get_attached_images
);
351 parser
->Start(base::Bind(&FinishParseMediaMetadata
, base::Owned(parser
)));