fix(network): switch between ifaces upon disconnection

pull/331/head
Alex 2019-05-21 17:38:47 +02:00
parent 296b448d06
commit 48a58cd979
3 changed files with 129 additions and 113 deletions

View File

@ -30,7 +30,7 @@ class Network : public ALabel {
void worker(); void worker();
void createInfoSocket(); void createInfoSocket();
void createEventSocket(); void createEventSocket();
int getExternalInterface(); int getExternalInterface(int skip_idx = -1);
void getInterfaceAddress(); void getInterfaceAddress();
int netlinkRequest(void*, uint32_t, uint32_t groups = 0); int netlinkRequest(void*, uint32_t, uint32_t groups = 0);
int netlinkResponse(void*, uint32_t, uint32_t groups = 0); int netlinkResponse(void*, uint32_t, uint32_t groups = 0);
@ -39,8 +39,9 @@ class Network : public ALabel {
void parseFreq(struct nlattr**); void parseFreq(struct nlattr**);
bool associatedOrJoined(struct nlattr**); bool associatedOrJoined(struct nlattr**);
bool checkInterface(struct ifinfomsg *rtif, std::string name); bool checkInterface(struct ifinfomsg *rtif, std::string name);
int getPreferredIface(); int getPreferredIface(int skip_idx = -1);
auto getInfo() -> void; auto getInfo() -> void;
void clearIface();
bool wildcardMatch(const std::string& pattern, const std::string& text); bool wildcardMatch(const std::string& pattern, const std::string& text);
waybar::util::SleeperThread thread_; waybar::util::SleeperThread thread_;

View File

@ -5,28 +5,29 @@
namespace { namespace {
constexpr const char * NETSTAT_FILE = "/proc/net/netstat"; // std::ifstream does not take std::string_view as param constexpr const char *NETSTAT_FILE =
constexpr std::string_view BANDWIDTH_CATEGORY = "IpExt"; "/proc/net/netstat"; // std::ifstream does not take std::string_view as param
constexpr std::string_view BANDWIDTH_DOWN_TOTAL_KEY = "InOctets"; constexpr std::string_view BANDWIDTH_CATEGORY = "IpExt";
constexpr std::string_view BANDWIDTH_UP_TOTAL_KEY = "OutOctets"; constexpr std::string_view BANDWIDTH_DOWN_TOTAL_KEY = "InOctets";
constexpr std::string_view BANDWIDTH_UP_TOTAL_KEY = "OutOctets";
std::ifstream netstat(NETSTAT_FILE); std::ifstream netstat(NETSTAT_FILE);
std::optional<unsigned long long> read_netstat(std::string_view category, std::string_view key) { std::optional<unsigned long long> read_netstat(std::string_view category, std::string_view key) {
if (!netstat) { if (!netstat) {
spdlog::warn("Failed to open netstat file {}", NETSTAT_FILE); spdlog::warn("Failed to open netstat file {}", NETSTAT_FILE);
return {}; return {};
} }
netstat.seekg(std::ios_base::beg); netstat.seekg(std::ios_base::beg);
// finding corresponding line (category) // finding corresponding line (category)
// looks into the file for the first line starting by the 'category' string // looks into the file for the first line starting by the 'category' string
auto starts_with = [](const std::string& str, std::string_view start) { auto starts_with = [](const std::string &str, std::string_view start) {
return start == std::string_view{str.data(), std::min(str.size(), start.size())}; return start == std::string_view{str.data(), std::min(str.size(), start.size())};
}; };
std::string read; std::string read;
while (std::getline(netstat, read) && !starts_with(read, category)); while (std::getline(netstat, read) && !starts_with(read, category))
;
if (!starts_with(read, category)) { if (!starts_with(read, category)) {
spdlog::warn("Category '{}' not found in netstat file {}", category, NETSTAT_FILE); spdlog::warn("Category '{}' not found in netstat file {}", category, NETSTAT_FILE);
return {}; return {};
@ -52,7 +53,8 @@ namespace {
} }
if (r_it == read.end() && k_it != key.end()) { if (r_it == read.end() && k_it != key.end()) {
spdlog::warn("Key '{}' not found in category '{}' of netstat file {}", key, category, NETSTAT_FILE); spdlog::warn(
"Key '{}' not found in category '{}' of netstat file {}", key, category, NETSTAT_FILE);
return {}; return {};
} }
@ -67,8 +69,8 @@ namespace {
unsigned long long value; unsigned long long value;
iss >> value; iss >> value;
return value; return value;
}
} }
} // namespace
waybar::modules::Network::Network(const std::string &id, const Json::Value &config) waybar::modules::Network::Network(const std::string &id, const Json::Value &config)
: ALabel(config, "{ifname}", 60), : ALabel(config, "{ifname}", 60),
@ -273,14 +275,16 @@ auto waybar::modules::Network::update() -> void {
} }
getState(signal_strength_); getState(signal_strength_);
auto pow_format = [](unsigned long long value, const std::string& unit) { auto pow_format = [](unsigned long long value, const std::string &unit) {
if (value > 2000ull * 1000ull * 1000ull) { // > 2G if (value > 2000ull * 1000ull * 1000ull) { // > 2G
auto go = value / (1000 * 1000 * 1000); auto go = value / (1000 * 1000 * 1000);
return std::to_string(go) + "." + std::to_string((value - go * 1000 * 1000 * 1000) / (100 * 1000 * 1000)) + "G" + unit; return std::to_string(go) + "." +
std::to_string((value - go * 1000 * 1000 * 1000) / (100 * 1000 * 1000)) + "G" + unit;
} else if (value > 2000ull * 1000ull) { // > 2M } else if (value > 2000ull * 1000ull) { // > 2M
auto mo = value / (1000 * 1000); auto mo = value / (1000 * 1000);
return std::to_string(mo) + "." + std::to_string((value - mo * 1000 * 1000) / (100 * 1000)) + "M" + unit; return std::to_string(mo) + "." + std::to_string((value - mo * 1000 * 1000) / (100 * 1000)) +
"M" + unit;
} else if (value > 2000ull) { // > 2k } else if (value > 2000ull) { // > 2k
auto ko = value / 1000; auto ko = value / 1000;
@ -291,7 +295,8 @@ auto waybar::modules::Network::update() -> void {
} }
}; };
auto text = fmt::format(format_, auto text = fmt::format(
format_,
fmt::arg("essid", essid_), fmt::arg("essid", essid_),
fmt::arg("signaldBm", signal_strength_dbm_), fmt::arg("signaldBm", signal_strength_dbm_),
fmt::arg("signalStrength", signal_strength_), fmt::arg("signalStrength", signal_strength_),
@ -313,7 +318,8 @@ auto waybar::modules::Network::update() -> void {
tooltip_format = config_["tooltip-format"].asString(); tooltip_format = config_["tooltip-format"].asString();
} }
if (!tooltip_format.empty()) { if (!tooltip_format.empty()) {
auto tooltip_text = fmt::format(tooltip_format, auto tooltip_text = fmt::format(
tooltip_format,
fmt::arg("essid", essid_), fmt::arg("essid", essid_),
fmt::arg("signaldBm", signal_strength_dbm_), fmt::arg("signaldBm", signal_strength_dbm_),
fmt::arg("signalStrength", signal_strength_), fmt::arg("signalStrength", signal_strength_),
@ -323,7 +329,8 @@ auto waybar::modules::Network::update() -> void {
fmt::arg("cidr", cidr_), fmt::arg("cidr", cidr_),
fmt::arg("frequency", frequency_), fmt::arg("frequency", frequency_),
fmt::arg("icon", getIcon(signal_strength_, connectiontype)), fmt::arg("icon", getIcon(signal_strength_, connectiontype)),
fmt::arg("bandwidthDownBits", pow_format(bandwidth_down * 8ull / interval_.count(), "b/s")), fmt::arg("bandwidthDownBits",
pow_format(bandwidth_down * 8ull / interval_.count(), "b/s")),
fmt::arg("bandwidthUpBits", pow_format(bandwidth_up * 8ull / interval_.count(), "b/s")), fmt::arg("bandwidthUpBits", pow_format(bandwidth_up * 8ull / interval_.count(), "b/s")),
fmt::arg("bandwidthDownOctets", pow_format(bandwidth_down / interval_.count(), "o/s")), fmt::arg("bandwidthDownOctets", pow_format(bandwidth_down / interval_.count(), "o/s")),
fmt::arg("bandwidthUpOctets", pow_format(bandwidth_up / interval_.count(), "o/s"))); fmt::arg("bandwidthUpOctets", pow_format(bandwidth_up / interval_.count(), "o/s")));
@ -337,7 +344,7 @@ auto waybar::modules::Network::update() -> void {
} }
// Based on https://gist.github.com/Yawning/c70d804d4b8ae78cc698 // Based on https://gist.github.com/Yawning/c70d804d4b8ae78cc698
int waybar::modules::Network::getExternalInterface() { int waybar::modules::Network::getExternalInterface(int skip_idx) {
static const uint32_t route_buffer_size = 8192; static const uint32_t route_buffer_size = 8192;
struct nlmsghdr * hdr = nullptr; struct nlmsghdr * hdr = nullptr;
struct rtmsg * rt = nullptr; struct rtmsg * rt = nullptr;
@ -447,7 +454,7 @@ int waybar::modules::Network::getExternalInterface() {
/* If this is the default route, and we know the interface index, /* If this is the default route, and we know the interface index,
* we can stop parsing this message. * we can stop parsing this message.
*/ */
if (has_gateway && !has_destination && temp_idx != -1) { if (has_gateway && !has_destination && temp_idx != -1 && temp_idx != skip_idx) {
ifidx = temp_idx; ifidx = temp_idx;
break; break;
} }
@ -540,7 +547,7 @@ bool waybar::modules::Network::checkInterface(struct ifinfomsg *rtif, std::strin
return external_iface == rtif->ifi_index; return external_iface == rtif->ifi_index;
} }
int waybar::modules::Network::getPreferredIface() { int waybar::modules::Network::getPreferredIface(int skip_idx) {
if (config_["interface"].isString()) { if (config_["interface"].isString()) {
ifid_ = if_nametoindex(config_["interface"].asCString()); ifid_ = if_nametoindex(config_["interface"].asCString());
if (ifid_ > 0) { if (ifid_ > 0) {
@ -566,7 +573,7 @@ int waybar::modules::Network::getPreferredIface() {
return ifid_; return ifid_;
} }
} }
ifid_ = getExternalInterface(); ifid_ = getExternalInterface(skip_idx);
if (ifid_ > 0) { if (ifid_ > 0) {
char ifname[IF_NAMESIZE]; char ifname[IF_NAMESIZE];
if_indextoname(ifid_, ifname); if_indextoname(ifid_, ifname);
@ -576,6 +583,17 @@ int waybar::modules::Network::getPreferredIface() {
return -1; return -1;
} }
void waybar::modules::Network::clearIface() {
essid_.clear();
ipaddr_.clear();
netmask_.clear();
cidr_ = 0;
signal_strength_dbm_ = 0;
signal_strength_ = 0;
frequency_ = 0;
linked_ = false;
}
int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) { int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
auto net = static_cast<waybar::modules::Network *>(data); auto net = static_cast<waybar::modules::Network *>(data);
auto nh = nlmsg_hdr(msg); auto nh = nlmsg_hdr(msg);
@ -586,7 +604,11 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
char ifname[IF_NAMESIZE]; char ifname[IF_NAMESIZE];
if_indextoname(rtif->ifi_index, ifname); if_indextoname(rtif->ifi_index, ifname);
// Auto detected network can also be assigned here // Auto detected network can also be assigned here
if (net->ifid_ == -1 && net->checkInterface(rtif, ifname)) { if ((net->ifid_ == -1 || rtif->ifi_index != net->ifid_) && net->checkInterface(rtif, ifname)) {
// If iface is different, clear data
if (rtif->ifi_index != net->ifid_) {
net->clearIface();
}
net->linked_ = true; net->linked_ = true;
net->ifname_ = ifname; net->ifname_ = ifname;
net->ifid_ = rtif->ifi_index; net->ifid_ = rtif->ifi_index;
@ -618,15 +640,9 @@ int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
net->ifid_ = rtif->ifi_index; net->ifid_ = rtif->ifi_index;
net->dp.emit(); net->dp.emit();
} else if (rtif->ifi_index == net->ifid_) { } else if (rtif->ifi_index == net->ifid_) {
net->linked_ = false; net->clearIface();
net->ifname_.clear();
net->ifid_ = -1;
net->essid_.clear();
net->signal_strength_dbm_ = 0;
net->signal_strength_ = 0;
net->frequency_ = 0;
// Check for a new interface and get info // Check for a new interface and get info
auto new_iface = net->getPreferredIface(); auto new_iface = net->getPreferredIface(rtif->ifi_index);
if (new_iface != -1) { if (new_iface != -1) {
net->getInterfaceAddress(); net->getInterfaceAddress();
net->thread_timer_.wake_up(); net->thread_timer_.wake_up();

View File

@ -1,5 +1,4 @@
#include "modules/pulseaudio.hpp" #include "modules/pulseaudio.hpp"
#include <iostream>
waybar::modules::Pulseaudio::Pulseaudio(const std::string &id, const Json::Value &config) waybar::modules::Pulseaudio::Pulseaudio(const std::string &id, const Json::Value &config)
: ALabel(config, "{volume}%"), : ALabel(config, "{volume}%"),