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.
4
5#include "mojo/edk/embedder/platform_channel_pair.h"
6
7#include <fcntl.h>
8#include <stddef.h>
9#include <stdint.h>
10#include <sys/types.h>
11#include <unistd.h>
12
13#include <limits>
14
15#include "base/command_line.h"
16#include "base/logging.h"
17#include "base/posix/global_descriptors.h"
18#include "base/rand_util.h"
19#include "base/strings/string_number_conversions.h"
20#include "build/build_config.h"
21#include "mojo/edk/embedder/platform_handle.h"
22
23#if !defined(OS_NACL_SFI)
24#include <sys/socket.h>
25#else
26#include "native_client/src/public/imc_syscalls.h"
27#endif
28
29#if !defined(SO_PEEK_OFF)
30#define SO_PEEK_OFF 42
31#endif
32
33namespace mojo {
34namespace edk {
35
36namespace {
37
38#if defined(OS_ANDROID)
39enum {
40  // Leave room for any other descriptors defined in content for example.
41  // TODO(jcivelli): consider changing base::GlobalDescriptors to generate a
42  //   key when setting the file descriptor (http://crbug.com/676442).
43  kAndroidClientHandleDescriptor =
44      base::GlobalDescriptors::kBaseDescriptor + 10000,
45};
46#else
47bool IsTargetDescriptorUsed(
48    const base::FileHandleMappingVector& file_handle_mapping,
49    int target_fd) {
50  for (size_t i = 0; i < file_handle_mapping.size(); i++) {
51    if (file_handle_mapping[i].second == target_fd)
52      return true;
53  }
54  return false;
55}
56#endif
57
58}  // namespace
59
60PlatformChannelPair::PlatformChannelPair(bool client_is_blocking) {
61  // Create the Unix domain socket.
62  int fds[2];
63  // TODO(vtl): Maybe fail gracefully if |socketpair()| fails.
64
65#if defined(OS_NACL_SFI)
66  PCHECK(imc_socketpair(fds) == 0);
67#else
68  PCHECK(socketpair(AF_UNIX, SOCK_STREAM, 0, fds) == 0);
69
70  // Set the ends to nonblocking.
71  PCHECK(fcntl(fds[0], F_SETFL, O_NONBLOCK) == 0);
72  if (!client_is_blocking)
73    PCHECK(fcntl(fds[1], F_SETFL, O_NONBLOCK) == 0);
74
75#if defined(OS_MACOSX)
76  // This turns off |SIGPIPE| when writing to a closed socket (causing it to
77  // fail with |EPIPE| instead). On Linux, we have to use |send...()| with
78  // |MSG_NOSIGNAL| -- which is not supported on Mac -- instead.
79  int no_sigpipe = 1;
80  PCHECK(setsockopt(fds[0], SOL_SOCKET, SO_NOSIGPIPE, &no_sigpipe,
81                    sizeof(no_sigpipe)) == 0);
82  PCHECK(setsockopt(fds[1], SOL_SOCKET, SO_NOSIGPIPE, &no_sigpipe,
83                    sizeof(no_sigpipe)) == 0);
84#endif  // defined(OS_MACOSX)
85#endif  // defined(OS_NACL_SFI)
86
87  server_handle_.reset(PlatformHandle(fds[0]));
88  DCHECK(server_handle_.is_valid());
89  client_handle_.reset(PlatformHandle(fds[1]));
90  DCHECK(client_handle_.is_valid());
91}
92
93// static
94ScopedPlatformHandle PlatformChannelPair::PassClientHandleFromParentProcess(
95    const base::CommandLine& command_line) {
96  std::string client_fd_string =
97      command_line.GetSwitchValueASCII(kMojoPlatformChannelHandleSwitch);
98  return PassClientHandleFromParentProcessFromString(client_fd_string);
99}
100
101ScopedPlatformHandle
102PlatformChannelPair::PassClientHandleFromParentProcessFromString(
103    const std::string& value) {
104  int client_fd = -1;
105#if defined(OS_ANDROID)
106  base::GlobalDescriptors::Key key = -1;
107  if (value.empty() || !base::StringToUint(value, &key)) {
108    LOG(ERROR) << "Missing or invalid --" << kMojoPlatformChannelHandleSwitch;
109    return ScopedPlatformHandle();
110  }
111  client_fd = base::GlobalDescriptors::GetInstance()->Get(key);
112#else
113  if (value.empty() ||
114      !base::StringToInt(value, &client_fd) ||
115      client_fd < base::GlobalDescriptors::kBaseDescriptor) {
116    LOG(ERROR) << "Missing or invalid --" << kMojoPlatformChannelHandleSwitch;
117    return ScopedPlatformHandle();
118  }
119#endif
120  return ScopedPlatformHandle(PlatformHandle(client_fd));
121}
122
123void PlatformChannelPair::PrepareToPassClientHandleToChildProcess(
124    base::CommandLine* command_line,
125    base::FileHandleMappingVector* handle_passing_info) const {
126  DCHECK(command_line);
127
128  // Log a warning if the command line already has the switch, but "clobber" it
129  // anyway, since it's reasonably likely that all the switches were just copied
130  // from the parent.
131  LOG_IF(WARNING, command_line->HasSwitch(kMojoPlatformChannelHandleSwitch))
132      << "Child command line already has switch --"
133      << kMojoPlatformChannelHandleSwitch << "="
134      << command_line->GetSwitchValueASCII(kMojoPlatformChannelHandleSwitch);
135  // (Any existing switch won't actually be removed from the command line, but
136  // the last one appended takes precedence.)
137  command_line->AppendSwitchASCII(
138      kMojoPlatformChannelHandleSwitch,
139      PrepareToPassClientHandleToChildProcessAsString(handle_passing_info));
140}
141
142std::string
143PlatformChannelPair::PrepareToPassClientHandleToChildProcessAsString(
144      HandlePassingInformation* handle_passing_info) const {
145#if defined(OS_ANDROID)
146  int fd = client_handle_.get().handle;
147  handle_passing_info->push_back(
148      std::pair<int, int>(fd, kAndroidClientHandleDescriptor));
149  return base::UintToString(kAndroidClientHandleDescriptor);
150#else
151  DCHECK(handle_passing_info);
152  // This is an arbitrary sanity check. (Note that this guarantees that the loop
153  // below will terminate sanely.)
154  CHECK_LT(handle_passing_info->size(), 1000u);
155
156  DCHECK(client_handle_.is_valid());
157
158  // Find a suitable FD to map our client handle to in the child process.
159  // This has quadratic time complexity in the size of |*handle_passing_info|,
160  // but |*handle_passing_info| should be very small (usually/often empty).
161  int target_fd = base::GlobalDescriptors::kBaseDescriptor;
162  while (IsTargetDescriptorUsed(*handle_passing_info, target_fd))
163    target_fd++;
164
165  handle_passing_info->push_back(
166      std::pair<int, int>(client_handle_.get().handle, target_fd));
167  return base::IntToString(target_fd);
168#endif
169}
170
171}  // namespace edk
172}  // namespace mojo
173