2
* Copyright (C) 2015 Canonical, Ltd.
4
* This program is free software: you can redistribute it and/or modify it
5
* under the terms of the GNU General Public License version 3, as published
6
* by the Free Software Foundation.
8
* This program is distributed in the hope that it will be useful, but
9
* WITHOUT ANY WARRANTY; without even the implied warranties of
10
* MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
11
* PURPOSE. See the GNU General Public License for more details.
13
* You should have received a copy of the GNU General Public License along
14
* with this program. If not, see <http://www.gnu.org/licenses/>.
20
#include <asm/types.h>
21
#include <linux/netlink.h>
22
#include <linux/rtnetlink.h>
23
#include <sys/socket.h>
24
#include <sys/prctl.h>
26
#include <boost/filesystem.hpp>
28
#include <mcs/logger.h>
29
#include <mcs/networkutils.h>
30
#include <mcs/keep_alive.h>
31
#include <mcs/scoped_gobject.h>
33
#include <mcs/config.h>
34
#include <w11tng/config.h>
36
#include "dhcpclient.h"
37
#include "dhcpleaseparser.h"
41
DhcpClient::Ptr DhcpClient::Create(const std::weak_ptr<Delegate> &delegate, const std::string &interface_name) {
42
auto sp = std::shared_ptr<DhcpClient>(new DhcpClient(delegate, interface_name));
47
DhcpClient::DhcpClient(const std::weak_ptr<Delegate> &delegate, const std::string &interface_name) :
49
interface_name_(interface_name) {
51
lease_file_path_ = mcs::Utils::Sprintf("%s/dhclient-%s-%s.leases",
53
boost::filesystem::unique_path().string(),
57
DhcpClient::~DhcpClient() {
58
::unlink(lease_file_path_.c_str());
61
mcs::IpV4Address DhcpClient::LocalAddress() const {
62
return local_address_;
65
mcs::IpV4Address DhcpClient::RemoteAddress() const {
66
return remote_address_;
69
void DhcpClient::Start() {
70
if (!mcs::Utils::CreateFile(lease_file_path_)) {
71
MCS_ERROR("Failed to create database for DHCP leases at %s",
76
monitor_ = FileMonitor::Create(lease_file_path_, shared_from_this());
78
std::vector<std::string> argv = {
79
// Disable background on lease (let dhclient not fork)
83
// Use the temporary lease file we used above to not interfere
84
// with any other parts in the system which are using dhclient
85
// as well. We also want a fresh lease file on every start.
86
"-lf", lease_file_path_,
87
// We only want dhclient to operate on the P2P interface an no other
91
executor_ = ProcessExecutor::Create(kDhcpClientPath, argv, shared_from_this());
94
void DhcpClient::OnProcessTerminated() {
95
if (auto sp = delegate_.lock())
96
sp->OnDhcpTerminated();
99
void DhcpClient::OnFileChanged(const std::string &path) {
100
auto leases = DhcpLeaseParser::FromFile(path);
101
if (leases.size() != 1)
104
auto actual_lease = leases[0];
106
local_address_ = actual_lease.FixedAddress();
107
remote_address_ = actual_lease.Gateway();
109
if (auto sp = delegate_.lock())
110
sp->OnDhcpAddressAssigned(local_address_, remote_address_);
112
} // namespace w11tng