summaryrefslogtreecommitdiff
path: root/ncserver/module/ip.py
blob: 8329c81f2fbc6aaa4c463cc59a1771f06e474980 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
"""
NETCONF for APK Distributions server:
    ietf-ip module

Copyright © 2020 Adélie Software in the Public Benefit, Inc.

Released under the terms of the NCSA license.  See the LICENSE file included
with this source distribution for more information.

SPDX-License-Identifier: NCSA
"""

import logging

from lxml.etree import QName  # pylint: disable=E0611
from netconf import error, util

from ncserver.base.log import log_config_change
from ncserver.base.util import _, node_operation
from ncserver.util import get_nmsa


LOGGER = logging.getLogger(__name__)
"""The object used for logging informational messages."""


M_ABI_VERSION = 1
"""The ABI version of this NETCONF module."""


M_PREFIX = "ip"
"""The XML tag prefix for this module's tags."""


M_NS = "urn:ietf:params:xml:ns:yang:ietf-ip"
"""The XML namespace for this module."""


M_NAME = "ietf-ip"
"""The YANG model name for this module."""


M_REVISION = "2018-02-22"
"""The YANG revision date for this module."""


M_IMPORTS = {
    'ietf-inet-types@2013-07-15': {
        'ns': "urn:ietf:params:xml:ns:yang:ietf-inet-types", 'prefix': "inet"
    },
    'ietf-yang-types@2013-07-15': {
        'ns': "urn:ietf:params:xml:ns:yang:ietf-yang-types", 'prefix': "yang"
    }
}
"""The imported YANG modules for this module."""


M_FEATURES = ('ipv6-privacy-autoconf',)
"""The supported features declared in YANG for this module."""


IF_NS = "urn:ietf:params:xml:ns:yang:ietf-interfaces"
"""The namespace of the ietf-interfaces module."""


M_AUGMENTS = (IF_NS,)
"""The namespaces that this YANG module augments."""


def _get_ifaces(node):
    """Retrieve the /if:interfaces node."""
    ifaces = node.find('{'+IF_NS+'}interfaces')
    if ifaces is None:
        LOGGER.error(_("interfaces node not found: "
                       "This module requires ietf-interfaces to be loaded"))

    return ifaces


def from_bool(value: bool) -> str:
    """Turn a Python bool into an XML bool."""
    return str(value).lower()


def _add_ipv4(iface, getter):
    """Add IPv4 configuration nodes."""
    name = iface.find('{'+IF_NS+'}name').text
    ipv4 = util.subelm(iface, 'ip:ipv4')
    #ipv4.append(util.leaf_elm('ip:enabled',
    #                          from_bool(getter(name, 'ipv4_enabled'))))
    ipv4.append(util.leaf_elm('ip:forwarding',
                              from_bool(getter(name, 'ipv4_forwarding'))))
    v4mtu = getter(name, 'ipv4_mtu')
    if v4mtu is not None:
        ipv4.append(util.leaf_elm('ip:mtu', v4mtu - 28))

    return ipv4


def _add_ipv6(iface, getter):
    """Add IPv6 configuration nodes."""
    name = iface.find('{'+IF_NS+'}name').text
    if getter(name, 'ipv6_enabled') is None:
        return None  # Unset means we don't have IPv6 config at all.

    ipv6 = util.subelm(iface, 'ip:ipv6')
    ipv6.append(util.leaf_elm('ip:enabled',
                              from_bool(getter(name, 'ipv6_enabled'))))

    forwarding = getter(name, 'ipv6_forwarding')
    if forwarding is not None:
        ipv6.append(util.leaf_elm('ip:forwarding', from_bool(forwarding)))

    v6mtu = getter(name, 'ipv6_mtu')
    if v6mtu is not None:
        ipv6.append(util.leaf_elm('ip:mtu', v6mtu))

    dad_xmit = getter(name, 'ipv6_dad_xmit')
    if dad_xmit is not None:
        ipv6.append(util.leaf_elm('ip:dup-addr-detect-transmits', dad_xmit))

    if any((getter(name, 'ipv6_slaac_globaladdr'),
            getter(name, 'ipv6_slaac_tempaddr'))):
        autoconf = util.subelm(ipv6, 'ip:autoconf')
        autoconf.append(util.leaf_elm('ip:create-global-addresses',
                                      from_bool(
                                          getter(name, 'ipv6_slaac_globaladdr')
                                      )))
        autoconf.append(util.leaf_elm('ip:create-temporary-addresses',
                                      from_bool(
                                          getter(name, 'ipv6_slaac_tempaddr')
                                      )))
        autoconf.append(util.leaf_elm('ip:temporary-valid-lifetime',
                                      getter(name, 'ipv6_slaac_validlft')))
        autoconf.append(util.leaf_elm('ip:temporary-preferred-lifetime',
                                      getter(name, 'ipv6_slaac_preflft')))

    return ipv6


def running(node):
    """Retrieve the IP configuration for this device."""
    ifaces = _get_ifaces(node)
    nmsa = get_nmsa()

    if None in (ifaces, nmsa):
        # We can't retrieve configuration unless both the ietf-interfaces and
        # the NMSA module is loaded.
        return

    for iface in ifaces.iterchildren():
        name = iface.find('{'+IF_NS+'}name').text

        # IPv4
        ipv4 = _add_ipv4(iface, nmsa.get_param)
        for address in nmsa.list_addresses(name):
            # Only IPv4 addresses count.
            if '.' not in address:
                continue

            ipaddr, subnet = address.split('/')

            addr = util.subelm(ipv4, 'ip:address')
            addr.append(util.leaf_elm('ip:ip', ipaddr))
            addr.append(util.leaf_elm('ip:prefix-length', subnet))
        # No neighbor support.

        # IPv6
        ipv6 = _add_ipv6(iface, nmsa.get_param)
        if not ipv6:
            continue

        for address in nmsa.list_addresses(name):
            # Only IPv6 addesses count.
            if ':' not in address:
                continue

            ipaddr, length = address.split('/')

            addr = util.subelm(ipv6, 'ip:address')
            addr.append(util.leaf_elm('ip:ip', ipaddr))
            addr.append(util.leaf_elm('ip:prefix-length', length))
        # No neighbor support.


def operational(node):
    """Retrieve the IP state for this device."""
    ifaces = _get_ifaces(node)
    nmsa = get_nmsa()

    if None in (ifaces, nmsa):
        # We can't retrieve configuration unless both the ietf-interfaces and
        # the NMSA module is loaded.
        return

    for iface in ifaces.iterchildren():
        # IPv4
        _add_ipv4(iface, nmsa.curr_param)
        # IPv6
        _add_ipv6(iface, nmsa.curr_param)


def _edit_param(iface: str, param: str, operation: str, rpc, node):
    """Edit an NMSA-controlled parameter."""
    nmsa = get_nmsa()
    value = nmsa.get_param(iface, param)

    if operation == 'create' and value is not None:
        raise error.DataExistsAppError(rpc)
    if operation == 'delete' and value is None:
        raise error.DataMissingAppError(rpc)

    if operation in ('delete', 'remove'):
        nmsa.unset_param(iface, param)
        return

    if operation not in ('create', 'merge', 'replace'):
        raise error.OperationNotSupportedAppError(rpc)

    if node.text in ('true', 'false'):
        nmsa.set_param(iface, param, node.text == 'true')
    else:
        nmsa.set_param(iface, param, node.text)


def _clear_ipv4(iface: str):
    """Remove all IPv4 configuration from a given interface."""
    nmsa = get_nmsa()

    nmsa.set_param(iface, 'ipv4_enabled', False)
    nmsa.unset_param(iface, 'ipv4_forwarding')
    nmsa.unset_param(iface, 'ipv4_mtu')


def _edit_ipv4(session, rpc, node, def_op, iface: str):
    """Edit IPv4 configuration for a given interface."""
    _params = {'enabled': 'ipv4_enabled', 'forwarding': 'ipv4_forwarding',
               'mtu': 'ipv4_mtu'}

    operation = node_operation(node, def_op)
    if operation in ('delete', 'remove'):
        log_config_change(session, "[ietf-ip %s]" % iface,
                          "removing IPv4 configuration")

        _clear_ipv4(iface)
        return

    if operation not in ('create', 'merge', 'replace'):
        raise error.OperationNotSupportedAppError(rpc)

    for xparam in node:
        operation = node_operation(xparam, operation)
        qparam = QName(xparam.tag)
        if qparam.localname in _params.keys():
            param = _params[qparam.localname]
            log_config_change(session, "[ietf-ip %s]" % iface,
                              "IPv4 %s: -> %s" % (param, node.text))
            _edit_param(iface, param, operation, rpc, node)
        elif qparam.localname == 'address':
            # Oh no.
            raise NotImplementedError
        elif qparam.localname == 'neighbor':
            # Oh *no*!
            raise NotImplementedError
        else:
            raise error.UnknownElementAppError(rpc, xparam)


def _clear_ipv6(iface: str):
    """Remove all IPv6 configuration from a given interface."""
    nmsa = get_nmsa()

    nmsa.set_param(iface, 'ipv6_enabled', False)
    for param in ('ipv6_forwarding', 'ipv6_mtu', 'ipv6_dad_xmit',
                  'ipv6_slaac_globaladdr', 'ipv6_slaac_tempaddr',
                  'ipv6_slaac_validlft', 'ipv6_slaac_preflft'):
        nmsa.unset_param(iface, param)


def _clear_slaac(iface: str):
    """Remove all SLAAC configuration from a given interface."""
    nmsa = get_nmsa()

    for param in ('ipv6_slaac_globaladdr', 'ipv6_slaac_tempaddr',
                  'ipv6_slaac_validlft', 'ipv6_slaac_preflft'):
        nmsa.unset_param(iface, param)


def _edit_slaac(session, rpc, node, def_op, iface: str):
    """Edit SLAAC configuration for a given interface."""
    _params = {'create-global-addresses': 'ipv6_slaac_globaladdr',
               'create-temporary-addresses': 'ipv6_slaac_tempaddr',
               'temporary-valid-lifetime': 'ipv6_slaac_validlft',
               'temporary-preferred-lifetime': 'ipv6_slaac_preflft'}

    operation = node_operation(node, def_op)
    if operation in ('delete', 'remove'):
        log_config_change(session, "[ietf-ip %s]" % iface,
                          "removing IPv6 SLAAC configuration")
        _clear_slaac(iface)
        return

    if operation not in ('create', 'merge', 'replace'):
        raise error.OperationNotSupportedAppError(rpc)

    for param in node:
        p_name = QName(param.tag).localname
        if p_name not in _params.keys():
            raise error.UnknownElementAppError(rpc, param)

        p_op = node_operation(param, operation)
        _edit_param(iface, _params[p_name], p_op, rpc, param)


def _edit_ipv6(session, rpc, node, def_op, iface: str):
    """Edit IPv6 configuration for a given interface."""
    _params = {'enabled': 'ipv6_enabled', 'forwarding': 'ipv6_forwarding',
               'mtu': 'ipv6_mtu', 'dup-addr-detect-transmits': 'ipv6_dad_xmit'}

    operation = node_operation(node, def_op)
    if operation in ('delete', 'remove'):
        log_config_change(session, "[ietf-ip %s]" % iface,
                          "removing IPv6 configuration")

        _clear_ipv6(iface)
        return

    if operation not in ('create', 'merge', 'replace'):
        raise error.OperationNotSupportedAppError(rpc)

    for xparam in node:
        p_op = node_operation(xparam, operation)
        qparam = QName(xparam.tag)
        if qparam.localname in _params.keys():
            param = _params[qparam.localname]
            log_config_change(session, "[ietf-ip %s]" % iface,
                              "IPv6 %s: -> %s" % (param, node.text))
            _edit_param(iface, param, p_op, rpc, node)
        elif qparam.localname == 'address':
            # Oh no.
            raise NotImplementedError
        elif qparam.localname == 'neighbor':
            # Oh *no*!
            raise NotImplementedError
        elif qparam.localname == 'autoconf':
            # Configure SLAAC parameters.
            _edit_slaac(session, rpc, node, def_op, iface)
        else:
            raise error.UnknownElementAppError(rpc, xparam)


def edit(session, rpc, node, def_op):
    """Edit the IP configuration for this device."""
    methods = {'ipv4': _edit_ipv4, 'ipv6': _edit_ipv6}

    nmsa = get_nmsa()
    if nmsa is None:
        raise error.OperationNotSupportedAppError(rpc)

    for interface in node:
        if QName(interface.tag).localname != 'interface' or\
           QName(interface.tag).namespace != IF_NS:
            continue  # Ignore unknown tags given to us.

        name_node = interface.find('{'+IF_NS+'}name')
        if name_node is None:
            raise error.MissingElementAppError(rpc, interface)
        iface = name_node.text

        operation = node_operation(interface, def_op)
        if operation in ('delete', 'remove'):
            # ietf-interfaces already removed the configuration for us.
            continue

        for conf in interface:
            if QName(conf.tag).namespace == M_NS:
                name = QName(conf.tag).localname
                if name in methods:
                    methods[name](session, rpc, conf, operation, iface)
                else:
                    raise error.UnknownElementAppError(rpc, conf)
            else:
                continue