gitee.com/mysnapcore/mysnapd@v0.1.0/netutil/metered.go (about) 1 // -*- Mode: Go; indent-tabs-mode: t -*- 2 3 /* 4 * Copyright (C) 2018 Canonical Ltd 5 * 6 * This program is free software: you can redistribute it and/or modify 7 * it under the terms of the GNU General Public License version 3 as 8 * published by the Free Software Foundation. 9 * 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * 15 * You should have received a copy of the GNU General Public License 16 * along with this program. If not, see <http://www.gnu.org/licenses/>. 17 * 18 */ 19 20 package netutil 21 22 import ( 23 "fmt" 24 25 "github.com/godbus/dbus" 26 27 "gitee.com/mysnapcore/mysnapd/logger" 28 ) 29 30 const ( 31 // https://developer.gnome.org/NetworkManager/stable/nm-dbus-types.html#NMMetered 32 NetworkManagerMeteredUnknown = 0 33 NetworkManagerMeteredYes = 1 34 NetworkManagerMeteredNo = 2 35 NetworkManagerMeteredGuessYes = 3 36 NetworkManagerMeteredGuessNo = 4 37 ) 38 39 // IsOnMeteredConnection checks whether the current default network connection 40 // is metered. If the state can not be determined, returns false and an error. 41 func IsOnMeteredConnection() (bool, error) { 42 // obtain a shared connection to system bus, no need to close it 43 conn, err := dbus.SystemBus() 44 if err != nil { 45 return false, fmt.Errorf("cannot connect to system bus: %v", err) 46 } 47 48 return isNMOnMetered(conn) 49 } 50 51 func isNMOnMetered(conn *dbus.Conn) (bool, error) { 52 nmObj := conn.Object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager") 53 // https://developer.gnome.org/NetworkManager/stable/gdbus-org.freedesktop.NetworkManager.html 54 dbusV, err := nmObj.GetProperty("org.freedesktop.NetworkManager.Metered") 55 if err != nil { 56 return false, err 57 } 58 v, ok := dbusV.Value().(uint32) 59 if !ok { 60 return false, fmt.Errorf("network manager returned invalid value for metering verification: %s", dbusV) 61 } 62 logger.Debugf("metered state reported by NetworkManager: %s", dbusV) 63 64 return v == NetworkManagerMeteredGuessYes || v == NetworkManagerMeteredYes, nil 65 }