1 // Copyright 2014 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 "content/browser/renderer_host/sandbox_ipc_linux.h"
8 #include <fontconfig/fontconfig.h>
10 #include <sys/socket.h>
13 #include "base/command_line.h"
14 #include "base/files/scoped_file.h"
15 #include "base/linux_util.h"
16 #include "base/memory/scoped_vector.h"
17 #include "base/memory/shared_memory.h"
18 #include "base/posix/eintr_wrapper.h"
19 #include "base/posix/unix_domain_socket_linux.h"
20 #include "base/process/launch.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "content/common/font_config_ipc_linux.h"
23 #include "content/common/sandbox_linux/sandbox_linux.h"
24 #include "content/common/set_process_title.h"
25 #include "content/public/common/content_switches.h"
26 #include "ppapi/c/trusted/ppb_browser_font_trusted.h"
27 #include "third_party/WebKit/public/platform/linux/WebFontInfo.h"
28 #include "third_party/WebKit/public/web/WebKit.h"
29 #include "third_party/npapi/bindings/npapi_extensions.h"
30 #include "third_party/skia/include/ports/SkFontConfigInterface.h"
31 #include "ui/gfx/font_render_params_linux.h"
33 using blink::WebCString
;
34 using blink::WebFontInfo
;
35 using blink::WebUChar
;
36 using blink::WebUChar32
;
40 // MSCharSetToFontconfig translates a Microsoft charset identifier to a
41 // fontconfig language set by appending to |langset|.
42 static void MSCharSetToFontconfig(FcLangSet
* langset
, unsigned fdwCharSet
) {
43 // We have need to translate raw fdwCharSet values into terms that
44 // fontconfig can understand. (See the description of fdwCharSet in the MSDN
45 // documentation for CreateFont:
46 // http://msdn.microsoft.com/en-us/library/dd183499(VS.85).aspx )
48 // Although the argument is /called/ 'charset', the actual values conflate
49 // character sets (which are sets of Unicode code points) and character
50 // encodings (which are algorithms for turning a series of bits into a
51 // series of code points.) Sometimes the values will name a language,
52 // sometimes they'll name an encoding. In the latter case I'm assuming that
53 // they mean the set of code points in the domain of that encoding.
55 // fontconfig deals with ISO 639-1 language codes:
56 // http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
58 // So, for each of the documented fdwCharSet values I've had to take a
59 // guess at the set of ISO 639-1 languages intended.
63 // These values I don't really know what to do with, so I'm going to map
64 // them to English also.
65 case NPCharsetDefault
:
69 FcLangSetAdd(langset
, reinterpret_cast<const FcChar8
*>("en"));
72 // The three baltic languages.
73 FcLangSetAdd(langset
, reinterpret_cast<const FcChar8
*>("et"));
74 FcLangSetAdd(langset
, reinterpret_cast<const FcChar8
*>("lv"));
75 FcLangSetAdd(langset
, reinterpret_cast<const FcChar8
*>("lt"));
77 // TODO(jungshik): Would we be better off mapping Big5 to zh-tw
78 // and GB2312 to zh-cn? Fontconfig has 4 separate orthography
79 // files (zh-{cn,tw,hk,mo}.
80 case NPCharsetChineseBIG5
:
82 FcLangSetAdd(langset
, reinterpret_cast<const FcChar8
*>("zh"));
84 case NPCharsetEastEurope
:
85 // A scattering of eastern European languages.
86 FcLangSetAdd(langset
, reinterpret_cast<const FcChar8
*>("pl"));
87 FcLangSetAdd(langset
, reinterpret_cast<const FcChar8
*>("cs"));
88 FcLangSetAdd(langset
, reinterpret_cast<const FcChar8
*>("sk"));
89 FcLangSetAdd(langset
, reinterpret_cast<const FcChar8
*>("hu"));
90 FcLangSetAdd(langset
, reinterpret_cast<const FcChar8
*>("hr"));
93 FcLangSetAdd(langset
, reinterpret_cast<const FcChar8
*>("el"));
98 FcLangSetAdd(langset
, reinterpret_cast<const FcChar8
*>("ko"));
100 case NPCharsetRussian
:
101 FcLangSetAdd(langset
, reinterpret_cast<const FcChar8
*>("ru"));
103 case NPCharsetShiftJIS
:
105 FcLangSetAdd(langset
, reinterpret_cast<const FcChar8
*>("ja"));
107 case NPCharsetTurkish
:
108 FcLangSetAdd(langset
, reinterpret_cast<const FcChar8
*>("tr"));
110 case NPCharsetVietnamese
:
111 FcLangSetAdd(langset
, reinterpret_cast<const FcChar8
*>("vi"));
113 case NPCharsetArabic
:
114 FcLangSetAdd(langset
, reinterpret_cast<const FcChar8
*>("ar"));
116 case NPCharsetHebrew
:
117 FcLangSetAdd(langset
, reinterpret_cast<const FcChar8
*>("he"));
120 FcLangSetAdd(langset
, reinterpret_cast<const FcChar8
*>("th"));
123 // Don't add any languages in that case that we don't recognise the
132 SandboxIPCProcess::SandboxIPCProcess(int lifeline_fd
,
134 std::string sandbox_cmd
)
135 : lifeline_fd_(lifeline_fd
), browser_socket_(browser_socket
) {
136 if (!sandbox_cmd
.empty()) {
137 sandbox_cmd_
.push_back(sandbox_cmd
);
138 sandbox_cmd_
.push_back(base::kFindInodeSwitch
);
141 // FontConfig doesn't provide a standard property to control subpixel
142 // positioning, so we pass the current setting through to WebKit.
143 WebFontInfo::setSubpixelPositioning(
144 gfx::GetDefaultWebkitSubpixelPositioning());
146 CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
147 command_line
.AppendSwitchASCII(switches::kProcessType
,
148 switches::kSandboxIPCProcess
);
150 // Update the process title. The argv was already cached by the call to
151 // SetProcessTitleFromCommandLine in content_main_runner.cc, so we can pass
152 // NULL here (we don't have the original argv at this point).
153 SetProcessTitleFromCommandLine(NULL
);
156 void SandboxIPCProcess::Run() {
157 struct pollfd pfds
[2];
158 pfds
[0].fd
= lifeline_fd_
;
159 pfds
[0].events
= POLLIN
;
160 pfds
[1].fd
= browser_socket_
;
161 pfds
[1].events
= POLLIN
;
163 int failed_polls
= 0;
165 const int r
= HANDLE_EINTR(poll(pfds
, 2, -1 /* no timeout */));
166 // '0' is not a possible return value with no timeout.
169 PLOG(WARNING
) << "poll";
170 if (failed_polls
++ == 3) {
171 LOG(FATAL
) << "poll(2) failing. RenderSandboxHostLinux aborting.";
179 if (pfds
[0].revents
) {
180 // our parent died so we should too.
184 if (pfds
[1].revents
) {
185 HandleRequestFromRenderer(browser_socket_
);
190 void SandboxIPCProcess::HandleRequestFromRenderer(int fd
) {
191 ScopedVector
<base::ScopedFD
> fds
;
193 // A FontConfigIPC::METHOD_MATCH message could be kMaxFontFamilyLength
194 // bytes long (this is the largest message type).
195 // 128 bytes padding are necessary so recvmsg() does not return MSG_TRUNC
196 // error for a maximum length message.
197 char buf
[FontConfigIPC::kMaxFontFamilyLength
+ 128];
199 const ssize_t len
= UnixDomainSocket::RecvMsg(fd
, buf
, sizeof(buf
), &fds
);
201 // TODO: should send an error reply, or the sender might block forever.
202 NOTREACHED() << "Sandbox host message is larger than kMaxFontFamilyLength";
208 Pickle
pickle(buf
, len
);
209 PickleIterator
iter(pickle
);
212 if (!pickle
.ReadInt(&iter
, &kind
))
215 if (kind
== FontConfigIPC::METHOD_MATCH
) {
216 HandleFontMatchRequest(fd
, pickle
, iter
, fds
.get());
217 } else if (kind
== FontConfigIPC::METHOD_OPEN
) {
218 HandleFontOpenRequest(fd
, pickle
, iter
, fds
.get());
219 } else if (kind
== LinuxSandbox::METHOD_GET_FONT_FAMILY_FOR_CHAR
) {
220 HandleGetFontFamilyForChar(fd
, pickle
, iter
, fds
.get());
221 } else if (kind
== LinuxSandbox::METHOD_LOCALTIME
) {
222 HandleLocaltime(fd
, pickle
, iter
, fds
.get());
223 } else if (kind
== LinuxSandbox::METHOD_GET_CHILD_WITH_INODE
) {
224 HandleGetChildWithInode(fd
, pickle
, iter
, fds
.get());
225 } else if (kind
== LinuxSandbox::METHOD_GET_STYLE_FOR_STRIKE
) {
226 HandleGetStyleForStrike(fd
, pickle
, iter
, fds
.get());
227 } else if (kind
== LinuxSandbox::METHOD_MAKE_SHARED_MEMORY_SEGMENT
) {
228 HandleMakeSharedMemorySegment(fd
, pickle
, iter
, fds
.get());
229 } else if (kind
== LinuxSandbox::METHOD_MATCH_WITH_FALLBACK
) {
230 HandleMatchWithFallback(fd
, pickle
, iter
, fds
.get());
234 int SandboxIPCProcess::FindOrAddPath(const SkString
& path
) {
235 int count
= paths_
.count();
236 for (int i
= 0; i
< count
; ++i
) {
237 if (path
== *paths_
[i
])
240 *paths_
.append() = new SkString(path
);
244 void SandboxIPCProcess::HandleFontMatchRequest(
246 const Pickle
& pickle
,
248 const std::vector
<base::ScopedFD
*>& fds
) {
249 uint32_t requested_style
;
251 if (!pickle
.ReadString(&iter
, &family
) ||
252 !pickle
.ReadUInt32(&iter
, &requested_style
))
255 SkFontConfigInterface::FontIdentity result_identity
;
256 SkString result_family
;
257 SkTypeface::Style result_style
;
258 SkFontConfigInterface
* fc
=
259 SkFontConfigInterface::GetSingletonDirectInterface();
261 fc
->matchFamilyName(family
.c_str(),
262 static_cast<SkTypeface::Style
>(requested_style
),
269 reply
.WriteBool(false);
271 // Stash away the returned path, so we can give it an ID (index)
272 // which will later be given to us in a request to open the file.
273 int index
= FindOrAddPath(result_identity
.fString
);
274 result_identity
.fID
= static_cast<uint32_t>(index
);
276 reply
.WriteBool(true);
277 skia::WriteSkString(&reply
, result_family
);
278 skia::WriteSkFontIdentity(&reply
, result_identity
);
279 reply
.WriteUInt32(result_style
);
281 SendRendererReply(fds
, reply
, -1);
284 void SandboxIPCProcess::HandleFontOpenRequest(
286 const Pickle
& pickle
,
288 const std::vector
<base::ScopedFD
*>& fds
) {
290 if (!pickle
.ReadUInt32(&iter
, &index
))
292 if (index
>= static_cast<uint32_t>(paths_
.count()))
294 const int result_fd
= open(paths_
[index
]->c_str(), O_RDONLY
);
297 if (result_fd
== -1) {
298 reply
.WriteBool(false);
300 reply
.WriteBool(true);
303 // The receiver will have its own access to the file, so we will close it
305 SendRendererReply(fds
, reply
, result_fd
);
307 if (result_fd
>= 0) {
308 int err
= IGNORE_EINTR(close(result_fd
));
313 void SandboxIPCProcess::HandleGetFontFamilyForChar(
315 const Pickle
& pickle
,
317 const std::vector
<base::ScopedFD
*>& fds
) {
318 // The other side of this call is
319 // chrome/renderer/renderer_sandbox_support_linux.cc
321 EnsureWebKitInitialized();
323 if (!pickle
.ReadInt(&iter
, &c
))
326 std::string preferred_locale
;
327 if (!pickle
.ReadString(&iter
, &preferred_locale
))
330 blink::WebFontFamily family
;
331 WebFontInfo::familyForChar(c
, preferred_locale
.c_str(), &family
);
334 if (family
.name
.data()) {
335 reply
.WriteString(family
.name
.data());
337 reply
.WriteString(std::string());
339 reply
.WriteBool(family
.isBold
);
340 reply
.WriteBool(family
.isItalic
);
341 SendRendererReply(fds
, reply
, -1);
344 void SandboxIPCProcess::HandleGetStyleForStrike(
346 const Pickle
& pickle
,
348 const std::vector
<base::ScopedFD
*>& fds
) {
352 if (!pickle
.ReadString(&iter
, &family
) ||
353 !pickle
.ReadInt(&iter
, &sizeAndStyle
)) {
357 EnsureWebKitInitialized();
358 blink::WebFontRenderStyle style
;
359 WebFontInfo::renderStyleForStrike(family
.c_str(), sizeAndStyle
, &style
);
362 reply
.WriteInt(style
.useBitmaps
);
363 reply
.WriteInt(style
.useAutoHint
);
364 reply
.WriteInt(style
.useHinting
);
365 reply
.WriteInt(style
.hintStyle
);
366 reply
.WriteInt(style
.useAntiAlias
);
367 reply
.WriteInt(style
.useSubpixelRendering
);
368 reply
.WriteInt(style
.useSubpixelPositioning
);
370 SendRendererReply(fds
, reply
, -1);
373 void SandboxIPCProcess::HandleLocaltime(
375 const Pickle
& pickle
,
377 const std::vector
<base::ScopedFD
*>& fds
) {
378 // The other side of this call is in zygote_main_linux.cc
380 std::string time_string
;
381 if (!pickle
.ReadString(&iter
, &time_string
) ||
382 time_string
.size() != sizeof(time_t)) {
387 memcpy(&time
, time_string
.data(), sizeof(time
));
388 // We use localtime here because we need the tm_zone field to be filled
389 // out. Since we are a single-threaded process, this is safe.
390 const struct tm
* expanded_time
= localtime(&time
);
392 std::string result_string
;
393 const char* time_zone_string
= "";
394 if (expanded_time
!= NULL
) {
395 result_string
= std::string(reinterpret_cast<const char*>(expanded_time
),
397 time_zone_string
= expanded_time
->tm_zone
;
401 reply
.WriteString(result_string
);
402 reply
.WriteString(time_zone_string
);
403 SendRendererReply(fds
, reply
, -1);
406 void SandboxIPCProcess::HandleGetChildWithInode(
408 const Pickle
& pickle
,
410 const std::vector
<base::ScopedFD
*>& fds
) {
411 // The other side of this call is in zygote_main_linux.cc
412 if (sandbox_cmd_
.empty()) {
413 LOG(ERROR
) << "Not in the sandbox, this should not be called";
418 if (!pickle
.ReadUInt64(&iter
, &inode
))
421 base::ProcessId pid
= 0;
422 std::string inode_output
;
424 std::vector
<std::string
> sandbox_cmd
= sandbox_cmd_
;
425 sandbox_cmd
.push_back(base::Int64ToString(inode
));
426 CommandLine
get_inode_cmd(sandbox_cmd
);
427 if (base::GetAppOutput(get_inode_cmd
, &inode_output
))
428 base::StringToInt(inode_output
, &pid
);
431 // Even though the pid is invalid, we still need to reply to the zygote
432 // and not just return here.
433 LOG(ERROR
) << "Could not get pid";
438 SendRendererReply(fds
, reply
, -1);
441 void SandboxIPCProcess::HandleMakeSharedMemorySegment(
443 const Pickle
& pickle
,
445 const std::vector
<base::ScopedFD
*>& fds
) {
446 base::SharedMemoryCreateOptions options
;
448 if (!pickle
.ReadUInt32(&iter
, &size
))
451 if (!pickle
.ReadBool(&iter
, &options
.executable
))
454 base::SharedMemory shm
;
455 if (shm
.Create(options
))
456 shm_fd
= shm
.handle().fd
;
458 SendRendererReply(fds
, reply
, shm_fd
);
461 void SandboxIPCProcess::HandleMatchWithFallback(
463 const Pickle
& pickle
,
465 const std::vector
<base::ScopedFD
*>& fds
) {
466 // Unlike the other calls, for which we are an indirection in front of
467 // WebKit or Skia, this call is always made via this sandbox helper
468 // process. Therefore the fontconfig code goes in here directly.
471 bool is_bold
, is_italic
;
472 uint32 charset
, fallback_family
;
474 if (!pickle
.ReadString(&iter
, &face
) || face
.empty() ||
475 !pickle
.ReadBool(&iter
, &is_bold
) ||
476 !pickle
.ReadBool(&iter
, &is_italic
) ||
477 !pickle
.ReadUInt32(&iter
, &charset
) ||
478 !pickle
.ReadUInt32(&iter
, &fallback_family
)) {
482 FcLangSet
* langset
= FcLangSetCreate();
483 MSCharSetToFontconfig(langset
, charset
);
485 FcPattern
* pattern
= FcPatternCreate();
486 // TODO(agl): FC_FAMILy needs to change
488 pattern
, FC_FAMILY
, reinterpret_cast<const FcChar8
*>(face
.c_str()));
490 std::string generic_font_name
;
491 switch (fallback_family
) {
492 case PP_BROWSERFONT_TRUSTED_FAMILY_SERIF
:
493 generic_font_name
= "Times New Roman";
495 case PP_BROWSERFONT_TRUSTED_FAMILY_SANSSERIF
:
496 generic_font_name
= "Arial";
498 case PP_BROWSERFONT_TRUSTED_FAMILY_MONOSPACE
:
499 generic_font_name
= "Courier New";
502 if (!generic_font_name
.empty()) {
503 const FcChar8
* fc_generic_font_name
=
504 reinterpret_cast<const FcChar8
*>(generic_font_name
.c_str());
505 FcPatternAddString(pattern
, FC_FAMILY
, fc_generic_font_name
);
509 FcPatternAddInteger(pattern
, FC_WEIGHT
, FC_WEIGHT_BOLD
);
511 FcPatternAddInteger(pattern
, FC_SLANT
, FC_SLANT_ITALIC
);
512 FcPatternAddLangSet(pattern
, FC_LANG
, langset
);
513 FcPatternAddBool(pattern
, FC_SCALABLE
, FcTrue
);
514 FcConfigSubstitute(NULL
, pattern
, FcMatchPattern
);
515 FcDefaultSubstitute(pattern
);
518 FcFontSet
* font_set
= FcFontSort(0, pattern
, 0, 0, &result
);
520 int good_enough_index
= -1;
521 bool good_enough_index_set
= false;
524 for (int i
= 0; i
< font_set
->nfont
; ++i
) {
525 FcPattern
* current
= font_set
->fonts
[i
];
527 // Older versions of fontconfig have a bug where they cannot select
528 // only scalable fonts so we have to manually filter the results.
530 if (FcPatternGetBool(current
, FC_SCALABLE
, 0, &is_scalable
) !=
537 if (FcPatternGetString(current
, FC_FILE
, 0, &c_filename
) !=
542 // We only want to return sfnt (TrueType) based fonts. We don't have a
543 // very good way of detecting this so we'll filter based on the
545 bool is_sfnt
= false;
546 static const char kSFNTExtensions
[][5] = {".ttf", ".otc", ".TTF", ".ttc",
548 const size_t filename_len
= strlen(reinterpret_cast<char*>(c_filename
));
549 for (unsigned j
= 0;; j
++) {
550 if (kSFNTExtensions
[j
][0] == 0) {
551 // None of the extensions matched.
554 const size_t ext_len
= strlen(kSFNTExtensions
[j
]);
555 if (filename_len
> ext_len
&&
556 memcmp(c_filename
+ filename_len
- ext_len
,
567 // This font is good enough to pass muster, but we might be able to do
568 // better with subsequent ones.
569 if (!good_enough_index_set
) {
570 good_enough_index
= i
;
571 good_enough_index_set
= true;
575 bool have_matrix
= FcPatternGet(current
, FC_MATRIX
, 0, &matrix
) == 0;
577 if (is_italic
&& have_matrix
) {
578 // we asked for an italic font, but fontconfig is giving us a
579 // non-italic font with a transformation matrix.
584 const bool have_embolden
=
585 FcPatternGet(current
, FC_EMBOLDEN
, 0, &embolden
) == 0;
587 if (is_bold
&& have_embolden
) {
588 // we asked for a bold font, but fontconfig gave us a non-bold font
589 // and asked us to apply fake bolding.
593 font_fd
= open(reinterpret_cast<char*>(c_filename
), O_RDONLY
);
599 if (font_fd
== -1 && good_enough_index_set
) {
600 // We didn't find a font that we liked, so we fallback to something
602 FcPattern
* current
= font_set
->fonts
[good_enough_index
];
604 FcPatternGetString(current
, FC_FILE
, 0, &c_filename
);
605 font_fd
= open(reinterpret_cast<char*>(c_filename
), O_RDONLY
);
609 FcFontSetDestroy(font_set
);
610 FcPatternDestroy(pattern
);
613 SendRendererReply(fds
, reply
, font_fd
);
616 if (IGNORE_EINTR(close(font_fd
)) < 0)
617 PLOG(ERROR
) << "close";
621 void SandboxIPCProcess::SendRendererReply(
622 const std::vector
<base::ScopedFD
*>& fds
,
626 memset(&msg
, 0, sizeof(msg
));
627 struct iovec iov
= {const_cast<void*>(reply
.data()), reply
.size()};
631 char control_buffer
[CMSG_SPACE(sizeof(int))];
633 if (reply_fd
!= -1) {
635 if (fstat(reply_fd
, &st
) == 0 && S_ISDIR(st
.st_mode
)) {
636 LOG(FATAL
) << "Tried to send a directory descriptor over sandbox IPC";
637 // We must never send directory descriptors to a sandboxed process
638 // because they can use openat with ".." elements in the path in order
639 // to escape the sandbox and reach the real filesystem.
642 struct cmsghdr
* cmsg
;
643 msg
.msg_control
= control_buffer
;
644 msg
.msg_controllen
= sizeof(control_buffer
);
645 cmsg
= CMSG_FIRSTHDR(&msg
);
646 cmsg
->cmsg_level
= SOL_SOCKET
;
647 cmsg
->cmsg_type
= SCM_RIGHTS
;
648 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
649 memcpy(CMSG_DATA(cmsg
), &reply_fd
, sizeof(reply_fd
));
650 msg
.msg_controllen
= cmsg
->cmsg_len
;
653 if (HANDLE_EINTR(sendmsg(fds
[0]->get(), &msg
, MSG_DONTWAIT
)) < 0)
654 PLOG(ERROR
) << "sendmsg";
657 SandboxIPCProcess::~SandboxIPCProcess() {
659 if (webkit_platform_support_
)
660 blink::shutdownWithoutV8();
663 void SandboxIPCProcess::EnsureWebKitInitialized() {
664 if (webkit_platform_support_
)
666 webkit_platform_support_
.reset(new BlinkPlatformImpl
);
667 blink::initializeWithoutV8(webkit_platform_support_
.get());
670 } // namespace content