blob: 85316d706b60112d52878e1fc8663e890b1a3c1b [file] [log] [blame]
Edward Hill024f5632017-06-29 15:23:38 -06001// Copyright 2017 The Chromium OS 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 "debugd/src/wifi_power_tool.h"
6
7#include <linux/capability.h>
8#include <net/if.h>
9
10#include "debugd/src/process_with_output.h"
11
12namespace debugd {
13
14namespace {
15
16const char kIwPath[] = "/usr/sbin/iw";
17const uint64_t kIwCapabilities = CAP_TO_MASK(CAP_NET_ADMIN);
18
19bool RunIwCommand(bool set, bool enable, std::string* output) {
20 bool success = false;
21 ProcessWithOutput p;
22 p.SetCapabilities(kIwCapabilities);
23 if (!p.Init()) {
24 *output = "<process init failed>";
25 return false;
26 }
27 p.AddArg(kIwPath);
28 p.AddArg("dev");
29 // Chrome OS WiFi device is either mlan0 or wlan0.
30 if (if_nametoindex("mlan0")) {
31 p.AddArg("mlan0");
32 } else if (if_nametoindex("wlan0")) {
33 p.AddArg("wlan0");
34 } else {
35 *output = "<no wifi device found>";
36 return false;
37 }
38 if (set) {
39 p.AddArg("set");
40 } else {
41 p.AddArg("get");
42 }
43 p.AddArg("power_save");
44 if (set) {
45 p.AddArg(enable ? "on" : "off");
46 }
47 if (p.Run() == 0) {
48 success = true;
49 }
50 p.GetOutput(output);
51 return success;
52}
53
54} // namespace
55
56std::string WifiPowerTool::SetWifiPowerSave(bool enable) const {
57 std::string result;
58 if (!RunIwCommand(true, enable, &result)) {
59 return result;
60 }
61 // Return the new state (successful set has no output)
62 return GetWifiPowerSave();
63}
64
65std::string WifiPowerTool::GetWifiPowerSave() const {
66 std::string result;
67 RunIwCommand(false, false, &result);
68 return result;
69}
70
71} // namespace debugd