Waybar/src/modules/network.cpp

837 lines
26 KiB
C++
Raw Normal View History

2018-08-09 14:38:24 +00:00
#include "modules/network.hpp"
2019-05-18 23:44:45 +00:00
#include <spdlog/spdlog.h>
2019-04-18 15:52:00 +00:00
#include <sys/eventfd.h>
#include <fstream>
#include <cassert>
#include <optional>
2019-09-23 20:25:54 +00:00
#include "util/format.hpp"
#ifdef WANT_RFKILL
2020-01-21 16:48:45 +00:00
#include "util/rfkill.hpp"
#endif
namespace {
2019-09-23 20:25:54 +00:00
using namespace waybar::util;
constexpr const char *NETSTAT_FILE =
"/proc/net/netstat"; // std::ifstream does not take std::string_view as param
constexpr std::string_view BANDWIDTH_CATEGORY = "IpExt";
constexpr std::string_view BANDWIDTH_DOWN_TOTAL_KEY = "InOctets";
constexpr std::string_view BANDWIDTH_UP_TOTAL_KEY = "OutOctets";
std::ifstream netstat(NETSTAT_FILE);
std::optional<unsigned long long> read_netstat(std::string_view category, std::string_view key) {
if (!netstat) {
spdlog::warn("Failed to open netstat file {}", NETSTAT_FILE);
return {};
}
netstat.seekg(std::ios_base::beg);
// finding corresponding line (category)
// looks into the file for the first line starting by the 'category' string
auto starts_with = [](const std::string &str, std::string_view start) {
return start == std::string_view{str.data(), std::min(str.size(), start.size())};
};
std::string read;
while (std::getline(netstat, read) && !starts_with(read, category))
;
if (!starts_with(read, category)) {
spdlog::warn("Category '{}' not found in netstat file {}", category, NETSTAT_FILE);
return {};
}
// finding corresponding column (key)
// looks into the fetched line for the first word (space separated) equal to 'key'
int index = 0;
auto r_it = read.begin();
auto k_it = key.begin();
while (k_it != key.end() && r_it != read.end()) {
if (*r_it != *k_it) {
r_it = std::find(r_it, read.end(), ' ');
if (r_it != read.end()) {
++r_it;
}
k_it = key.begin();
++index;
} else {
++r_it;
++k_it;
}
}
if (r_it == read.end() && k_it != key.end()) {
spdlog::warn(
"Key '{}' not found in category '{}' of netstat file {}", key, category, NETSTAT_FILE);
return {};
}
// finally accessing value
// accesses the line right under the fetched one
std::getline(netstat, read);
assert(starts_with(read, category));
std::istringstream iss(read);
while (index--) {
std::getline(iss, read, ' ');
}
unsigned long long value;
iss >> value;
return value;
}
} // namespace
2018-08-09 14:38:24 +00:00
2019-04-18 15:52:00 +00:00
waybar::modules::Network::Network(const std::string &id, const Json::Value &config)
: ALabel(config, "network", id, "{ifname}", 60),
2019-05-16 09:22:22 +00:00
ifid_(-1),
2019-05-16 10:22:08 +00:00
family_(config["family"] == "ipv6" ? AF_INET6 : AF_INET),
2020-09-21 08:56:40 +00:00
efd_(-1),
ev_fd_(-1),
2019-04-18 15:52:00 +00:00
cidr_(-1),
signal_strength_dbm_(0),
2019-05-17 09:27:38 +00:00
signal_strength_(0),
#ifdef WANT_RFKILL
rfkill_{RFKILL_TYPE_WLAN},
#endif
frequency_(0) {
auto down_octets = read_netstat(BANDWIDTH_CATEGORY, BANDWIDTH_DOWN_TOTAL_KEY);
auto up_octets = read_netstat(BANDWIDTH_CATEGORY, BANDWIDTH_UP_TOTAL_KEY);
if (down_octets) {
bandwidth_down_total_ = *down_octets;
} else {
bandwidth_down_total_ = 0;
}
if (up_octets) {
bandwidth_up_total_ = *up_octets;
} else {
bandwidth_up_total_ = 0;
}
2018-12-26 10:13:36 +00:00
createEventSocket();
createInfoSocket();
2019-09-25 08:32:22 +00:00
auto default_iface = getPreferredIface(-1, false);
2019-05-16 09:22:22 +00:00
if (default_iface != -1) {
2019-05-22 20:20:50 +00:00
ifid_ = default_iface;
2019-05-16 09:22:22 +00:00
char ifname[IF_NAMESIZE];
if_indextoname(default_iface, ifname);
ifname_ = ifname;
getInterfaceAddress();
2018-08-16 12:29:41 +00:00
}
2018-12-18 16:30:54 +00:00
dp.emit();
2018-11-16 09:02:12 +00:00
worker();
}
2019-04-18 15:52:00 +00:00
waybar::modules::Network::~Network() {
2020-09-21 08:56:40 +00:00
if (ev_fd_ > -1) {
close(ev_fd_);
}
if (efd_ > -1) {
close(efd_);
}
2019-05-16 09:22:22 +00:00
if (ev_sock_ != nullptr) {
nl_socket_drop_membership(ev_sock_, RTNLGRP_LINK);
if (family_ == AF_INET) {
nl_socket_drop_membership(ev_sock_, RTNLGRP_IPV4_IFADDR);
} else {
nl_socket_drop_membership(ev_sock_, RTNLGRP_IPV6_IFADDR);
}
2019-05-16 09:22:22 +00:00
nl_close(ev_sock_);
nl_socket_free(ev_sock_);
2018-12-26 10:13:36 +00:00
}
2019-05-16 09:22:22 +00:00
if (sock_ != nullptr) {
nl_close(sock_);
nl_socket_free(sock_);
2018-12-26 10:13:36 +00:00
}
2018-11-16 09:02:12 +00:00
}
void waybar::modules::Network::createEventSocket() {
2019-05-16 09:22:22 +00:00
ev_sock_ = nl_socket_alloc();
nl_socket_disable_seq_check(ev_sock_);
nl_socket_modify_cb(ev_sock_, NL_CB_VALID, NL_CB_CUSTOM, handleEvents, this);
auto groups = RTMGRP_LINK | (family_ == AF_INET ? RTMGRP_IPV4_IFADDR : RTMGRP_IPV6_IFADDR);
nl_join_groups(ev_sock_, groups); // Deprecated
2019-05-16 09:22:22 +00:00
if (nl_connect(ev_sock_, NETLINK_ROUTE) != 0) {
throw std::runtime_error("Can't connect network socket");
}
2019-05-16 09:22:22 +00:00
nl_socket_add_membership(ev_sock_, RTNLGRP_LINK);
if (family_ == AF_INET) {
nl_socket_add_membership(ev_sock_, RTNLGRP_IPV4_IFADDR);
} else {
nl_socket_add_membership(ev_sock_, RTNLGRP_IPV6_IFADDR);
}
2020-09-21 08:56:40 +00:00
efd_ = epoll_create1(EPOLL_CLOEXEC);
if (efd_ < 0) {
throw std::runtime_error("Can't create epoll");
}
{
ev_fd_ = eventfd(0, EFD_NONBLOCK);
struct epoll_event event;
memset(&event, 0, sizeof(event));
event.events = EPOLLIN | EPOLLET;
event.data.fd = ev_fd_;
if (epoll_ctl(efd_, EPOLL_CTL_ADD, ev_fd_, &event) == -1) {
throw std::runtime_error("Can't add epoll event");
}
}
{
auto fd = nl_socket_get_fd(ev_sock_);
struct epoll_event event;
memset(&event, 0, sizeof(event));
event.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
event.data.fd = fd;
if (epoll_ctl(efd_, EPOLL_CTL_ADD, fd, &event) == -1) {
throw std::runtime_error("Can't add epoll event");
}
}
2018-12-26 10:13:36 +00:00
}
void waybar::modules::Network::createInfoSocket() {
2019-05-16 09:22:22 +00:00
sock_ = nl_socket_alloc();
if (genl_connect(sock_) != 0) {
2018-12-26 10:13:36 +00:00
throw std::runtime_error("Can't connect to netlink socket");
}
2019-05-16 09:22:22 +00:00
if (nl_socket_modify_cb(sock_, NL_CB_VALID, NL_CB_CUSTOM, handleScan, this) < 0) {
2018-12-26 10:13:36 +00:00
throw std::runtime_error("Can't set callback");
}
2019-05-16 09:22:22 +00:00
nl80211_id_ = genl_ctrl_resolve(sock_, "nl80211");
2018-12-26 10:13:36 +00:00
if (nl80211_id_ < 0) {
spdlog::warn("Can't resolve nl80211 interface");
2018-12-26 10:13:36 +00:00
}
}
2019-04-18 15:52:00 +00:00
void waybar::modules::Network::worker() {
// update via here not working
2018-11-23 10:57:37 +00:00
thread_timer_ = [this] {
2019-05-18 13:32:40 +00:00
{
std::lock_guard<std::mutex> lock(mutex_);
if (ifid_ > 0) {
getInfo();
dp.emit();
}
2018-11-16 09:02:12 +00:00
}
2018-12-26 10:13:36 +00:00
thread_timer_.sleep_for(interval_);
};
#ifdef WANT_RFKILL
rfkill_.on_update.connect([this](auto &) {
std::lock_guard<std::mutex> lock(mutex_);
if (ifid_ > 0) {
getInfo();
dp.emit();
}
});
#else
spdlog::warn("Waybar has been built without rfkill support.");
#endif
2020-09-21 08:56:40 +00:00
thread_ = [this] {
std::array<struct epoll_event, EPOLL_MAX> events{};
int ec = epoll_wait(efd_, events.data(), EPOLL_MAX, -1);
if (ec > 0) {
for (auto i = 0; i < ec; i++) {
if (events[i].data.fd != nl_socket_get_fd(ev_sock_) || nl_recvmsgs_default(ev_sock_) < 0) {
thread_.stop();
break;
}
}
}
};
2018-08-19 11:39:57 +00:00
}
2019-05-24 07:49:56 +00:00
const std::string waybar::modules::Network::getNetworkState() const {
if (ifid_ == -1) {
2020-08-15 08:36:15 +00:00
#ifdef WANT_RFKILL
if (rfkill_.getState())
2020-01-21 16:48:45 +00:00
return "disabled";
2020-08-15 08:36:15 +00:00
#endif
2020-01-21 16:48:45 +00:00
return "disconnected";
}
2019-05-24 07:49:56 +00:00
if (ipaddr_.empty()) return "linked";
if (essid_.empty()) return "ethernet";
return "wifi";
}
2019-04-18 15:52:00 +00:00
auto waybar::modules::Network::update() -> void {
2019-05-18 13:32:40 +00:00
std::lock_guard<std::mutex> lock(mutex_);
2019-05-24 07:49:56 +00:00
std::string tooltip_format;
auto down_octets = read_netstat(BANDWIDTH_CATEGORY, BANDWIDTH_DOWN_TOTAL_KEY);
auto up_octets = read_netstat(BANDWIDTH_CATEGORY, BANDWIDTH_UP_TOTAL_KEY);
unsigned long long bandwidth_down = 0;
if (down_octets) {
bandwidth_down = *down_octets - bandwidth_down_total_;
bandwidth_down_total_ = *down_octets;
}
unsigned long long bandwidth_up = 0;
if (up_octets) {
bandwidth_up = *up_octets - bandwidth_up_total_;
bandwidth_up_total_ = *up_octets;
}
2019-05-24 07:49:56 +00:00
if (!alt_) {
auto state = getNetworkState();
if (!state_.empty() && label_.get_style_context()->has_class(state_)) {
label_.get_style_context()->remove_class(state_);
2019-01-13 21:36:37 +00:00
}
2019-05-24 07:49:56 +00:00
if (config_["format-" + state].isString()) {
default_format_ = config_["format-" + state].asString();
}
2019-05-24 07:49:56 +00:00
if (config_["tooltip-format-" + state].isString()) {
tooltip_format = config_["tooltip-format-" + state].asString();
}
if (!label_.get_style_context()->has_class(state)) {
label_.get_style_context()->add_class(state);
2018-08-17 12:24:00 +00:00
}
2019-01-13 21:36:37 +00:00
format_ = default_format_;
2019-05-24 07:49:56 +00:00
state_ = state;
2019-01-13 21:36:37 +00:00
}
getState(signal_strength_);
auto text = fmt::format(
format_,
fmt::arg("essid", essid_),
fmt::arg("signaldBm", signal_strength_dbm_),
fmt::arg("signalStrength", signal_strength_),
fmt::arg("ifname", ifname_),
fmt::arg("netmask", netmask_),
fmt::arg("ipaddr", ipaddr_),
fmt::arg("cidr", cidr_),
fmt::arg("frequency", frequency_),
2019-05-24 07:49:56 +00:00
fmt::arg("icon", getIcon(signal_strength_, state_)),
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("bandwidthDownOctets", pow_format(bandwidth_down / interval_.count(), "o/s")),
fmt::arg("bandwidthUpOctets", pow_format(bandwidth_up / interval_.count(), "o/s")));
if (text.compare(label_.get_label()) != 0) {
2019-05-18 13:32:40 +00:00
label_.set_markup(text);
2019-12-30 12:44:06 +00:00
if (text.empty()) {
event_box_.hide();
} else {
event_box_.show();
}
2019-05-18 13:32:40 +00:00
}
if (tooltipEnabled()) {
2019-05-18 13:32:40 +00:00
if (tooltip_format.empty() && config_["tooltip-format"].isString()) {
tooltip_format = config_["tooltip-format"].asString();
}
if (!tooltip_format.empty()) {
auto tooltip_text = fmt::format(
tooltip_format,
fmt::arg("essid", essid_),
fmt::arg("signaldBm", signal_strength_dbm_),
fmt::arg("signalStrength", signal_strength_),
fmt::arg("ifname", ifname_),
fmt::arg("netmask", netmask_),
fmt::arg("ipaddr", ipaddr_),
fmt::arg("cidr", cidr_),
fmt::arg("frequency", frequency_),
2019-05-24 07:49:56 +00:00
fmt::arg("icon", getIcon(signal_strength_, state_)),
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("bandwidthDownOctets", pow_format(bandwidth_down / interval_.count(), "o/s")),
fmt::arg("bandwidthUpOctets", pow_format(bandwidth_up / interval_.count(), "o/s")));
if (label_.get_tooltip_text() != tooltip_text) {
2019-05-18 13:32:40 +00:00
label_.set_tooltip_text(tooltip_text);
}
2019-05-18 13:45:18 +00:00
} else if (label_.get_tooltip_text() != text) {
label_.set_tooltip_text(text);
}
}
2020-04-12 16:30:21 +00:00
// Call parent update
ALabel::update();
2018-08-09 14:38:24 +00:00
}
2018-08-17 12:24:00 +00:00
// Based on https://gist.github.com/Yawning/c70d804d4b8ae78cc698
2019-05-22 20:20:50 +00:00
int waybar::modules::Network::getExternalInterface(int skip_idx) const {
2018-08-20 12:50:45 +00:00
static const uint32_t route_buffer_size = 8192;
2019-04-18 15:52:00 +00:00
struct nlmsghdr * hdr = nullptr;
struct rtmsg * rt = nullptr;
char resp[route_buffer_size] = {0};
int ifidx = -1;
2018-08-17 12:24:00 +00:00
2018-08-20 12:50:45 +00:00
/* Prepare request. */
2018-10-04 16:03:01 +00:00
constexpr uint32_t reqlen = NLMSG_SPACE(sizeof(*rt));
2019-04-18 15:52:00 +00:00
char req[reqlen] = {0};
2018-08-17 12:24:00 +00:00
/* Build the RTM_GETROUTE request. */
2018-08-20 12:50:45 +00:00
hdr = reinterpret_cast<struct nlmsghdr *>(req);
2018-08-17 12:24:00 +00:00
hdr->nlmsg_len = NLMSG_LENGTH(sizeof(*rt));
hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;
hdr->nlmsg_type = RTM_GETROUTE;
rt = static_cast<struct rtmsg *>(NLMSG_DATA(hdr));
rt->rtm_family = family_;
rt->rtm_table = RT_TABLE_MAIN;
/* Issue the query. */
2018-12-26 10:13:36 +00:00
if (netlinkRequest(req, reqlen) < 0) {
2018-08-17 12:24:00 +00:00
goto out;
}
/* Read the response(s).
*
* WARNING: All the packets generated by the request must be consumed (as in,
* consume responses till NLMSG_DONE/NLMSG_ERROR is encountered).
*/
do {
2018-12-26 10:13:36 +00:00
auto len = netlinkResponse(resp, route_buffer_size);
2018-08-17 12:24:00 +00:00
if (len < 0) {
goto out;
}
/* Parse the response payload into netlink messages. */
2018-08-20 12:50:45 +00:00
for (hdr = reinterpret_cast<struct nlmsghdr *>(resp); NLMSG_OK(hdr, len);
2019-04-18 15:52:00 +00:00
hdr = NLMSG_NEXT(hdr, len)) {
2018-08-17 12:24:00 +00:00
if (hdr->nlmsg_type == NLMSG_DONE) {
goto out;
}
if (hdr->nlmsg_type == NLMSG_ERROR) {
/* Even if we found the interface index, something is broken with the
* netlink socket, so return an error.
*/
ifidx = -1;
goto out;
}
/* If we found the correct answer, skip parsing the attributes. */
if (ifidx != -1) {
continue;
}
/* Find the message(s) concerting the main routing table, each message
* corresponds to a single routing table entry.
*/
rt = static_cast<struct rtmsg *>(NLMSG_DATA(hdr));
if (rt->rtm_table != RT_TABLE_MAIN) {
continue;
}
/* Parse all the attributes for a single routing table entry. */
struct rtattr *attr = RTM_RTA(rt);
2019-04-18 15:52:00 +00:00
uint64_t attrlen = RTM_PAYLOAD(hdr);
bool has_gateway = false;
bool has_destination = false;
int temp_idx = -1;
2018-08-17 12:24:00 +00:00
for (; RTA_OK(attr, attrlen); attr = RTA_NEXT(attr, attrlen)) {
/* Determine if this routing table entry corresponds to the default
* route by seeing if it has a gateway, and if a destination addr is
* set, that it is all 0s.
*/
switch (attr->rta_type) {
case RTA_GATEWAY:
/* The gateway of the route.
*
* If someone every needs to figure out the gateway address as well,
* it's here as the attribute payload.
*/
has_gateway = true;
break;
case RTA_DST: {
/* The destination address.
* Should be either missing, or maybe all 0s. Accept both.
*/
const uint32_t nr_zeroes = (family_ == AF_INET) ? 4 : 16;
2019-04-18 15:52:00 +00:00
unsigned char c = 0;
size_t dstlen = RTA_PAYLOAD(attr);
2018-08-17 12:24:00 +00:00
if (dstlen != nr_zeroes) {
break;
}
for (uint32_t i = 0; i < dstlen; i += 1) {
2018-10-04 16:03:01 +00:00
c |= *((unsigned char *)RTA_DATA(attr) + i);
2018-08-17 12:24:00 +00:00
}
has_destination = (c == 0);
break;
}
case RTA_OIF:
/* The output interface index. */
2019-04-18 15:52:00 +00:00
temp_idx = *static_cast<int *>(RTA_DATA(attr));
2018-08-17 12:24:00 +00:00
break;
default:
break;
}
}
/* If this is the default route, and we know the interface index,
* we can stop parsing this message.
*/
if (has_gateway && !has_destination && temp_idx != -1 && temp_idx != skip_idx) {
2018-08-17 12:24:00 +00:00
ifidx = temp_idx;
break;
}
}
} while (true);
out:
return ifidx;
}
void waybar::modules::Network::getInterfaceAddress() {
struct ifaddrs *ifaddr, *ifa;
cidr_ = 0;
int success = getifaddrs(&ifaddr);
2019-05-16 10:14:12 +00:00
if (success != 0) {
return;
}
ifa = ifaddr;
2019-05-25 16:02:36 +00:00
while (ifa != nullptr) {
2019-05-16 10:14:12 +00:00
if (ifa->ifa_addr != nullptr && ifa->ifa_addr->sa_family == family_ &&
ifa->ifa_name == ifname_) {
char ipaddr[INET6_ADDRSTRLEN];
char netmask[INET6_ADDRSTRLEN];
unsigned int cidr = 0;
2020-01-04 02:11:34 +00:00
if (family_ == AF_INET) {
ipaddr_ = inet_ntop(AF_INET,
&reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr)->sin_addr,
ipaddr,
INET_ADDRSTRLEN);
auto net_addr = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_netmask);
netmask_ = inet_ntop(AF_INET, &net_addr->sin_addr, netmask, INET_ADDRSTRLEN);
unsigned int cidrRaw = net_addr->sin_addr.s_addr;
while (cidrRaw) {
cidr += cidrRaw & 1;
cidrRaw >>= 1;
}
} else {
ipaddr_ = inet_ntop(AF_INET6,
&reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr)->sin6_addr,
ipaddr,
INET6_ADDRSTRLEN);
auto net_addr = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_netmask);
netmask_ = inet_ntop(AF_INET6, &net_addr->sin6_addr, netmask, INET6_ADDRSTRLEN);
for (size_t i = 0; i < sizeof(net_addr->sin6_addr.s6_addr); ++i) {
unsigned char cidrRaw = net_addr->sin6_addr.s6_addr[i];
while (cidrRaw) {
cidr += cidrRaw & 1;
cidrRaw >>= 1;
}
}
}
2019-05-16 10:14:12 +00:00
cidr_ = cidr;
2019-05-25 16:02:36 +00:00
break;
}
2019-05-16 10:14:12 +00:00
ifa = ifa->ifa_next;
}
2019-05-16 10:14:12 +00:00
freeifaddrs(ifaddr);
}
2019-05-22 20:20:50 +00:00
int waybar::modules::Network::netlinkRequest(void *req, uint32_t reqlen, uint32_t groups) const {
2018-09-10 09:16:57 +00:00
struct sockaddr_nl sa = {};
2018-08-17 12:24:00 +00:00
sa.nl_family = AF_NETLINK;
sa.nl_groups = groups;
2019-04-18 15:52:00 +00:00
struct iovec iov = {req, reqlen};
2019-05-16 15:09:25 +00:00
struct msghdr msg = {
.msg_name = &sa,
.msg_namelen = sizeof(sa),
.msg_iov = &iov,
.msg_iovlen = 1,
};
2019-05-16 09:22:22 +00:00
return sendmsg(nl_socket_get_fd(ev_sock_), &msg, 0);
2018-08-17 12:24:00 +00:00
}
2019-05-22 20:20:50 +00:00
int waybar::modules::Network::netlinkResponse(void *resp, uint32_t resplen, uint32_t groups) const {
2018-09-10 09:16:57 +00:00
struct sockaddr_nl sa = {};
2018-08-17 12:24:00 +00:00
sa.nl_family = AF_NETLINK;
sa.nl_groups = groups;
2019-04-18 15:52:00 +00:00
struct iovec iov = {resp, resplen};
2019-05-16 15:09:25 +00:00
struct msghdr msg = {
.msg_name = &sa,
.msg_namelen = sizeof(sa),
.msg_iov = &iov,
.msg_iovlen = 1,
};
auto ret = recvmsg(nl_socket_get_fd(ev_sock_), &msg, 0);
2018-08-20 12:50:45 +00:00
if (msg.msg_flags & MSG_TRUNC) {
2018-08-17 12:24:00 +00:00
return -1;
2018-08-20 12:50:45 +00:00
}
2018-08-17 12:24:00 +00:00
return ret;
}
2019-05-18 11:57:35 +00:00
bool waybar::modules::Network::checkInterface(struct ifinfomsg *rtif, std::string name) {
2019-05-16 09:22:22 +00:00
if (config_["interface"].isString()) {
return config_["interface"].asString() == name ||
wildcardMatch(config_["interface"].asString(), name);
}
// getExternalInterface may need some delay to detect external interface
for (uint8_t tries = 0; tries < MAX_RETRY; tries += 1) {
auto external_iface = getExternalInterface();
if (external_iface > 0) {
return external_iface == rtif->ifi_index;
}
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
return false;
2019-05-16 09:22:22 +00:00
}
2019-09-25 08:59:07 +00:00
int waybar::modules::Network::getPreferredIface(int skip_idx, bool wait) const {
2019-05-22 20:20:50 +00:00
int ifid = -1;
2019-05-16 09:22:22 +00:00
if (config_["interface"].isString()) {
2019-05-22 20:20:50 +00:00
ifid = if_nametoindex(config_["interface"].asCString());
if (ifid > 0) {
return ifid;
2019-05-16 09:22:22 +00:00
} else {
2019-05-16 10:14:12 +00:00
// Try with wildcard
2019-05-16 09:22:22 +00:00
struct ifaddrs *ifaddr, *ifa;
int success = getifaddrs(&ifaddr);
if (success != 0) {
return -1;
}
ifa = ifaddr;
2019-05-22 20:20:50 +00:00
ifid = -1;
2019-05-16 10:14:12 +00:00
while (ifa != nullptr) {
if (wildcardMatch(config_["interface"].asString(), ifa->ifa_name)) {
2019-05-22 20:20:50 +00:00
ifid = if_nametoindex(ifa->ifa_name);
2019-05-16 09:22:22 +00:00
break;
}
ifa = ifa->ifa_next;
}
freeifaddrs(ifaddr);
2019-05-22 20:20:50 +00:00
return ifid;
2019-05-16 09:22:22 +00:00
}
}
// getExternalInterface may need some delay to detect external interface
for (uint8_t tries = 0; tries < MAX_RETRY; tries += 1) {
ifid = getExternalInterface(skip_idx);
if (ifid > 0) {
return ifid;
}
2019-09-25 08:32:22 +00:00
if (wait) {
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
2019-05-16 09:22:22 +00:00
}
return -1;
}
void waybar::modules::Network::clearIface() {
essid_.clear();
ipaddr_.clear();
netmask_.clear();
cidr_ = 0;
signal_strength_dbm_ = 0;
signal_strength_ = 0;
frequency_ = 0;
}
void waybar::modules::Network::checkNewInterface(struct ifinfomsg *rtif) {
auto new_iface = getPreferredIface(rtif->ifi_index);
if (new_iface != -1) {
ifid_ = new_iface;
char ifname[IF_NAMESIZE];
if_indextoname(new_iface, ifname);
ifname_ = ifname;
getInterfaceAddress();
thread_timer_.wake_up();
} else {
ifid_ = -1;
dp.emit();
}
}
int waybar::modules::Network::handleEvents(struct nl_msg *msg, void *data) {
2019-05-16 09:22:22 +00:00
auto net = static_cast<waybar::modules::Network *>(data);
std::lock_guard<std::mutex> lock(net->mutex_);
auto nh = nlmsg_hdr(msg);
auto ifi = static_cast<struct ifinfomsg *>(NLMSG_DATA(nh));
if (nh->nlmsg_type == RTM_DELADDR) {
// Check for valid interface
if (ifi->ifi_index == net->ifid_) {
net->ipaddr_.clear();
net->netmask_.clear();
net->cidr_ = 0;
if (!(ifi->ifi_flags & IFF_RUNNING)) {
net->clearIface();
// Check for a new interface and get info
net->checkNewInterface(ifi);
} else {
net->dp.emit();
}
return NL_OK;
}
} else if (nh->nlmsg_type == RTM_NEWLINK || nh->nlmsg_type == RTM_DELLINK) {
char ifname[IF_NAMESIZE];
if_indextoname(ifi->ifi_index, ifname);
// Check for valid interface
if (ifi->ifi_index != net->ifid_ && net->checkInterface(ifi, ifname)) {
net->ifname_ = ifname;
net->ifid_ = ifi->ifi_index;
// Get Iface and WIFI info
net->getInterfaceAddress();
net->thread_timer_.wake_up();
return NL_OK;
} else if (ifi->ifi_index == net->ifid_ &&
(!(ifi->ifi_flags & IFF_RUNNING) || !(ifi->ifi_flags & IFF_UP) ||
!net->checkInterface(ifi, ifname))) {
net->clearIface();
// Check for a new interface and get info
net->checkNewInterface(ifi);
return NL_OK;
}
} else {
2019-05-16 09:22:22 +00:00
char ifname[IF_NAMESIZE];
if_indextoname(ifi->ifi_index, ifname);
2019-05-16 09:26:06 +00:00
// Auto detected network can also be assigned here
if (ifi->ifi_index != net->ifid_ && net->checkInterface(ifi, ifname)) {
// If iface is different, clear data
if (ifi->ifi_index != net->ifid_) {
net->clearIface();
}
net->ifname_ = ifname;
net->ifid_ = ifi->ifi_index;
2019-05-16 09:22:22 +00:00
}
// Check for valid interface
if (ifi->ifi_index == net->ifid_) {
2019-05-16 09:22:22 +00:00
// Get Iface and WIFI info
net->getInterfaceAddress();
2019-05-18 10:27:10 +00:00
net->thread_timer_.wake_up();
return NL_OK;
}
2018-12-26 10:13:36 +00:00
}
return NL_SKIP;
2018-12-26 10:13:36 +00:00
}
int waybar::modules::Network::handleScan(struct nl_msg *msg, void *data) {
2019-04-18 15:52:00 +00:00
auto net = static_cast<waybar::modules::Network *>(data);
auto gnlh = static_cast<genlmsghdr *>(nlmsg_data(nlmsg_hdr(msg)));
struct nlattr * tb[NL80211_ATTR_MAX + 1];
struct nlattr * bss[NL80211_BSS_MAX + 1];
2018-08-24 13:32:06 +00:00
struct nla_policy bss_policy[NL80211_BSS_MAX + 1]{};
bss_policy[NL80211_BSS_TSF].type = NLA_U64;
bss_policy[NL80211_BSS_FREQUENCY].type = NLA_U32;
bss_policy[NL80211_BSS_BSSID].type = NLA_UNSPEC;
bss_policy[NL80211_BSS_BEACON_INTERVAL].type = NLA_U16;
bss_policy[NL80211_BSS_CAPABILITY].type = NLA_U16;
bss_policy[NL80211_BSS_INFORMATION_ELEMENTS].type = NLA_UNSPEC;
bss_policy[NL80211_BSS_SIGNAL_MBM].type = NLA_U32;
bss_policy[NL80211_BSS_SIGNAL_UNSPEC].type = NLA_U8;
bss_policy[NL80211_BSS_STATUS].type = NLA_U32;
2018-08-09 14:38:24 +00:00
2019-04-18 15:52:00 +00:00
if (nla_parse(
tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_attrlen(gnlh, 0), nullptr) < 0) {
2018-08-24 13:32:06 +00:00
return NL_SKIP;
}
if (tb[NL80211_ATTR_BSS] == nullptr) {
2018-08-09 14:38:24 +00:00
return NL_SKIP;
2018-08-24 13:32:06 +00:00
}
if (nla_parse_nested(bss, NL80211_BSS_MAX, tb[NL80211_ATTR_BSS], bss_policy) != 0) {
return NL_SKIP;
}
if (!net->associatedOrJoined(bss)) {
return NL_SKIP;
}
net->parseEssid(bss);
net->parseSignal(bss);
2019-05-17 09:27:38 +00:00
net->parseFreq(bss);
return NL_OK;
2018-08-09 14:38:24 +00:00
}
2019-04-18 15:52:00 +00:00
void waybar::modules::Network::parseEssid(struct nlattr **bss) {
2018-08-09 14:38:24 +00:00
if (bss[NL80211_BSS_INFORMATION_ELEMENTS] != nullptr) {
2019-04-18 15:52:00 +00:00
auto ies = static_cast<char *>(nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS]));
auto ies_len = nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
2018-08-09 14:38:24 +00:00
const auto hdr_len = 2;
while (ies_len > hdr_len && ies[0] != 0) {
ies_len -= ies[1] + hdr_len;
ies += ies[1] + hdr_len;
}
if (ies_len > hdr_len && ies_len > ies[1] + hdr_len) {
2019-04-18 15:52:00 +00:00
auto essid_begin = ies + hdr_len;
auto essid_end = essid_begin + ies[1];
std::string essid_raw;
std::copy(essid_begin, essid_end, std::back_inserter(essid_raw));
essid_ = Glib::Markup::escape_text(essid_raw);
2018-08-09 14:38:24 +00:00
}
}
}
2018-08-16 12:29:41 +00:00
void waybar::modules::Network::parseSignal(struct nlattr **bss) {
2018-08-24 13:32:06 +00:00
if (bss[NL80211_BSS_SIGNAL_MBM] != nullptr) {
2018-12-26 10:13:36 +00:00
// signalstrength in dBm from mBm
signal_strength_dbm_ = nla_get_s32(bss[NL80211_BSS_SIGNAL_MBM]) / 100;
2018-08-24 13:32:06 +00:00
// WiFi-hardware usually operates in the range -90 to -20dBm.
const int hardwareMax = -20;
const int hardwareMin = -90;
2019-09-19 21:07:38 +00:00
const int strength =
((signal_strength_dbm_ - hardwareMin) / double{hardwareMax - hardwareMin}) * 100;
signal_strength_ = std::clamp(strength, 0, 100);
2018-08-09 20:05:15 +00:00
}
2018-12-26 10:13:36 +00:00
if (bss[NL80211_BSS_SIGNAL_UNSPEC] != nullptr) {
signal_strength_ = nla_get_u8(bss[NL80211_BSS_SIGNAL_UNSPEC]);
}
2018-08-24 13:32:06 +00:00
}
2018-08-09 20:05:15 +00:00
2019-05-17 09:27:38 +00:00
void waybar::modules::Network::parseFreq(struct nlattr **bss) {
if (bss[NL80211_BSS_FREQUENCY] != nullptr) {
// in MHz
frequency_ = nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
}
}
2019-04-18 15:52:00 +00:00
bool waybar::modules::Network::associatedOrJoined(struct nlattr **bss) {
2018-08-24 13:32:06 +00:00
if (bss[NL80211_BSS_STATUS] == nullptr) {
return false;
}
auto status = nla_get_u32(bss[NL80211_BSS_STATUS]);
switch (status) {
case NL80211_BSS_STATUS_ASSOCIATED:
case NL80211_BSS_STATUS_IBSS_JOINED:
case NL80211_BSS_STATUS_AUTHENTICATED:
return true;
default:
2018-08-09 14:38:24 +00:00
return false;
}
2018-08-24 13:32:06 +00:00
}
2018-08-09 14:38:24 +00:00
2019-04-18 15:52:00 +00:00
auto waybar::modules::Network::getInfo() -> void {
struct nl_msg *nl_msg = nlmsg_alloc();
2018-08-24 13:32:06 +00:00
if (nl_msg == nullptr) {
2018-08-09 14:38:24 +00:00
return;
}
2019-04-18 15:52:00 +00:00
if (genlmsg_put(
nl_msg, NL_AUTO_PORT, NL_AUTO_SEQ, nl80211_id_, 0, NLM_F_DUMP, NL80211_CMD_GET_SCAN, 0) ==
nullptr ||
nla_put_u32(nl_msg, NL80211_ATTR_IFINDEX, ifid_) < 0) {
2018-12-28 16:09:25 +00:00
nlmsg_free(nl_msg);
return;
2018-08-09 14:38:24 +00:00
}
2019-05-16 09:22:22 +00:00
nl_send_sync(sock_, nl_msg);
}
// https://gist.github.com/rressi/92af77630faf055934c723ce93ae2495
2019-05-22 20:20:50 +00:00
bool waybar::modules::Network::wildcardMatch(const std::string &pattern,
const std::string &text) const {
2019-05-16 09:22:22 +00:00
auto P = int(pattern.size());
auto T = int(text.size());
auto p = 0, fallback_p = -1;
auto t = 0, fallback_t = -1;
while (t < T) {
// Wildcard match:
if (p < P && pattern[p] == '*') {
fallback_p = p++; // starting point after failures
fallback_t = t; // starting point after failures
}
// Simple match:
else if (p < P && (pattern[p] == '?' || pattern[p] == text[t])) {
p++;
t++;
}
// Failure, fall back just after last matched '*':
else if (fallback_p >= 0) {
p = fallback_p + 1; // position just after last matched '*"
t = ++fallback_t; // re-try to match text from here
}
// There were no '*' before, so we fail here:
else {
return false;
}
}
// Consume all '*' at the end of pattern:
while (p < P && pattern[p] == '*') p++;
return p == P;
2018-08-09 14:38:24 +00:00
}