1//
2// Copyright (C) 2015 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//      http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
16
17#include "shill/dbus/chromeos_permission_broker_proxy.h"
18
19#include <string>
20#include <vector>
21
22#include "shill/logging.h"
23
24namespace shill {
25
26// static
27const int ChromeosPermissionBrokerProxy::kInvalidHandle = -1;
28
29ChromeosPermissionBrokerProxy::ChromeosPermissionBrokerProxy(
30    const scoped_refptr<dbus::Bus>& bus)
31    : proxy_(new org::chromium::PermissionBrokerProxy(bus)),
32      lifeline_read_fd_(kInvalidHandle),
33      lifeline_write_fd_(kInvalidHandle) {
34  // TODO(zqiu): register handler for service name owner changes, to
35  // automatically re-request VPN setup when permission broker is restarted.
36}
37
38ChromeosPermissionBrokerProxy::~ChromeosPermissionBrokerProxy() {}
39
40bool ChromeosPermissionBrokerProxy::RequestVpnSetup(
41    const std::vector<std::string>& user_names,
42    const std::string& interface) {
43  if (lifeline_read_fd_ != kInvalidHandle ||
44      lifeline_write_fd_ != kInvalidHandle) {
45    LOG(ERROR) << "Already setup?";
46    return false;
47  }
48
49  // TODO(zqiu): move pipe creation/cleanup to the constructor and destructor.
50  // No need to recreate pipe for each request.
51  int fds[2];
52  if (pipe(fds) != 0) {
53    LOG(ERROR) << "Failed to create lifeline pipe";
54    return false;
55  }
56  lifeline_read_fd_ = fds[0];
57  lifeline_write_fd_ = fds[1];
58
59  dbus::FileDescriptor dbus_fd(lifeline_read_fd_);
60  dbus_fd.CheckValidity();
61  brillo::ErrorPtr error;
62  bool success = false;
63  if (!proxy_->RequestVpnSetup(
64      user_names, interface, dbus_fd, &success, &error)) {
65    LOG(ERROR) << "Failed to request VPN setup: " << error->GetCode()
66               << " " << error->GetMessage();
67  }
68  return success;
69}
70
71bool ChromeosPermissionBrokerProxy::RemoveVpnSetup() {
72  if (lifeline_read_fd_ == kInvalidHandle &&
73      lifeline_write_fd_ == kInvalidHandle) {
74    return true;
75  }
76
77  close(lifeline_read_fd_);
78  close(lifeline_write_fd_);
79  lifeline_read_fd_ = kInvalidHandle;
80  lifeline_write_fd_ = kInvalidHandle;
81  brillo::ErrorPtr error;
82  bool success = false;
83  if (!proxy_->RemoveVpnSetup(&success, &error)) {
84    LOG(ERROR) << "Failed to remove VPN setup: " << error->GetCode()
85               << " " << error->GetMessage();
86  }
87  return success;
88}
89
90}  // namespace shill
91