Waybar/src/modules/network.cpp

379 lines
11 KiB
C++
Raw Normal View History

2018-08-09 14:38:24 +00:00
#include "modules/network.hpp"
2018-08-20 12:50:45 +00:00
waybar::modules::Network::Network(const Json::Value& config)
: ALabel(config), family_(AF_INET),
2018-08-16 13:41:09 +00:00
signal_strength_dbm_(0), signal_strength_(0)
2018-08-09 14:38:24 +00:00
{
2018-08-17 12:24:00 +00:00
sock_fd_ = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (sock_fd_ < 0) {
throw std::runtime_error("Can't open network socket");
}
nladdr_.nl_family = AF_NETLINK;
nladdr_.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR;
if (bind(sock_fd_, reinterpret_cast<struct sockaddr *>(&nladdr_),
sizeof(nladdr_)) != 0) {
throw std::runtime_error("Can't bind network socket");
}
if (config_["interface"]) {
ifid_ = if_nametoindex(config_["interface"].asCString());
ifname_ = config_["interface"].asString();
if (ifid_ <= 0) {
throw std::runtime_error("Can't found network interface");
}
} else {
ifid_ = getExternalInterface();
if (ifid_ > 0) {
char ifname[IF_NAMESIZE];
if_indextoname(ifid_, ifname);
ifname_ = ifname;
}
2018-08-16 12:29:41 +00:00
}
label_.set_name("network");
2018-08-19 11:39:57 +00:00
// Trigger first values
2018-08-17 12:24:00 +00:00
getInfo();
update();
2018-08-17 12:24:00 +00:00
thread_ = [this] {
char buf[4096];
uint64_t len = netlinkResponse(sock_fd_, buf, sizeof(buf),
RTMGRP_LINK | RTMGRP_IPV4_IFADDR);
bool need_update = false;
for (auto nh = reinterpret_cast<struct nlmsghdr *>(buf); NLMSG_OK(nh, len);
nh = NLMSG_NEXT(nh, len)) {
if (nh->nlmsg_type == NLMSG_DONE) {
break;
}
if (nh->nlmsg_type == NLMSG_ERROR) {
continue;
}
if (nh->nlmsg_type < RTM_NEWADDR) {
auto rtif = static_cast<struct ifinfomsg *>(NLMSG_DATA(nh));
if (rtif->ifi_index == static_cast<int>(ifid_)) {
need_update = true;
if (!(rtif->ifi_flags & IFF_RUNNING)) {
disconnected();
}
}
}
}
if (ifid_ <= 0 && !config_["interface"]) {
// Need to wait before get external interface
thread_.sleep_for(std::chrono::seconds(1));
ifid_ = getExternalInterface();
if (ifid_ > 0) {
char ifname[IF_NAMESIZE];
if_indextoname(ifid_, ifname);
ifname_ = ifname;
need_update = true;
}
}
if (need_update) {
getInfo();
2018-08-20 12:50:45 +00:00
dp.emit();
2018-08-17 12:24:00 +00:00
}
2018-08-09 14:38:24 +00:00
};
}
2018-08-09 14:38:24 +00:00
2018-08-19 11:39:57 +00:00
waybar::modules::Network::~Network()
{
close(sock_fd_);
}
2018-08-09 14:38:24 +00:00
auto waybar::modules::Network::update() -> void
{
2018-08-17 12:24:00 +00:00
auto format = config_["format"] ? config_["format"].asString() : "{ifname}";
if (ifid_ <= 0) {
format = config_["format-disconnected"]
? config_["format-disconnected"].asString() : format;
label_.get_style_context()->add_class("disconnected");
} else {
if (essid_.empty()) {
format = config_["format-ethernet"]
? config_["format-ethernet"].asString() : format;
} else {
format = config_["format-wifi"]
? config_["format-wifi"].asString() : format;
}
label_.get_style_context()->remove_class("disconnected");
}
2018-08-16 12:29:41 +00:00
label_.set_text(fmt::format(format,
fmt::arg("essid", essid_),
fmt::arg("signaldBm", signal_strength_dbm_),
2018-08-17 12:24:00 +00:00
fmt::arg("signalStrength", signal_strength_),
fmt::arg("ifname", ifname_)
2018-08-09 20:05:15 +00:00
));
2018-08-09 14:38:24 +00:00
}
2018-08-17 12:24:00 +00:00
void waybar::modules::Network::disconnected()
{
essid_.clear();
signal_strength_dbm_ = 0;
signal_strength_ = 0;
ifname_.clear();
ifid_ = -1;
}
// Based on https://gist.github.com/Yawning/c70d804d4b8ae78cc698
int waybar::modules::Network::getExternalInterface()
{
2018-08-20 12:50:45 +00:00
static const uint32_t route_buffer_size = 8192;
2018-08-17 12:24:00 +00:00
struct nlmsghdr *hdr = nullptr;
struct rtmsg *rt = nullptr;
2018-08-20 12:50:45 +00:00
char resp[route_buffer_size] = {0};
2018-08-17 12:24:00 +00:00
int ifidx = -1;
2018-08-20 12:50:45 +00:00
/* Prepare request. */
2018-08-17 12:24:00 +00:00
uint32_t reqlen = NLMSG_SPACE(sizeof(*rt));
2018-08-20 12:50:45 +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. */
if (netlinkRequest(sock_fd_, req, reqlen) < 0) {
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 {
uint64_t len = netlinkResponse(sock_fd_, resp, route_buffer_size);
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);
2018-08-17 12:24:00 +00:00
hdr = NLMSG_NEXT(hdr, len)) {
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);
uint64_t attrlen = RTM_PAYLOAD(hdr);
bool has_gateway = false;
bool has_destination = false;
int temp_idx = -1;
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;
unsigned char c = 0;
size_t dstlen = RTA_PAYLOAD(attr);
if (dstlen != nr_zeroes) {
break;
}
for (uint32_t i = 0; i < dstlen; i += 1) {
c |= *(unsigned char *)(RTA_DATA(attr) + i);
}
has_destination = (c == 0);
break;
}
case RTA_OIF:
/* The output interface index. */
temp_idx = *static_cast<int*>(RTA_DATA(attr));
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) {
ifidx = temp_idx;
break;
}
}
} while (true);
out:
return ifidx;
}
uint64_t waybar::modules::Network::netlinkRequest(int fd, void *req,
uint32_t reqlen, uint32_t groups)
{
struct sockaddr_nl sa = {0};
sa.nl_family = AF_NETLINK;
sa.nl_groups = groups;
struct iovec iov = { req, reqlen };
struct msghdr msg = { &sa, sizeof(sa), &iov, 1, nullptr, 0, 0 };
return sendmsg(fd, &msg, 0);
}
uint64_t waybar::modules::Network::netlinkResponse(int fd, void *resp,
uint32_t resplen, uint32_t groups)
{
uint64_t ret;
struct sockaddr_nl sa = {0};
sa.nl_family = AF_NETLINK;
sa.nl_groups = groups;
struct iovec iov = { resp, resplen };
struct msghdr msg = { &sa, sizeof(sa), &iov, 1, nullptr, 0, 0 };
ret = recvmsg(fd, &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;
}
2018-08-16 12:29:41 +00:00
int waybar::modules::Network::scanCb(struct nl_msg *msg, void *data) {
2018-08-09 14:38:24 +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];
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-16 12:29:41 +00:00
if (nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_attrlen(gnlh, 0), nullptr) < 0) {
2018-08-09 14:38:24 +00:00
return NL_SKIP;
2018-08-16 12:29:41 +00:00
}
if (tb[NL80211_ATTR_BSS] == nullptr) {
2018-08-09 14:38:24 +00:00
return NL_SKIP;
2018-08-16 12:29:41 +00:00
}
if (nla_parse_nested(bss, NL80211_BSS_MAX, tb[NL80211_ATTR_BSS], bss_policy) != 0) {
2018-08-09 14:38:24 +00:00
return NL_SKIP;
2018-08-16 12:29:41 +00:00
}
if (!net->associatedOrJoined(bss)) {
2018-08-09 14:38:24 +00:00
return NL_SKIP;
2018-08-16 12:29:41 +00:00
}
net->parseEssid(bss);
net->parseSignal(bss);
// TODO(someone): parse quality
2018-08-09 14:38:24 +00:00
return NL_SKIP;
}
2018-08-16 12:29:41 +00:00
void waybar::modules::Network::parseEssid(struct nlattr **bss)
2018-08-09 14:38:24 +00:00
{
2018-08-16 12:29:41 +00:00
essid_.clear();
2018-08-09 14:38:24 +00:00
if (bss[NL80211_BSS_INFORMATION_ELEMENTS] != nullptr) {
auto ies =
static_cast<char*>(nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS]));
auto ies_len = nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
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) {
auto essid_begin = ies + hdr_len;
auto essid_end = essid_begin + ies[1];
2018-08-16 12:29:41 +00:00
std::copy(essid_begin, essid_end, std::back_inserter(essid_));
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-09 20:05:15 +00:00
if (bss[NL80211_BSS_SIGNAL_MBM] != nullptr) {
// signalstrength in dBm
2018-08-16 12:29:41 +00:00
signal_strength_dbm_ =
2018-08-09 20:05:15 +00:00
static_cast<int>(nla_get_u32(bss[NL80211_BSS_SIGNAL_MBM])) / 100;
// WiFi-hardware usually operates in the range -90 to -20dBm.
const int hardwareMax = -20;
const int hardwareMin = -90;
2018-08-16 12:29:41 +00:00
signal_strength_ = ((signal_strength_dbm_ - hardwareMin)
/ double{hardwareMax - hardwareMin}) * 100;
2018-08-09 20:05:15 +00:00
}
}
2018-08-16 12:29:41 +00:00
bool waybar::modules::Network::associatedOrJoined(struct nlattr** bss)
2018-08-09 14:38:24 +00:00
{
2018-08-16 12:29:41 +00:00
if (bss[NL80211_BSS_STATUS] == nullptr) {
2018-08-09 14:38:24 +00:00
return false;
2018-08-16 12:29:41 +00:00
}
2018-08-09 14:38:24 +00:00
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:
return false;
}
}
2018-08-16 12:29:41 +00:00
auto waybar::modules::Network::getInfo() -> void
2018-08-09 14:38:24 +00:00
{
struct nl_sock *sk = nl_socket_alloc();
if (genl_connect(sk) != 0) {
nl_socket_free(sk);
return;
}
2018-08-16 12:29:41 +00:00
if (nl_socket_modify_cb(sk, NL_CB_VALID, NL_CB_CUSTOM, scanCb, this) < 0) {
2018-08-09 14:38:24 +00:00
nl_socket_free(sk);
return;
}
const int nl80211_id = genl_ctrl_resolve(sk, "nl80211");
if (nl80211_id < 0) {
nl_socket_free(sk);
return;
}
struct nl_msg *msg = nlmsg_alloc();
2018-08-16 12:29:41 +00:00
if (msg == nullptr) {
2018-08-09 14:38:24 +00:00
nl_socket_free(sk);
return;
}
2018-08-16 12:29:41 +00:00
if (genlmsg_put(msg, NL_AUTO_PORT, NL_AUTO_SEQ, nl80211_id, 0, NLM_F_DUMP,
NL80211_CMD_GET_SCAN, 0) == nullptr
|| nla_put_u32(msg, NL80211_ATTR_IFINDEX, ifid_) < 0) {
2018-08-09 14:38:24 +00:00
nlmsg_free(msg);
return;
}
nl_send_sync(sk, msg);
nl_socket_free(sk);
}