blob: ab6da4066855344a70f0b1e8ccbe2759fc63b7e4 [file] [log] [blame]
Lorenz Brun56a7ae62020-10-29 11:03:30 +01001// Copyright 2020 The Monogon Project Authors.
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17package dhcp4c
18
19import (
20 "net"
21 "time"
22
23 "github.com/insomniacslk/dhcp/dhcpv4"
24)
25
26// Lease represents a DHCPv4 lease. It only consists of an IP, an expiration timestamp and options as all other
27// relevant parts of the message have been normalized into their respective options. It also contains some smart
28// getters for commonly-used options which extract only valid information from options.
29type Lease struct {
30 AssignedIP net.IP
31 ExpiresAt time.Time
32 Options dhcpv4.Options
33}
34
35// SubnetMask returns the SubnetMask option or the default mask if not set or invalid.
36// It returns nil if the lease is nil.
37func (l *Lease) SubnetMask() net.IPMask {
38 if l == nil {
39 return nil
40 }
41 mask := net.IPMask(dhcpv4.GetIP(dhcpv4.OptionSubnetMask, l.Options))
42 if _, bits := mask.Size(); bits != 32 { // If given mask is not valid, use the default mask
43 mask = l.AssignedIP.DefaultMask()
44 }
45 return mask
46}
47
48// IPNet returns an IPNet from the assigned IP and subnet mask.
49// It returns nil if the lease is nil.
50func (l *Lease) IPNet() *net.IPNet {
51 if l == nil {
52 return nil
53 }
54 return &net.IPNet{
55 IP: l.AssignedIP,
56 Mask: l.SubnetMask(),
57 }
58}
59
60// Router returns the first valid router from the DHCP router option or nil if none such exists.
61// It returns nil if the lease is nil.
62func (l *Lease) Router() net.IP {
63 if l == nil {
64 return nil
65 }
66 routers := dhcpv4.GetIPs(dhcpv4.OptionRouter, l.Options)
67 for _, r := range routers {
68 if r.IsGlobalUnicast() || r.IsLinkLocalUnicast() {
69 return r
70 }
71 }
72 // No (valid) router found
73 return nil
74}