summaryrefslogtreecommitdiffstats
path: root/components/arc/arc_bridge_bootstrap.cc
blob: 204bf7c0780e77a945dc3696a06969fe5350dd9b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/arc/arc_bridge_bootstrap.h"

#include <fcntl.h>

#include <utility>

#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/task_runner_util.h"
#include "base/thread_task_runner_handle.h"
#include "base/threading/thread_checker.h"
#include "base/threading/worker_pool.h"
#include "chromeos/dbus/dbus_method_call_status.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/session_manager_client.h"
#include "ipc/unix_domain_socket_util.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "third_party/mojo/src/mojo/edk/embedder/embedder.h"
#include "third_party/mojo/src/mojo/edk/embedder/platform_channel_pair.h"
#include "third_party/mojo/src/mojo/edk/embedder/scoped_platform_handle.h"

namespace arc {

namespace {

const base::FilePath::CharType kArcBridgeSocketPath[] =
    FILE_PATH_LITERAL("/var/run/chrome/arc_bridge.sock");

void OnChannelCreated(mojo::embedder::ChannelInfo* channel) {}

class ArcBridgeBootstrapImpl : public ArcBridgeBootstrap {
 public:
  // The possible states of the bootstrap connection.  In the normal flow,
  // the state changes in the following sequence:
  //
  // STOPPED
  //   Start() ->
  // SOCKET_CREATING
  //   CreateSocket() -> OnSocketCreated() ->
  // STARTING
  //   StartArcInstance() -> OnInstanceStarted() ->
  // STARTED
  //   AcceptInstanceConnection() -> OnInstanceConnected() ->
  // READY
  //
  // When Stop() is called from any state, either because an operation
  // resulted in an error or because the user is logging out:
  //
  // (any)
  //   Stop() ->
  // STOPPING
  //   StopInstance() ->
  // STOPPED
  //
  // When the instance crashes while it was ready, it will be stopped:
  //   READY -> STOPPING -> STOPPED
  // and then restarted:
  //   STOPPED -> SOCKET_CREATING -> ... -> READY).
  enum class State {
    // ARC is not currently running.
    STOPPED,

    // An UNIX socket is being created.
    SOCKET_CREATING,

    // The request to start the instance has been sent.
    STARTING,

    // The instance has started. Waiting for it to connect to the IPC bridge.
    STARTED,

    // The instance has finished booting.
    READY,

    // The request to shut down the instance has been sent.
    STOPPING,
  };

  ArcBridgeBootstrapImpl();
  ~ArcBridgeBootstrapImpl() override;

  // ArcBridgeBootstrap:
  void Start() override;
  void Stop() override;

 private:
  // Creates the UNIX socket on the bootstrap thread and then processes its
  // file descriptor.
  static base::ScopedFD CreateSocket();
  void OnSocketCreated(base::ScopedFD fd);

  // Synchronously accepts a connection on |socket_fd| and then processes the
  // connected socket's file descriptor.
  static base::ScopedFD AcceptInstanceConnection(base::ScopedFD socket_fd);
  void OnInstanceConnected(base::ScopedFD fd);

  void SetState(State state);

  // DBus callbacks.
  void OnInstanceStarted(base::ScopedFD socket_fd, bool success);
  void OnInstanceStopped(bool success);

  // The state of the bootstrap connection.
  State state_ = State::STOPPED;

  base::ThreadChecker thread_checker_;

  // WeakPtrFactory to use callbacks.
  base::WeakPtrFactory<ArcBridgeBootstrapImpl> weak_factory_;

 private:
  DISALLOW_COPY_AND_ASSIGN(ArcBridgeBootstrapImpl);
};

ArcBridgeBootstrapImpl::ArcBridgeBootstrapImpl() : weak_factory_(this) {}

ArcBridgeBootstrapImpl::~ArcBridgeBootstrapImpl() {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(state_ == State::STOPPED);
}

void ArcBridgeBootstrapImpl::Start() {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(delegate_);
  if (state_ != State::STOPPED) {
    VLOG(1) << "Start() called when instance is not stopped";
    return;
  }
  SetState(State::SOCKET_CREATING);
  base::PostTaskAndReplyWithResult(
      base::WorkerPool::GetTaskRunner(true).get(), FROM_HERE,
      base::Bind(&ArcBridgeBootstrapImpl::CreateSocket),
      base::Bind(&ArcBridgeBootstrapImpl::OnSocketCreated,
                 weak_factory_.GetWeakPtr()));
}

// static
base::ScopedFD ArcBridgeBootstrapImpl::CreateSocket() {
  base::FilePath socket_path(kArcBridgeSocketPath);

  int raw_fd = -1;
  if (!IPC::CreateServerUnixDomainSocket(socket_path, &raw_fd)) {
    return base::ScopedFD();
  }
  base::ScopedFD socket_fd(raw_fd);

  // Make socket blocking.
  int flags = HANDLE_EINTR(fcntl(socket_fd.get(), F_GETFL));
  if (flags == -1) {
    PLOG(ERROR) << "fcntl(F_GETFL)";
    return base::ScopedFD();
  }
  if (HANDLE_EINTR(fcntl(socket_fd.get(), F_SETFL, flags & ~O_NONBLOCK)) < 0) {
    PLOG(ERROR) << "fcntl(O_NONBLOCK)";
    return base::ScopedFD();
  }

  // TODO(lhchavez): Tighten the security around the socket by tying it to
  // the user the instance will run as.
  if (!base::SetPosixFilePermissions(socket_path, 0777)) {
    PLOG(ERROR) << "Could not set permissions: " << socket_path.value();
    return base::ScopedFD();
  }

  return socket_fd;
}

void ArcBridgeBootstrapImpl::OnSocketCreated(base::ScopedFD socket_fd) {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (state_ != State::SOCKET_CREATING) {
    VLOG(1) << "Stop() called while connecting";
    return;
  }
  SetState(State::STARTING);

  if (!socket_fd.is_valid()) {
    LOG(ERROR) << "ARC: Error creating socket";
    Stop();
    return;
  }
  chromeos::SessionManagerClient* session_manager_client =
      chromeos::DBusThreadManager::Get()->GetSessionManagerClient();
  session_manager_client->StartArcInstance(
      kArcBridgeSocketPath,
      base::Bind(&ArcBridgeBootstrapImpl::OnInstanceStarted,
                 weak_factory_.GetWeakPtr(), base::Passed(&socket_fd)));
}

void ArcBridgeBootstrapImpl::OnInstanceStarted(base::ScopedFD socket_fd,
                                               bool success) {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (state_ != State::STARTING) {
    VLOG(1) << "Stop() called when ARC is not running";
    return;
  }
  if (!success) {
    LOG(ERROR) << "Failed to start ARC instance";
    // Roll back the state to SOCKET_CREATING to avoid sending the D-Bus signal
    // to stop the failed instance.
    SetState(State::SOCKET_CREATING);
    Stop();
    return;
  }
  SetState(State::STARTED);

  base::PostTaskAndReplyWithResult(
      base::WorkerPool::GetTaskRunner(true).get(), FROM_HERE,
      base::Bind(&ArcBridgeBootstrapImpl::AcceptInstanceConnection,
                 base::Passed(&socket_fd)),
      base::Bind(&ArcBridgeBootstrapImpl::OnInstanceConnected,
                 weak_factory_.GetWeakPtr()));
}

// static
base::ScopedFD ArcBridgeBootstrapImpl::AcceptInstanceConnection(
    base::ScopedFD socket_fd) {
  int raw_fd = -1;
  if (!IPC::ServerAcceptConnection(socket_fd.get(), &raw_fd)) {
    return base::ScopedFD();
  }
  return base::ScopedFD(raw_fd);
}

void ArcBridgeBootstrapImpl::OnInstanceConnected(base::ScopedFD fd) {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (state_ != State::STARTED) {
    VLOG(1) << "Stop() called when ARC is not running";
    return;
  }
  SetState(State::READY);
  mojo::ScopedMessagePipeHandle server_pipe = mojo::embedder::CreateChannel(
      mojo::embedder::ScopedPlatformHandle(
          mojo::embedder::PlatformHandle(fd.release())),
      base::Bind(&OnChannelCreated), base::ThreadTaskRunnerHandle::Get());
  ArcBridgeInstancePtr instance;
  instance.Bind(
      mojo::InterfacePtrInfo<ArcBridgeInstance>(std::move(server_pipe), 0u));
  delegate_->OnConnectionEstablished(std::move(instance));
}

void ArcBridgeBootstrapImpl::Stop() {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (state_ == State::STOPPED || state_ == State::STOPPING) {
    VLOG(1) << "Stop() called when ARC is not running";
    return;
  }
  if (state_ == State::SOCKET_CREATING) {
    // This was stopped before the D-Bus command to start the instance. Skip
    // the D-Bus command to stop it.
    SetState(State::STOPPING);
    OnInstanceStopped(true);
    return;
  }
  SetState(State::STOPPING);
  chromeos::SessionManagerClient* session_manager_client =
      chromeos::DBusThreadManager::Get()->GetSessionManagerClient();
  session_manager_client->StopArcInstance(base::Bind(
      &ArcBridgeBootstrapImpl::OnInstanceStopped, weak_factory_.GetWeakPtr()));
}

void ArcBridgeBootstrapImpl::OnInstanceStopped(bool success) {
  DCHECK(thread_checker_.CalledOnValidThread());
  // STOPPING is the only valid state for this function.
  // DCHECK on enum classes not supported.
  DCHECK(state_ == State::STOPPING);
  DCHECK(delegate_);
  SetState(State::STOPPED);
  delegate_->OnStopped();
}

void ArcBridgeBootstrapImpl::SetState(State state) {
  DCHECK(thread_checker_.CalledOnValidThread());
  // DCHECK on enum classes not supported.
  DCHECK(state_ != state);
  state_ = state;
}

}  // namespace

ArcBridgeBootstrap::ArcBridgeBootstrap() {}
ArcBridgeBootstrap::~ArcBridgeBootstrap() {}

// static
scoped_ptr<ArcBridgeBootstrap> ArcBridgeBootstrap::Create() {
  return make_scoped_ptr(new ArcBridgeBootstrapImpl());
}

}  // namespace arc