tools: ynl: prepare for wireguard
Subsystems (3)
cover tools: ynl: prepare for wireguard
This series contains the last batch of YNL changes to support the wireguard YNL conversion.
The next batch has been posted as an RFC series here:
https://lore.kernel.org/netdev/[email protected]/
Asbjørn Sloth Tønnesen (11):
tools: ynl-gen: allow overriding name-prefix for constants
tools: ynl-gen: generate nested array policies
tools: ynl-gen: add sub-type check
tools: ynl-gen: define count iterator in print_dump()
tools: ynl-gen: define nlattr *array in a block scope
tools: ynl-gen: don't validate nested array attribute types
tools: ynl-gen: rename TypeArrayNest to TypeIndexedArray
tools: ynl: move nest packing to a helper function
tools: ynl: encode indexed-array
tools: ynl: decode hex input
tools: ynl: add ipv4-or-v6 display hint
Documentation/netlink/genetlink-legacy.yaml | 2 +- tools/net/ynl/pyynl/lib/ynl.py | 36 +++++++++++++++--- tools/net/ynl/pyynl/ynl_gen_c.py | 42 ++++++++++++++------- 3 files changed, 59 insertions(+), 21 deletions(-)
Signature · 1 line
2.51.0
PATCH 1/11 tools: ynl-gen: allow overriding name-prefix for constants
Allow using custom name-prefix with constants,
just like it is for enum and flags declarations.
This is needed for generating WG_KEY_LEN ininclude/uapi/linux/wireguard.h from a spec.
--- tools/net/ynl/pyynl/ynl_gen_c.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
tools/net/ynl/pyynl/ynl_gen_c.py +2 -1
@@ -3211,8 +3211,9 @@ def render_uapi(family, cw): cw.block_end(line=';') cw.nl() elif const['type'] == 'const': + name_pfx = const.get('name-prefix', f"{family.ident_name}-") defines.append([c_upper(family.get('c-define-name', - f"{family.ident_name}-{const['name']}")), + f"{name_pfx}{const['name']}")), const['value']]) if defines:
Signature · 1 line
2.51.0
Re: [PATCH net-next 01/11] tools: ynl-gen: allow overriding name-prefix for constants
Quoted 7 lines · Asbjørn Sloth Tønnesen
Allow using custom name-prefix with constants,
just like it is for enum and flags declarations.This is needed for generating
WG_KEY_LENininclude/uapi/linux/wireguard.hfrom a spec.Signed-off-by Asbjørn Sloth Tønnesen <[email protected]>
Re: [PATCH net-next 01/11] tools: ynl-gen: allow overriding name-prefix for constants
In reply to Asbjørn Sloth TønnesenQuoted 5 lines · On Thu, 4 Sep 2025 22:01:24 +0000 Asbjørn Sloth Tønnesen wrote:
Allow using custom name-prefix with constants,
just like it is for enum and flags declarations.This is needed for generating
WG_KEY_LENininclude/uapi/linux/wireguard.hfrom a spec.
Re: [PATCH net-next 01/11] tools: ynl-gen: allow overriding name-prefix for constants
In reply to Asbjørn Sloth TønnesenQuoted 16 lines · Asbjørn Sloth Tønnesen
Allow using custom name-prefix with constants,
just like it is for enum and flags declarations.This is needed for generating
WG_KEY_LENininclude/uapi/linux/wireguard.hfrom a spec.Signed-off-by Asbjørn Sloth Tønnesen <[email protected]>--- tools/net/ynl/pyynl/ynl_gen_c.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)tools/net/ynl/pyynl/ynl_gen_c.py +0
-0
tools/net/ynl/pyynl/ynl_gen_c.py def render_uapi(family, cw): · line 3214
Quoted 4 lines
tools/net/ynl/pyynl/ynl_gen_c.py +1
-0@@ -3211,8 +3211,9 @@ def render_uapi(family, cw): cw.block_end(line=';') cw.nl() elif const['type'] == 'const': + name_pfx = const.get('name-prefix', f"{family.ident_name}-")
Previously we always used "{family.ident_name}-", but now we get the name-prefix and use that, falling back to the default if it doesn't exist. Good.
Quoted 6 lines
tools/net/ynl/pyynl/ynl_gen_c.py +1
-1defines.append([c_upper(family.get('c-define-name', - f"{family.ident_name}-{const['name']}")), + f"{name_pfx}{const['name']}")), const['value']]) if defines:
PATCH 2/11 tools: ynl-gen: generate nested array policies
In reply to Asbjørn Sloth TønnesenThis patch adds support for NLA_POLICY_NESTED_ARRAY() policies.
Example spec (from future wireguard.yaml):
-
name: wgpeer
attributes:
-
name: allowedips
type: indexed-array
sub-type: nest
nested-attributes: wgallowedipyields NLA_POLICY_NESTED_ARRAY(wireguard_wgallowedip_nl_policy).
This doesn't change any currently generated code, as it isn't used in any specs currently used for generating code.
--- tools/net/ynl/pyynl/ynl_gen_c.py | 5 +++++ 1 file changed, 5 insertions(+)
tools/net/ynl/pyynl/ynl_gen_c.py +5 -0
@@ -816,6 +816,11 @@ class TypeArrayNest(Type): f'unsigned int n_{self.c_name}'] return super().arg_member(ri) + def _attr_policy(self, policy): + if self.attr['sub-type'] == 'nest': + return f'NLA_POLICY_NESTED_ARRAY({self.nested_render_name}_nl_policy)' + return super()._attr_policy(policy) + def _attr_typol(self): if self.attr['sub-type'] in scalars: return f'.type = YNL_PT_U{c_upper(self.sub_type[1:])}, '
Signature · 1 line
2.51.0
Re: [PATCH net-next 02/11] tools: ynl-gen: generate nested array policies
Quoted 12 lines · Asbjørn Sloth Tønnesen
This patch adds support for
NLA_POLICY_NESTED_ARRAY()policies.Example spec (from future
wireguard.yaml):
-
name: wgpeer
attributes:- name: allowedips type: indexed-array sub-type: nest nested-attributes: wgallowedip
Quoted 6 lines
yields
NLA_POLICY_NESTED_ARRAY(wireguard_wgallowedip_nl_policy).This doesn't change any currently generated code, as it isn't used in any specs currently used for generating code.
Signed-off-by Asbjørn Sloth Tønnesen <[email protected]>
Re: [PATCH net-next 02/11] tools: ynl-gen: generate nested array policies
In reply to Asbjørn Sloth TønnesenQuoted 12 lines · On Thu, 4 Sep 2025 22:01:25 +0000 Asbjørn Sloth Tønnesen wrote:
This patch adds support for
NLA_POLICY_NESTED_ARRAY()policies.Example spec (from future
wireguard.yaml):
-
name: wgpeer
attributes:- name: allowedips type: indexed-array sub-type: nest nested-attributes: wgallowedip
Quoted 4 lines
yields
NLA_POLICY_NESTED_ARRAY(wireguard_wgallowedip_nl_policy).This doesn't change any currently generated code, as it isn't used in any specs currently used for generating code.
Re: [PATCH net-next 02/11] tools: ynl-gen: generate nested array policies
In reply to Asbjørn Sloth TønnesenQuoted 12 lines · Asbjørn Sloth Tønnesen
This patch adds support for
NLA_POLICY_NESTED_ARRAY()policies.Example spec (from future
wireguard.yaml):
-
name: wgpeer
attributes:- name: allowedips type: indexed-array sub-type: nest nested-attributes: wgallowedip
Quoted 7 lines
yields
NLA_POLICY_NESTED_ARRAY(wireguard_wgallowedip_nl_policy).This doesn't change any currently generated code, as it isn't used in any specs currently used for generating code.
Signed-off-by Asbjørn Sloth Tønnesen <[email protected]>---
Is this keyed of off the sub-type? Does you mean that all the existing uses of 'sub-type: nest' don't generate code today? Or that this _attr_policy implementation is not called yet?
I checked and we have quite a number of uses:
Quoted 28 lines
$ rg 'sub-type: nest' Documentation/netlink/specs/nlctrl.yaml 69: sub-type: nest 74: sub-type: nest
Documentation/netlink/specs/tc.yaml2045: sub-type: nest 2065: sub-type: nest 2190: sub-type: nest 2304: sub-type: nest 2494: sub-type: nest 3021: sub-type: nest 3181: sub-type: nest 3567: sub-type: nest 3799: sub-type: nest
Documentation/netlink/specs/rt-link.yaml
2203: sub-type: nest
Documentation/netlink/specs/nl80211.yaml
610: sub-type: nest1309: sub-type: nest 1314: sub-type: nest 1337: sub-type: nest 1420: sub-type: nest 1476: sub-type: nest 1615: sub-type: nest
Re: [PATCH net-next 02/11] tools: ynl-gen: generate nested array policies
Quoted 18 lines · Jacob Keller
Quoted 17 lines · Asbjørn Sloth Tønnesen
This patch adds support for
NLA_POLICY_NESTED_ARRAY()policies.Example spec (from future
wireguard.yaml):
-
name: wgpeer
attributes:- name: allowedips type: indexed-array sub-type: nest nested-attributes: wgallowedipyields
NLA_POLICY_NESTED_ARRAY(wireguard_wgallowedip_nl_policy).This doesn't change any currently generated code, as it isn't used in any specs currently used for generating code.
Quoted 6 lines
Quoted 2 lines
Signed-off-by Asbjørn Sloth Tønnesen <[email protected]>---
Is this keyed of off the sub-type? Does you mean that all the existing uses of 'sub-type: nest' don't generate code today? Or that this
_attr_policyimplementation is not called yet?
Thanks for the reviews. Yeah, it is a careful wording, because we have specs matching it, but there aren't any source files that triggers ynl-gen to generate code based on those specs.
Therefore this patch, doesn't result in any code changes when running:
$ ./tools/net/ynl/ynl-regen.sh -f
Actually ynl-gen generates a fictive "{ .type = NLA_INDEXED_ARRAY, }" policy, without this patch, leading to a build failure.
Quoted 11 lines
I checked and we have quite a number of uses:
Quoted 9 lines
$ rg 'sub-type: nest' Documentation/netlink/specs/nlctrl.yaml [..] Documentation/netlink/specs/tc.yaml [..] Documentation/netlink/specs/rt-link.yaml [..] Documentation/netlink/specs/nl80211.yaml [..]
None of those currently have a generated netlink policy.
These are the netlink policies currently generated by ynl-gen:
$ git grep -h -B1 'YNL-GEN kernel source' | grep '^/\*[^ ]' /* Documentation/netlink/specs/dpll.yaml */ /* Documentation/netlink/specs/ovpn.yaml */ /* Documentation/netlink/specs/team.yaml */ /* Documentation/netlink/specs/lockd.yaml */ /* Documentation/netlink/specs/nfsd.yaml */ /* Documentation/netlink/specs/netdev.yaml */ /* Documentation/netlink/specs/devlink.yaml */ /* Documentation/netlink/specs/handshake.yaml */ /* Documentation/netlink/specs/fou.yaml */ /* Documentation/netlink/specs/mptcp_pm.yaml */ /* Documentation/netlink/specs/net_shaper.yaml */
Johannes introduced NLA_NESTED_ARRAY and the NLA_POLICY_NESTED_ARRAY() macro in commit 1501d13596b9 for use in nl80211, and it's therefore used in net/wireless/nl80211.c, but outside of that the macro is only sparsely adopted (only by mac80211_hwsim.c and nf_tables_api.c).
Wireguard adopts the macro in this RFC patch:
https://lore.kernel.org/netdev/[email protected]/
Re: [PATCH net-next 02/11] tools: ynl-gen: generate nested array policies
Quoted 8 lines · Asbjørn Sloth Tønnesen
Johannes introduced
NLA_NESTED_ARRAYand theNLA_POLICY_NESTED_ARRAY()macro in commit1501d13596b9for use in nl80211, and it's therefore used innet/wireless/nl80211.c, but outside of that the macro is only sparsely adopted (only bymac80211_hwsim.candnf_tables_api.c).Wireguard adopts the macro in this RFC patch:
https://lore.kernel.org/netdev/[email protected]/
I think the general consensus now is that preference should be towards arrays being expressed by giving the attribute holding the array multiple times, i.e. each occurrence of an attribute holds a single entry of the array:
[header][type1:a1][type2:b][type1:a2][type1:a3]
resulting in an array
[a1, a2, a3] and a separate value "b",
rather than a nested array:
[header][type1:[1:a1][2:a2][3:a3]][type2:b]
Of course if each entry has multiple values, then you'd still need nesting:
[header][type1:[subtype1:x1][subtype2:x2]][type1:[subtype1:y1][subtype2:y2]]
would be an array
[[x1, x2], [y1, y2]].
I can't get rid of the nested array types in nl80211 though, of course.
I'm not sure the nl80211 ynl code was ever merged, but it wasn't authoritative anyway, just for some limited userspace generation, so I'm not sure the whole ynl handling this is needed at all?
johannes
Re: [PATCH net-next 02/11] tools: ynl-gen: generate nested array policies
Quoted 25 lines · Johannes Berg
Quoted 7 lines · Asbjørn Sloth Tønnesen
Johannes introduced
NLA_NESTED_ARRAYand theNLA_POLICY_NESTED_ARRAY()macro in commit1501d13596b9for use in nl80211, and it's therefore used innet/wireless/nl80211.c, but outside of that the macro is only sparsely adopted (only bymac80211_hwsim.candnf_tables_api.c).Wireguard adopts the macro in this RFC patch:
https://lore.kernel.org/netdev/[email protected]/I think the general consensus now is that preference should be towards arrays being expressed by giving the attribute holding the array multiple times, i.e. each occurrence of an attribute holds a single entry of the array:
[header][type1:a1][type2:b][type1:a2][type1:a3]
resulting in an array
[a1, a2, a3] and a separate value "b",
rather than a nested array:
[header][type1:[1:a1][2:a2][3:a3]][type2:b]
Quoted 8 lines
Of course if each entry has multiple values, then you'd still need nesting:
[header][type1:[subtype1:x1][subtype2:x2]][type1:[subtype1:y1][subtype2:y2]]
would be an array
[[x1, x2], [y1, y2]].
Thank you for the consensus write up. Should we prohibit indexed-array with sub-type nest for families with a genetlink protocol?
It is currently only used in families with a netlink-raw or genetlink-legacy protocol.
Quoted 1 line
I can't get rid of the nested array types in nl80211 though, of course.
Wireguard is already in the same boat. It is not using the term, nor the policy, but it is doing the validation in the handler through, so it can adopt a NLA_POLICY_NESTED_ARRAY() policy, instead of a plain '{ .type = NLA_NESTED }'.
Comments on the protocol in include/uapi/linux/wireguard.h:
Quoted 7 lines
WGDEVICE_A_PEERS:NLA_NESTED
0:NLA_NESTED
WGPEER_A_PUBLIC_KEY:NLA_EXACT_LEN, lenWG_KEY_LEN[..]
0:NLA_NESTED......
Given that, as Jacob pointed out, there are more families with nested arrays in their YNL spec, than those using NLA_NESTED_ARRAY, then it appears that there are more families already in the boat.
Re: [PATCH net-next 02/11] tools: ynl-gen: generate nested array policies
Quoted 5 lines · Asbjørn Sloth Tønnesen
Thank you for the consensus write up. Should we prohibit indexed-array with sub-type nest for families with a genetlink protocol?
It is currently only used in families with a netlink-raw or genetlink-legacy protocol.
I have no strong opinion on that, but I guess maybe so? At least print out a warning for anyone who's trying to add such a new thing perhaps, so that new stuff that isn't just a port (to ynl) or annotation of existing APIs doesn't add it.
Quoted 3 lines
Quoted 1 line
I can't get rid of the nested array types in nl80211 though, of course.
Wireguard is already in the same boat. [...]
Oh, sorry. I didn't look at the linked patch and thought it was adding such a new thing. Looking now, I see it just makes the policy validate it instead of (only) doing it in the code. (FWIW, in the code you could then also set the policy argument for nla_parse_nested() calls to NULL.)
Quoted 3 lines
Given that, as Jacob pointed out, there are more families with nested arrays in their YNL spec, than those using
NLA_NESTED_ARRAY, then it appears that there are more families already in the boat.
Right.
johannes
Re: [PATCH net-next 02/11] tools: ynl-gen: generate nested array policies
In reply to Asbjørn Sloth TønnesenQuoted 24 lines · Asbjørn Sloth Tønnesen
CC JohannesQuoted 21 lines · Jacob Keller
Quoted 19 lines · Asbjørn Sloth Tønnesen
This patch adds support for
NLA_POLICY_NESTED_ARRAY()policies.Example spec (from future
wireguard.yaml):
-
name: wgpeer
attributes:- name: allowedips type: indexed-array sub-type: nest nested-attributes: wgallowedipyields
NLA_POLICY_NESTED_ARRAY(wireguard_wgallowedip_nl_policy).This doesn't change any currently generated code, as it isn't used in any specs currently used for generating code.
Signed-off-by Asbjørn Sloth Tønnesen <[email protected]>---
Quoted 8 lines
Quoted 3 lines
Is this keyed of off the sub-type? Does you mean that all the existing uses of 'sub-type: nest' don't generate code today? Or that this
_attr_policyimplementation is not called yet?Thanks for the reviews. Yeah, it is a careful wording, because we have specs matching it, but there aren't any source files that triggers ynl-gen to generate code based on those specs.
Ok. That's what I thought and just wanted to be certain, since I saw several uses in the code. Thanks for explaining!
PATCH 3/11 tools: ynl-gen: add sub-type check
In reply to Asbjørn Sloth TønnesenAdd a check to verify that the sub-type is "nest", and throw an exception if no policy could be generated, as a guard to prevent against generating a bad policy.
This is a trivial patch with no behavioural changes intended.
--- tools/net/ynl/pyynl/ynl_gen_c.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
tools/net/ynl/pyynl/ynl_gen_c.py +3 -1
@@ -826,8 +826,10 @@ class TypeArrayNest(Type): return f'.type = YNL_PT_U{c_upper(self.sub_type[1:])}, ' elif self.attr['sub-type'] == 'binary' and 'exact-len' in self.checks: return f'.type = YNL_PT_BINARY, .len = {self.checks["exact-len"]}, ' - else: + elif self.attr['sub-type'] == 'nest': return f'.type = YNL_PT_NEST, .nest = &{self.nested_render_name}_nest, ' + else: + raise Exception(f"Typol for ArrayNest sub-type {self.attr['sub-type']} not supported, yet") def _attr_get(self, ri, var): local_vars = ['const struct nlattr *attr2;']
Signature · 1 line
2.51.0
Re: [PATCH net-next 03/11] tools: ynl-gen: add sub-type check
Quoted 7 lines · Asbjørn Sloth Tønnesen
Add a check to verify that the sub-type is "nest", and throw an exception if no policy could be generated, as a guard to prevent against generating a bad policy.
This is a trivial patch with no behavioural changes intended.
Signed-off-by Asbjørn Sloth Tønnesen <[email protected]>
Re: [PATCH net-next 03/11] tools: ynl-gen: add sub-type check
In reply to Asbjørn Sloth TønnesenQuoted 5 lines · On Thu, 4 Sep 2025 22:01:26 +0000 Asbjørn Sloth Tønnesen wrote:
Add a check to verify that the sub-type is "nest", and throw an exception if no policy could be generated, as a guard to prevent against generating a bad policy.
This is a trivial patch with no behavioural changes intended.
I _think_ the expectation was that one of the other methods which validate the types more thoroughly has to be called if this one is. But either way:
Re: [PATCH net-next 03/11] tools: ynl-gen: add sub-type check
In reply to Asbjørn Sloth TønnesenQuoted 7 lines · Asbjørn Sloth Tønnesen
Add a check to verify that the sub-type is "nest", and throw an exception if no policy could be generated, as a guard to prevent against generating a bad policy.
This is a trivial patch with no behavioural changes intended.
Quoted 1 line
Signed-off-by Asbjørn Sloth Tønnesen <[email protected]>---
Quoted 19 lines
tools/net/ynl/pyynl/ynl_gen_c.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)tools/net/ynl/pyynl/ynl_gen_c.py +3
-1@@ -826,8 +826,10 @@ class TypeArrayNest(Type): return f'.type = YNL_PT_U{c_upper(self.sub_type[1:])}, ' elif self.attr['sub-type'] == 'binary' and 'exact-len' in self.checks: return f'.type = YNL_PT_BINARY, .len = {self.checks["exact-len"]}, ' - else: + elif self.attr['sub-type'] == 'nest': return f'.type = YNL_PT_NEST, .nest = &{self.nested_render_name}_nest, ' + else: + raise Exception(f"Typol for ArrayNest sub-type {self.attr['sub-type']} not supported, yet") def _attr_get(self, ri, var): local_vars = ['const struct nlattr *attr2;']
PATCH 4/11 tools: ynl-gen: define count iterator in print_dump()
In reply to Asbjørn Sloth TønnesenIn wireguard_get_device_dump(), as generated by print_dump(), it didn't generate a declaration of unsigned int i:
$ make -C tools/net/ynl/generated wireguard-user.o
-e CC wireguard-user.o
wireguard-user.c: In function ‘wireguard_get_device_dump’:
wireguard-user.c:502:22: error: ‘i’ undeclared (first use in this fn)
502 | for (i = 0; i < req->_count.peers; i++)
| ^Copy the logic from print_req() as it correctly generated the iterator in wireguard_set_device().
--- tools/net/ynl/pyynl/ynl_gen_c.py | 5 +++++ 1 file changed, 5 insertions(+)
tools/net/ynl/pyynl/ynl_gen_c.py +5 -0
@@ -2425,6 +2425,11 @@ def print_dump(ri): local_vars += ['size_t hdr_len;', 'void *hdr;'] + for _, attr in ri.struct['request'].member_list(): + if attr.presence_type() == 'count': + local_vars += ['unsigned int i;'] + break + ri.cw.write_func_lvar(local_vars) ri.cw.p('yds.yarg.ys = ys;')
Signature · 1 line
2.51.0
Re: [PATCH net-next 04/11] tools: ynl-gen: define count iterator in print_dump()
Quoted 10 lines · Asbjørn Sloth Tønnesen
In
wireguard_get_device_dump(), as generated byprint_dump(), it didn't generate a declaration ofunsigned int i:$ make -C tools/net/ynl/generated wireguard-user.o -e CC wireguard-user.o wireguard-user.c: In function ‘wireguard_get_device_dump’: wireguard-user.c:502:22: error: ‘i’ undeclared (first use in this fn) 502 | for (i = 0; i < req->_count.peers; i++) | ^
Quoted 4 lines
Copy the logic from
print_req()as it correctly generated the iterator inwireguard_set_device().Signed-off-by Asbjørn Sloth Tønnesen <[email protected]>
Re: [PATCH net-next 04/11] tools: ynl-gen: define count iterator in print_dump()
In reply to Asbjørn Sloth TønnesenQuoted 10 lines · On Thu, 4 Sep 2025 22:01:27 +0000 Asbjørn Sloth Tønnesen wrote:
In
wireguard_get_device_dump(), as generated byprint_dump(), it didn't generate a declaration ofunsigned int i:$ make -C tools/net/ynl/generated wireguard-user.o -e CC wireguard-user.o wireguard-user.c: In function ‘wireguard_get_device_dump’: wireguard-user.c:502:22: error: ‘i’ undeclared (first use in this fn) 502 | for (i = 0; i < req->_count.peers; i++) | ^
Quoted 2 lines
Copy the logic from
print_req()as it correctly generated the iterator inwireguard_set_device().
Re: [PATCH net-next 04/11] tools: ynl-gen: define count iterator in print_dump()
In reply to Asbjørn Sloth TønnesenQuoted 10 lines · Asbjørn Sloth Tønnesen
In
wireguard_get_device_dump(), as generated byprint_dump(), it didn't generate a declaration ofunsigned int i:$ make -C tools/net/ynl/generated wireguard-user.o -e CC wireguard-user.o wireguard-user.c: In function ‘wireguard_get_device_dump’: wireguard-user.c:502:22: error: ‘i’ undeclared (first use in this fn) 502 | for (i = 0; i < req->_count.peers; i++) | ^
Quoted 5 lines
Copy the logic from
print_req()as it correctly generated the iterator inwireguard_set_device().Signed-off-by Asbjørn Sloth Tønnesen <[email protected]>---
Quoted 19 lines
tools/net/ynl/pyynl/ynl_gen_c.py | 5 +++++ 1 file changed, 5 insertions(+)tools/net/ynl/pyynl/ynl_gen_c.py +5
-0@@ -2425,6 +2425,11 @@ def print_dump(ri): local_vars += ['size_t hdr_len;', 'void *hdr;'] + for _, attr in ri.struct['request'].member_list(): + if attr.presence_type() == 'count': + local_vars += ['unsigned int i;'] + break + ri.cw.write_func_lvar(local_vars) ri.cw.p('yds.yarg.ys = ys;')
PATCH 5/11 tools: ynl-gen: define nlattr *array in a block scope
In reply to Asbjørn Sloth TønnesenInstead of trying to define "struct nlattr *array;" in the all the right places, then simply define it in a block scope, as it's only used here.
Before this patch it was generated for attribute set _put() functions, like wireguard_wgpeer_put(), but missing and caused a compile error for the command function wireguard_set_device().
$ make -C tools/net/ynl/generated wireguard-user.o
-e CC wireguard-user.o
wireguard-user.c: In function ‘wireguard_set_device’:
wireguard-user.c:548:9: error: ‘array’ undeclared (first use in ..)
548 | array = ynl_attr_nest_start(nlh, WGDEVICE_A_PEERS);
| ^~~~~--- tools/net/ynl/pyynl/ynl_gen_c.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
tools/net/ynl/pyynl/ynl_gen_c.py +4 -4
@@ -842,6 +842,9 @@ class TypeArrayNest(Type): return get_lines, None, local_vars def attr_put(self, ri, var): + ri.cw.block_start() + ri.cw.p('struct nlattr *array;') + ri.cw.nl() ri.cw.p(f'array = ynl_attr_nest_start(nlh, {self.enum_name});') if self.sub_type in scalars: put_type = self.sub_type
@@ -857,6 +860,7 @@ class TypeArrayNest(Type): else: raise Exception(f"Put for ArrayNest sub-type {self.attr['sub-type']} not supported, yet") ri.cw.p('ynl_attr_nest_end(nlh, array);') + ri.cw.block_end() def _setter_lines(self, ri, member, presence): return [f"{member} = {self.c_name};",
@@ -2063,13 +2067,9 @@ def put_req_nested(ri, struct): init_lines.append(f"hdr = ynl_nlmsg_put_extra_header(nlh, {struct_sz});") init_lines.append(f"memcpy(hdr, &obj->_hdr, {struct_sz});") - has_anest = False has_count = False for _, arg in struct.member_list(): - has_anest |= arg.type == 'indexed-array' has_count |= arg.presence_type() == 'count' - if has_anest: - local_vars.append('struct nlattr *array;') if has_count: local_vars.append('unsigned int i;')
Signature · 1 line
2.51.0
Re: [PATCH net-next 05/11] tools: ynl-gen: define nlattr *array in a block scope
Quoted 8 lines · Asbjørn Sloth Tønnesen
Instead of trying to define "struct nlattr *array;" in the all the right places, then simply define it in a block scope, as it's only used here.
Before this patch it was generated for attribute set
_put()functions, likewireguard_wgpeer_put(), but missing and caused a compile error for the command functionwireguard_set_device().
Quoted 8 lines
$ make -C tools/net/ynl/generated wireguard-user.o -e CC wireguard-user.o wireguard-user.c: In function ‘wireguard_set_device’: wireguard-user.c:548:9: error: ‘array’ undeclared (first use in ..) 548 | array = ynl_attr_nest_start(nlh, WGDEVICE_A_PEERS); | ^~~~~Signed-off-by Asbjørn Sloth Tønnesen <[email protected]>
Jakub Kicinski
maintainerRe: [PATCH net-next 05/11] tools: ynl-gen: define nlattr *array in a block scope
In reply to Asbjørn Sloth TønnesenQuoted 8 lines · On Thu, 4 Sep 2025 22:01:28 +0000 Asbjørn Sloth Tønnesen wrote:
Instead of trying to define "struct nlattr *array;" in the all the right places, then simply define it in a block scope, as it's only used here.
Before this patch it was generated for attribute set
_put()functions, likewireguard_wgpeer_put(), but missing and caused a compile error for the command functionwireguard_set_device().
Quoted 6 lines
$ make -C tools/net/ynl/generated wireguard-user.o
-e CC wireguard-user.o
wireguard-user.c: In function ‘wireguard_set_device’:
wireguard-user.c:548:9: error: ‘array’ undeclared (first use in ..)
548 | array = ynl_attr_nest_start(nlh, WGDEVICE_A_PEERS);
| ^~~~~Dunno about this one. In patch 4 you basically add another instance of the "let's declare local vars at function level" approach. And here you're going the other way. This patch will certainly work, but I felt like I wouldn't have written it this way if I was typing in the parsers by hand.
Re: [PATCH net-next 05/11] tools: ynl-gen: define nlattr *array in a block scope
Quoted 16 lines · Jakub Kicinski
Quoted 8 lines · On Thu, 4 Sep 2025 22:01:28 +0000 Asbjørn Sloth Tønnesen wrote:
Instead of trying to define "struct nlattr *array;" in the all the right places, then simply define it in a block scope, as it's only used here.
Before this patch it was generated for attribute set
_put()functions, likewireguard_wgpeer_put(), but missing and caused a compile error for the command functionwireguard_set_device().Quoted 6 lines
$ make -C tools/net/ynl/generated wireguard-user.o -e CC wireguard-user.o wireguard-user.c: In function ‘wireguard_set_device’: wireguard-user.c:548:9: error: ‘array’ undeclared (first use in ..) 548 | array = ynl_attr_nest_start(nlh, WGDEVICE_A_PEERS); | ^~~~~
Quoted 5 lines
Dunno about this one. In patch 4 you basically add another instance of the "let's declare local vars at function level" approach. And here you're going the other way. This patch will certainly work, but I felt like I wouldn't have written it this way if I was typing in the parsers by hand.
Thanks for the reviews.
In patch 4, it is about a variable used by multiple Type classes having presence_type() = 'count', which is currently 3 classes:
- TypeBinaryScalarArray
- TypeMultiAttr
- TypeArrayNest (later renamed to TypeIndexedArray)
In patch 5, I move code for a special variable used by one Type class, to be contained within that class. It makes it easier to ensure that the variable is only defined, when used, and vice versa. This comes at the cost of the generated code looking generated.
If we should make the generated code look like it was written by humans, then I would move the definition of these local variables into a class method, so i can be generated by the generic implementation, and array can be implemented in it's class. I will take a stab at this, but it might be too much refactoring for this series, eg. len is also defined local to conditional blocks multiple branches in a row.
tools/net/ynl/generated/nl80211-user.c:nl80211_iftype_data_attrs_parse(..) {
[..]
ynl_attr_for_each_nested(attr, nested) {
unsigned int type = ynl_attr_type(attr);
if (type == NL80211_BAND_IFTYPE_ATTR_IFTYPES) {
unsigned int len;
[..]
} else if (type == NL80211_BAND_IFTYPE_ATTR_HE_CAP_MAC) {
unsigned int len;
[..]
[same pattern 8 times, so 11 times in total]
} else if (type == NL80211_BAND_IFTYPE_ATTR_EHT_CAP_PPE) {
unsigned int len;
[..]
} }
return 0;
}
(I didn't have to search for this, I saw the pattern in wireguard-user.c, looked for it in nl80211-user.c and this was the first len usage there.)
That looks very generated, I would have len defined together with type, and a switch statement would also look a lot more natural, but maybe leave the if->switch conversion for the compiler to detect.
Jakub Kicinski
maintainerRe: [PATCH net-next 05/11] tools: ynl-gen: define nlattr *array in a block scope
Quoted 10 lines · On Sat, 6 Sep 2025 13:13:29 +0000 Asbjørn Sloth Tønnesen wrote:
In patch 4, it is about a variable used by multiple Type classes having
presence_type()= 'count', which is currently 3 classes:
- TypeBinaryScalarArray
- TypeMultiAttr
- TypeArrayNest (later renamed to TypeIndexedArray)In patch 5, I move code for a special variable used by one Type class, to be contained within that class. It makes it easier to ensure that the variable is only defined, when used, and vice versa. This comes at the cost of the generated code looking generated.
So you're agreeing?
Quoted 19 lines
If we should make the generated code look like it was written by humans, then I would move the definition of these local variables into a class method, so
ican be generated by the generic implementation, andarraycan be implemented in it's class. I will take a stab at this, but it might be too much refactoring for this series, eg.lenis also defined local to conditional blocks multiple branches in a row.
tools/net/ynl/generated/nl80211-user.c:nl80211_iftype_data_attrs_parse(..) { [..] ynl_attr_for_each_nested(attr, nested) { unsigned int type = ynl_attr_type(attr); if (type == NL80211_BAND_IFTYPE_ATTR_IFTYPES) { unsigned int len; [..] } else if (type == NL80211_BAND_IFTYPE_ATTR_HE_CAP_MAC) { unsigned int len; [..]
Quoted 8 lines
[same pattern 8 times, so 11 times in total]
} else if (type == NL80211_BAND_IFTYPE_ATTR_EHT_CAP_PPE) {
unsigned int len;
[..]
}
}
return 0;
}It's pretty easily doable, I already gave up on not calling _attr_get() for sub-messages.
Quoted 3 lines
That looks very generated, I would have
lendefined together withtype, and a switch statement would also look a lot more natural, but maybe leave theif->switchconversion for the compiler to detect.
tools/net/ynl/pyynl/ynl_gen_c.py +9 -5
@@ -243,7 +243,7 @@ from lib import SpecSubMessage, SpecSubMessageFormat raise Exception(f"Attr get not implemented for class type {self.type}") def attr_get(self, ri, var, first): - lines, init_lines, local_vars = self._attr_get(ri, var) + lines, init_lines, _ = self._attr_get(ri, var) if type(lines) is str: lines = [lines] if type(init_lines) is str:
@@ -251,10 +251,6 @@ from lib import SpecSubMessage, SpecSubMessageFormat kw = 'if' if first else 'else if' ri.cw.block_start(line=f"{kw} (type == {self.enum_name})") - if local_vars: - for local in local_vars: - ri.cw.p(local) - ri.cw.nl() if not self.is_multi_val(): ri.cw.p("if (ynl_attr_validate(yarg, attr))")
@@ -2101,6 +2097,7 @@ _C_KW = { else: raise Exception(f"Per-op fixed header not supported, yet") + var_set = set() array_nests = set() multi_attrs = set() needs_parg = False
@@ -2118,6 +2115,13 @@ _C_KW = { multi_attrs.add(arg) needs_parg |= 'nested-attributes' in aspec needs_parg |= 'sub-message' in aspec + + try: + _, _, l_vars = aspec._attr_get(ri, '') + var_set |= set(l_vars) if l_vars else set() + except: + pass # _attr_get() not implemented by simple types, ignore + local_vars += list(var_set) if array_nests or multi_attrs: local_vars.append('int i;') if needs_parg:
Re: [PATCH net-next 05/11] tools: ynl-gen: define nlattr *array in a block scope
Quoted 85 lines · Jakub Kicinski
Quoted 10 lines · On Sat, 6 Sep 2025 13:13:29 +0000 Asbjørn Sloth Tønnesen wrote:
In patch 4, it is about a variable used by multiple Type classes having
presence_type()= 'count', which is currently 3 classes:
- TypeBinaryScalarArray
- TypeMultiAttr
- TypeArrayNest (later renamed to TypeIndexedArray)In patch 5, I move code for a special variable used by one Type class, to be contained within that class. It makes it easier to ensure that the variable is only defined, when used, and vice versa. This comes at the cost of the generated code looking generated.
So you're agreeing?
Quoted 19 lines
If we should make the generated code look like it was written by humans, then I would move the definition of these local variables into a class method, so
ican be generated by the generic implementation, andarraycan be implemented in it's class. I will take a stab at this, but it might be too much refactoring for this series, eg.lenis also defined local to conditional blocks multiple branches in a row.
tools/net/ynl/generated/nl80211-user.c:nl80211_iftype_data_attrs_parse(..) { [..] ynl_attr_for_each_nested(attr, nested) { unsigned int type = ynl_attr_type(attr); if (type == NL80211_BAND_IFTYPE_ATTR_IFTYPES) { unsigned int len; [..] } else if (type == NL80211_BAND_IFTYPE_ATTR_HE_CAP_MAC) { unsigned int len; [..]Quoted 8 lines
[same pattern 8 times, so 11 times in total] } else if (type == NL80211_BAND_IFTYPE_ATTR_EHT_CAP_PPE) { unsigned int len; [..] } } return 0; }It's pretty easily doable, I already gave up on not calling
_attr_get()for sub-messages.Quoted 3 lines
That looks very generated, I would have
lendefined together withtype, and a switch statement would also look a lot more natural, but maybe leave theif->switchconversion for the compiler to detect.tools/net/ynl/pyynl/ynl_gen_c.py +2
-5@@ -243,7 +243,7 @@ from lib import SpecSubMessage, SpecSubMessageFormat raise Exception(f"Attr get not implemented for class type {self.type}") def attr_get(self, ri, var, first): - lines, init_lines, local_vars = self._attr_get(ri, var) + lines, init_lines, _ = self._attr_get(ri, var) if type(lines) is str: lines = [lines] if type(init_lines) is str:@@ -251,10 +251,6 @@ from lib import SpecSubMessage, SpecSubMessageFormat kw = 'if' if first else 'else if' ri.cw.block_start(line=f"{kw} (type == {self.enum_name})") - if local_vars: - for local in local_vars: - ri.cw.p(local) - ri.cw.nl() if not self.is_multi_val(): ri.cw.p("if (ynl_attr_validate(yarg, attr))")@@ -2101,6 +2097,7 @@ _C_KW = { else: raise Exception(f"Per-op fixed header not supported, yet") + var_set = set() array_nests = set() multi_attrs = set() needs_parg = False@@ -2118,6 +2115,13 @@ _C_KW = { multi_attrs.add(arg) needs_parg |= 'nested-attributes' in aspec needs_parg |= 'sub-message' in aspec
tools/net/ynl/pyynl/ynl_gen_c.py _C_KW = { · line 2127
Quoted 10 lines
tools/net/ynl/pyynl/ynl_gen_c.py +7
-0+ + try: + _, _, l_vars = aspec._attr_get(ri, '') + var_set |= set(l_vars) if l_vars else set() + except: + pass # _attr_get() not implemented by simple types, ignore + local_vars += list(var_set) if array_nests or multi_attrs: local_vars.append('int i;') if needs_parg:
I left this for you to submit, there is a trivial conflict with patch 8 in my v2 posting.
It gives a pretty nice diffstat when comparing the generated code:
devlink-user.c | 187 +++---------------- dpll-user.c | 10 - ethtool-user.c | 49 +---- fou-user.c | 5 handshake-user.c | 3 mptcp_pm-user.c | 3 nfsd-user.c | 16 - nl80211-user.c | 159 +--------------- nlctrl-user.c | 21 -- ovpn-user.c | 7 ovs_datapath-user.c | 9 ovs_flow-user.c | 89 --------- ovs_vport-user.c | 7 rt-addr-user.c | 14 - rt-link-user.c | 183 ++---------------- rt-neigh-user.c | 14 - rt-route-user.c | 26 -- rt-rule-user.c | 11 - tc-user.c | 380 +++++---------------------------------- tcp_metrics-user.c | 7 team-user.c | 5 21 files changed, 175 insertions(+), 1030 deletions(-)
Jakub Kicinski
maintainerRe: [PATCH net-next 05/11] tools: ynl-gen: define nlattr *array in a block scope
Quoted 2 lines · On Thu, 11 Sep 2025 00:01:48 +0000 Asbjørn Sloth Tønnesen wrote:
I left this for you to submit, there is a trivial conflict with patch 8 in my v2 posting.
Hah, no, please take this and submit as yours if you can. You can add me as Suggested-by. I already dropped it form my tree. Maintainers tend to throw random snippets of code at people, it's just quicker than explaining but we have enough commits in our name..
PATCH 6/11 tools: ynl-gen: don't validate nested array attribute types
In reply to Asbjørn Sloth TønnesenIn nested arrays don't require that the intermediate attribute type should be a valid attribute type, it might just be an index or simple 0, it is often not even used.
See include/net/netlink.h about NLA_NESTED_ARRAY:
Quoted 5 lines
The difference to
NLA_NESTEDis the structure:NLA_NESTEDhas the nested attributes directly inside while an array has the nested attributes at another level down and the attribute types directly in the nesting don't matter.
--- tools/net/ynl/pyynl/ynl_gen_c.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-)
tools/net/ynl/pyynl/ynl_gen_c.py +6 -5
@@ -834,11 +834,12 @@ class TypeArrayNest(Type): def _attr_get(self, ri, var): local_vars = ['const struct nlattr *attr2;'] get_lines = [f'attr_{self.c_name} = attr;', - 'ynl_attr_for_each_nested(attr2, attr) {', - '\tif (ynl_attr_validate(yarg, attr2))', - '\t\treturn YNL_PARSE_CB_ERROR;', - f'\tn_{self.c_name}++;', - '}'] + 'ynl_attr_for_each_nested(attr2, attr) {'] + if self.attr['sub-type'] != 'nest': + get_lines.append('\tif (ynl_attr_validate(yarg, attr2))') + get_lines.append('\t\treturn YNL_PARSE_CB_ERROR;') + get_lines.append(f'\tn_{self.c_name}++;') + get_lines.append('}') return get_lines, None, local_vars def attr_put(self, ri, var):
Signature · 1 line
2.51.0
Jakub Kicinski
maintainerRe: [PATCH net-next 06/11] tools: ynl-gen: don't validate nested array attribute types
Quoted 11 lines · On Thu, 4 Sep 2025 22:01:29 +0000 Asbjørn Sloth Tønnesen wrote:
In nested arrays don't require that the intermediate attribute type should be a valid attribute type, it might just be an index or simple 0, it is often not even used.
See
include/net/netlink.haboutNLA_NESTED_ARRAY:Quoted 5 lines
The difference to
NLA_NESTEDis the structure:NLA_NESTEDhas the nested attributes directly inside while an array has the nested attributes at another level down and the attribute types directly in the nesting don't matter.
I don't understand, please provide more details. This is an ArrayNest, right?
[ARRAY-ATTR]
[ENTRY]
[MEMBER1]
[MEMBER2]
[ENTRY]
[MEMBER1]
[MEMBER2]Which level are you saying doesn't matter?
If entry is a nest it must be a valid nest.
What the comment you're quoting is saying is that the nla_type of ENTRY doesn't matter.
Re: [PATCH net-next 06/11] tools: ynl-gen: don't validate nested array attribute types
Quoted 24 lines · Jakub Kicinski
Quoted 11 lines · On Thu, 4 Sep 2025 22:01:29 +0000 Asbjørn Sloth Tønnesen wrote:
In nested arrays don't require that the intermediate attribute type should be a valid attribute type, it might just be an index or simple 0, it is often not even used.
See
include/net/netlink.haboutNLA_NESTED_ARRAY:Quoted 5 lines
The difference to
NLA_NESTEDis the structure:NLA_NESTEDhas the nested attributes directly inside while an array has the nested attributes at another level down and the attribute types directly in the nesting don't matter.I don't understand, please provide more details. This is an ArrayNest, right?
[ARRAY-ATTR]
[ENTRY][MEMBER1] [MEMBER2] [ENTRY] [MEMBER1] [MEMBER2]
Quoted 4 lines
Which level are you saying doesn't matter?
If entry is a nest it must be a valid nest.
What the comment you're quoting is saying is that thenla_typeof ENTRY doesn't matter.
I will expand this in v2, but the gist of it is that this is part of the "split attribute counting, and later allocating an array to hold them" code.
The check that I remove for nested arrays, is an early exit during the counting phase. Later in the allocation and parse phase it validates the nested payload.
In include/uapi/linux/wireguard.h:
Quoted 7 lines
WGDEVICE_A_PEERS:NLA_NESTED
0:NLA_NESTED
WGPEER_A_PUBLIC_KEY:NLA_EXACT_LEN, lenWG_KEY_LEN[..]
0:NLA_NESTED......
The current check requires that the nested type is valid in the nested attribute set, which in this case resolves to WGDEVICE_A_UNSPEC, which is YNL_PT_REJECT, and it takes the early exit and returns YNL_PARSE_CB_ERROR.
Jakub Kicinski
maintainerRe: [PATCH net-next 06/11] tools: ynl-gen: don't validate nested array attribute types
Quoted 32 lines · On Sat, 6 Sep 2025 13:22:01 +0000 Asbjørn Sloth Tønnesen wrote:
Quoted 11 lines
I don't understand, please provide more details. This is an ArrayNest, right?
[ARRAY-ATTR]
[ENTRY][MEMBER1] [MEMBER2] [ENTRY] [MEMBER1] [MEMBER2]Quoted 4 lines
Which level are you saying doesn't matter?
If entry is a nest it must be a valid nest.
What the comment you're quoting is saying is that thenla_typeof ENTRY doesn't matter.I will expand this in v2, but the gist of it is that this is part of the "split attribute counting, and later allocating an array to hold them" code.
The check that I remove for nested arrays, is an early exit during the counting phase. Later in the allocation and parse phase it validates the nested payload.
In
include/uapi/linux/wireguard.h:Quoted 7 lines
WGDEVICE_A_PEERS:NLA_NESTED
0:NLA_NESTED
WGPEER_A_PUBLIC_KEY:NLA_EXACT_LEN, lenWG_KEY_LEN[..]
0:NLA_NESTED......
Quoted 3 lines
The current check requires that the nested type is valid in the nested attribute set, which in this case resolves to
WGDEVICE_A_UNSPEC, which isYNL_PT_REJECT, and it takes the early exit and returnsYNL_PARSE_CB_ERROR.
I see your point now. We're validating ENTRY as an attribute in the parent attribute set, but it's just a meaningless id.
I think we need more fixing here. The real parsing loop will only validate what's _inside_ the [MEMBER]. Which doesn't matter all that much to nests, but look at what happens if subtype is a scalar. We'll just call ynl_attr_get_u32(), type is never really validate.
I think we need this, and make the codegen feed in the ARRAY-ATTR type to validate ENTRY?
tools/net/ynl/lib/ynl.c +8 -3
@@ -360,15 +360,15 @@ static int ynl_cb_done(const struct nlmsghdr *nlh, struct ynl_parse_arg *yarg)/* Attribute validation */ -int ynl_attr_validate (struct ynl_parse_arg *yarg,const struct nlattr *attr) +int __ynl_attr_validate (struct ynl_parse_arg *yarg,const struct nlattr *attr, +unsigned int type) {const struct ynl_policy_attr *policy; -unsigned int type, len;unsigned char *data; +unsigned int len; data =ynl_attr_data (attr); len =ynl_attr_data_len (attr); - type =ynl_attr_type (attr);if (type > yarg->rsp_policy->max_attr) {yerr (yarg->ys,YNL_ERROR_INTERNAL ,"Internal error, validating unknown attribute" );
@@ -450,6 +450,11 @@ int ynl_attr_validate(struct ynl_parse_arg *yarg, const struct nlattr *attr)return 0 ; } +int ynl_attr_validate (struct ynl_parse_arg *yarg,const struct nlattr *attr) +{ +return __ynl_attr_validate (yarg, attr,ynl_attr_type (attr)); +} +int ynl_submsg_failed (struct ynl_parse_arg *yarg,const char *field_name,const char *sel_name) {
Re: [PATCH net-next 06/11] tools: ynl-gen: don't validate nested array attribute types
In reply to Asbjørn Sloth TønnesenQuoted 5 lines · Asbjørn Sloth Tønnesen
In nested arrays don't require that the intermediate attribute type should be a valid attribute type, it might just be an index or simple 0, it is often not even used.
Quoted 7 lines
See
include/net/netlink.haboutNLA_NESTED_ARRAY:Quoted 5 lines
The difference to
NLA_NESTEDis the structure:NLA_NESTEDhas the nested attributes directly inside while an array has the nested attributes at another level down and the attribute types directly in the nesting don't matter.
To me, it would seem like it makes more sense to define these (even if thats defined per family?) than to just say they aren't defined at all?
Hm.
Quoted 27 lines
Signed-off-by Asbjørn Sloth Tønnesen <[email protected]>--- tools/net/ynl/pyynl/ynl_gen_c.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-)tools/net/ynl/pyynl/ynl_gen_c.py +6
-5@@ -834,11 +834,12 @@ class TypeArrayNest(Type): def _attr_get(self, ri, var): local_vars = ['const struct nlattr *attr2;'] get_lines = [f'attr_{self.c_name} = attr;', - 'ynl_attr_for_each_nested(attr2, attr) {', - '\tif (ynl_attr_validate(yarg, attr2))', - '\t\treturn YNL_PARSE_CB_ERROR;', - f'\tn_{self.c_name}++;', - '}'] + 'ynl_attr_for_each_nested(attr2, attr) {'] + if self.attr['sub-type'] != 'nest': + get_lines.append('\tif (ynl_attr_validate(yarg, attr2))') + get_lines.append('\t\treturn YNL_PARSE_CB_ERROR;') + get_lines.append(f'\tn_{self.c_name}++;') + get_lines.append('}') return get_lines, None, local_vars def attr_put(self, ri, var):
Re: [PATCH net-next 06/11] tools: ynl-gen: don't validate nested array attribute types
Quoted 14 lines · Jacob Keller
Quoted 5 lines · Asbjørn Sloth Tønnesen
In nested arrays don't require that the intermediate attribute type should be a valid attribute type, it might just be an index or simple 0, it is often not even used.
Quoted 7 lines
See
include/net/netlink.haboutNLA_NESTED_ARRAY:Quoted 5 lines
The difference to
NLA_NESTEDis the structure:NLA_NESTEDhas the nested attributes directly inside while an array has the nested attributes at another level down and the attribute types directly in the nesting don't matter.
Quoted 4 lines
To me, it would seem like it makes more sense to define these (even if thats defined per family?) than to just say they aren't defined at all?
Hm.
I considered adding some of that metadata too, as I am actually removing it for wireguard (in comment form, but still).
In include/uapi/linux/wireguard.h in the comment block at the top, it is very clear that wireguard only used type 0 for all the nested array entries, however the truth is that it doesn't care. It therefore doesn't matter if the generated -user.* keeps track of the index in .idx, or that cli.py decodes a JSON array and sends it with indexes, it's not needed, but it still works.
In practice I don't think we will break any clients if we enforced it, and validated that wireguard only accepts type 0 entries, in it's nested arrays.
For the other families, I don't know how well defined it is, Johannes have stated that nl80211 doesn't care which types are used, but I have no idea how consistent clients have abused that statement to send random data, or do they all just send zeros?
This would make a lot more sense if 'array-nest' hadn't been renamed to 'indexed-array' in ynl, because it feels wrong to add 'unindexed: true' now. We could also call it 'all-zero-indexed: true'.
In cli.py this gives some extra issues, as seen in [1], the nested arrays are outputted as '[{0: {..}}, {0: {..}}, ..]', but on input has the format '[{..},{..}, ..]' because it has to be JSON-compatible on input.
If we had an attribute like 'all-zero-indexed' then cli.py, could also output '[{..},{..}, ..]'.
Re: [PATCH net-next 06/11] tools: ynl-gen: don't validate nested array attribute types
Quoted 5 lines · Asbjørn Sloth Tønnesen
For the other families, I don't know how well defined it is, Johannes have stated that nl80211 doesn't care which types are used, but I have no idea how consistent clients have abused that statement to send random data, or do they all just send zeros?
I think most clients probably send incrementing numbers (1, 2, 3, ...), but maybe some start at 0, some sometimes might use band numbers and thus have sparse values, etc.
But as I just wrote, I'm not really sure it should be used at all.
joahnnes
Re: [PATCH net-next 06/11] tools: ynl-gen: don't validate nested array attribute types
In reply to Asbjørn Sloth TønnesenQuoted 32 lines · Asbjørn Sloth Tønnesen
CC JohannesQuoted 14 lines · Jacob Keller
Quoted 5 lines · Asbjørn Sloth Tønnesen
In nested arrays don't require that the intermediate attribute type should be a valid attribute type, it might just be an index or simple 0, it is often not even used.
Quoted 7 lines
See
include/net/netlink.haboutNLA_NESTED_ARRAY:Quoted 5 lines
The difference to
NLA_NESTEDis the structure:NLA_NESTEDhas the nested attributes directly inside while an array has the nested attributes at another level down and the attribute types directly in the nesting don't matter.Quoted 4 lines
To me, it would seem like it makes more sense to define these (even if thats defined per family?) than to just say they aren't defined at all?
Hm.
I considered adding some of that metadata too, as I am actually removing it for wireguard (in comment form, but still).
In
include/uapi/linux/wireguard.hin the comment block at the top, it is very clear that wireguard only used type 0 for all the nested array entries, however the truth is that it doesn't care. It therefore doesn't matter if the generated -user.* keeps track of the index in .idx, or thatcli.pydecodes a JSON array and sends it with indexes, it's not needed, but it still works.
Quoted 8 lines
In practice I don't think we will break any clients if we enforced it, and validated that wireguard only accepts type 0 entries, in it's nested arrays.
For the other families, I don't know how well defined it is, Johannes have stated that nl80211 doesn't care which types are used, but I have no idea how consistent clients have abused that statement to send random data, or do they all just send zeros?
Changing it at this point could be a significant backwards compat break, as some clients might somehow send data that wasn't zero-initialized, and checking would break them. At this point I guess it makes sense to leave it as is... It would increase code cost and complexity for no gain.
Quoted 11 lines
This would make a lot more sense if 'array-nest' hadn't been renamed to 'indexed-array' in ynl, because it feels wrong to add 'unindexed: true' now. We could also call it 'all-zero-indexed: true'.
In
cli.pythis gives some extra issues, as seen in [1], the nested arrays are outputted as '[{0: {..}}, {0: {..}}, ..]', but on input has the format '[{..},{..}, ..]' because it has to be JSON-compatible on input.If we had an attribute like 'all-zero-indexed' then
cli.py, could also output '[{..},{..}, ..]'.
This part would be cool. If we know the index is "uninteresting", eliding it so that the input and output formats match is good.
Quoted 1 line
PATCH 7/11 tools: ynl-gen: rename TypeArrayNest to TypeIndexedArray
In reply to Asbjørn Sloth TønnesenAs TypeArrayNest can now be used with many other sub-types than nest, then rename it to TypeIndexedArray, to reduce confusion.
This is a trivial patch with no behavioural changes intended.
--- tools/net/ynl/pyynl/ynl_gen_c.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
tools/net/ynl/pyynl/ynl_gen_c.py +4 -4
@@ -792,7 +792,7 @@ class TypeMultiAttr(Type): f"{presence} = n_{self.c_name};"] -class TypeArrayNest(Type): +class TypeIndexedArray(Type): def is_multi_val(self): return True
@@ -829,7 +829,7 @@ class TypeArrayNest(Type): elif self.attr['sub-type'] == 'nest': return f'.type = YNL_PT_NEST, .nest = &{self.nested_render_name}_nest, ' else: - raise Exception(f"Typol for ArrayNest sub-type {self.attr['sub-type']} not supported, yet") + raise Exception(f"Typol for IndexedArray sub-type {self.attr['sub-type']} not supported, yet") def _attr_get(self, ri, var): local_vars = ['const struct nlattr *attr2;']
@@ -859,7 +859,7 @@ class TypeArrayNest(Type): ri.cw.p(f'for (i = 0; i < {var}->_count.{self.c_name}; i++)') ri.cw.p(f"{self.nested_render_name}_put(nlh, i, &{var}->{self.c_name}[i]);") else: - raise Exception(f"Put for ArrayNest sub-type {self.attr['sub-type']} not supported, yet") + raise Exception(f"Put for IndexedArray sub-type {self.attr['sub-type']} not supported, yet") ri.cw.p('ynl_attr_nest_end(nlh, array);') ri.cw.block_end()
@@ -1137,7 +1137,7 @@ class AttrSet(SpecAttrSet): t = TypeNest(self.family, self, elem, value) elif elem['type'] == 'indexed-array' and 'sub-type' in elem: if elem["sub-type"] in ['binary', 'nest', 'u32']: - t = TypeArrayNest(self.family, self, elem, value) + t = TypeIndexedArray(self.family, self, elem, value) else: raise Exception(f'new_attr: unsupported sub-type {elem["sub-type"]}') elif elem['type'] == 'nest-type-value':
Signature · 1 line
2.51.0
Re: [PATCH net-next 07/11] tools: ynl-gen: rename TypeArrayNest to TypeIndexedArray
Quoted 7 lines · Asbjørn Sloth Tønnesen
As TypeArrayNest can now be used with many other sub-types than nest, then rename it to TypeIndexedArray, to reduce confusion.
This is a trivial patch with no behavioural changes intended.
Signed-off-by Asbjørn Sloth Tønnesen <[email protected]>
Jakub Kicinski
maintainerRe: [PATCH net-next 07/11] tools: ynl-gen: rename TypeArrayNest to TypeIndexedArray
In reply to Asbjørn Sloth TønnesenQuoted 3 lines · On Thu, 4 Sep 2025 22:01:30 +0000 Asbjørn Sloth Tønnesen wrote:
As TypeArrayNest can now be used with many other sub-types than nest, then rename it to TypeIndexedArray, to reduce confusion.
You need to also find all the local comments and variables which allude to the name.
PATCH 8/11 tools: ynl: move nest packing to a helper function
In reply to Asbjørn Sloth TønnesenThis patch moves nest packing into a helper function, that can also be used for packing indexed arrays.
No behavioural changes intended.
--- tools/net/ynl/pyynl/lib/ynl.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-)
tools/net/ynl/pyynl/lib/ynl.py +9 -4
@@ -562,11 +562,8 @@ class YnlFamily(SpecFamily): if attr["type"] == 'nest': nl_type |= Netlink.NLA_F_NESTED - attr_payload = b'' sub_space = attr['nested-attributes'] - sub_attrs = SpaceAttrs(self.attr_sets[sub_space], value, search_attrs) - for subname, subvalue in value.items(): - attr_payload += self._add_attr(sub_space, subname, subvalue, sub_attrs) + attr_payload = self._add_nest_attrs(value, sub_space, search_attrs) elif attr["type"] == 'flag': if not value: # If value is absent or false then skip attribute creation.
@@ -623,6 +620,14 @@ class YnlFamily(SpecFamily): pad = b'\x00' * ((4 - len(attr_payload) % 4) % 4) return struct.pack('HH', len(attr_payload) + 4, nl_type) + attr_payload + pad + def _add_nest_attrs(self, value, sub_space, search_attrs): + sub_attrs = SpaceAttrs(self.attr_sets[sub_space], value, search_attrs) + attr_payload = b'' + for subname, subvalue in value.items(): + attr_payload += self._add_attr(sub_space, subname, subvalue, + sub_attrs) + return attr_payload + def _get_enum_or_unknown(self, enum, raw): try: name = enum.entries_by_val[raw].name
Signature · 1 line
2.51.0
Re: [PATCH net-next 08/11] tools: ynl: move nest packing to a helper function
Quoted 6 lines · Asbjørn Sloth Tønnesen
This patch moves nest packing into a helper function, that can also be used for packing indexed arrays.
No behavioural changes intended.
Signed-off-by Asbjørn Sloth Tønnesen <[email protected]>
PATCH 9/11 tools: ynl: encode indexed-array
In reply to Asbjørn Sloth TønnesenThis patch adds support for encoding indexed-array attributes with sub-type nest in pyynl.
--- tools/net/ynl/pyynl/lib/ynl.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+)
tools/net/ynl/pyynl/lib/ynl.py +17 -0
@@ -564,6 +564,11 @@ class YnlFamily(SpecFamily): nl_type |= Netlink.NLA_F_NESTED sub_space = attr['nested-attributes'] attr_payload = self._add_nest_attrs(value, sub_space, search_attrs) + elif attr['type'] == 'indexed-array' and attr['sub-type'] == 'nest': + nl_type |= Netlink.NLA_F_NESTED + sub_space = attr['nested-attributes'] + attr_payload = self._encode_indexed_array(value, sub_space, + search_attrs) elif attr["type"] == 'flag': if not value: # If value is absent or false then skip attribute creation.
@@ -617,6 +622,9 @@ class YnlFamily(SpecFamily): else: raise Exception(f'Unknown type at {space} {name} {value} {attr["type"]}') + return self._add_attr_raw(nl_type, attr_payload) + + def _add_attr_raw(self, nl_type, attr_payload): pad = b'\x00' * ((4 - len(attr_payload) % 4) % 4) return struct.pack('HH', len(attr_payload) + 4, nl_type) + attr_payload + pad
@@ -628,6 +636,15 @@ class YnlFamily(SpecFamily): sub_attrs) return attr_payload + def _encode_indexed_array(self, vals, sub_space, search_attrs): + attr_payload = b'' + nested_flag = Netlink.NLA_F_NESTED + for i, val in enumerate(vals): + idx = i | Netlink.NLA_F_NESTED + val_payload = self._add_nest_attrs(val, sub_space, search_attrs) + attr_payload += self._add_attr_raw(idx, val_payload) + return attr_payload + def _get_enum_or_unknown(self, enum, raw): try: name = enum.entries_by_val[raw].name
Signature · 1 line
2.51.0
Donald Hunter
maintainerRe: [PATCH net-next 09/11] tools: ynl: encode indexed-array
Quoted 35 lines · Asbjørn Sloth Tønnesen
This patch adds support for encoding indexed-array attributes with sub-type nest in pyynl.
Signed-off-by Asbjørn Sloth Tønnesen <[email protected]>--- tools/net/ynl/pyynl/lib/ynl.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+)tools/net/ynl/pyynl/lib/ynl.py +8
-0@@ -564,6 +564,11 @@ class YnlFamily(SpecFamily): nl_type |= Netlink.NLA_F_NESTED sub_space = attr['nested-attributes'] attr_payload = self._add_nest_attrs(value, sub_space, search_attrs) + elif attr['type'] == 'indexed-array' and attr['sub-type'] == 'nest': + nl_type |= Netlink.NLA_F_NESTED + sub_space = attr['nested-attributes'] + attr_payload = self._encode_indexed_array(value, sub_space, + search_attrs) elif attr["type"] == 'flag': if not value: # If value is absent or false then skip attribute creation.@@ -617,6 +622,9 @@ class YnlFamily(SpecFamily): else: raise Exception(f'Unknown type at {space} {name} {value} {attr["type"]}') + return self._add_attr_raw(nl_type, attr_payload) + + def _add_attr_raw(self, nl_type, attr_payload): pad = b'\x00' * ((4 - len(attr_payload) % 4) % 4) return struct.pack('HH', len(attr_payload) + 4, nl_type) + attr_payload + pad
tools/net/ynl/pyynl/lib/ynl.py class YnlFamily(SpecFamily): · line 641
Quoted 6 lines
tools/net/ynl/pyynl/lib/ynl.py +3
-0@@ -628,6 +636,15 @@ class YnlFamily(SpecFamily): sub_attrs) return attr_payload + def _encode_indexed_array(self, vals, sub_space, search_attrs): + attr_payload = b'' + nested_flag = Netlink.NLA_F_NESTED
This line is not doing anything, right?
Quoted 9 lines
tools/net/ynl/pyynl/lib/ynl.py +6
-0+ for i, val in enumerate(vals): + idx = i | Netlink.NLA_F_NESTED + val_payload = self._add_nest_attrs(val, sub_space, search_attrs) + attr_payload += self._add_attr_raw(idx, val_payload) + return attr_payload + def _get_enum_or_unknown(self, enum, raw): try: name = enum.entries_by_val[raw].name
Re: [PATCH net-next 09/11] tools: ynl: encode indexed-array
Hi Donald,
Thanks for the reviews.
Quoted 40 lines · Donald Hunter
Quoted 38 lines · Asbjørn Sloth Tønnesen
This patch adds support for encoding indexed-array attributes with sub-type nest in pyynl.
Signed-off-by Asbjørn Sloth Tønnesen <[email protected]>--- tools/net/ynl/pyynl/lib/ynl.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+)tools/net/ynl/pyynl/lib/ynl.py +8
-0@@ -564,6 +564,11 @@ class YnlFamily(SpecFamily): nl_type |= Netlink.NLA_F_NESTED sub_space = attr['nested-attributes'] attr_payload = self._add_nest_attrs(value, sub_space, search_attrs) + elif attr['type'] == 'indexed-array' and attr['sub-type'] == 'nest': + nl_type |= Netlink.NLA_F_NESTED + sub_space = attr['nested-attributes'] + attr_payload = self._encode_indexed_array(value, sub_space, + search_attrs) elif attr["type"] == 'flag': if not value: # If value is absent or false then skip attribute creation.@@ -617,6 +622,9 @@ class YnlFamily(SpecFamily): else: raise Exception(f'Unknown type at {space} {name} {value} {attr["type"]}') + return self._add_attr_raw(nl_type, attr_payload) + + def _add_attr_raw(self, nl_type, attr_payload): pad = b'\x00' * ((4 - len(attr_payload) % 4) % 4) return struct.pack('HH', len(attr_payload) + 4, nl_type) + attr_payload + pad@@ -628,6 +636,15 @@ class YnlFamily(SpecFamily): sub_attrs) return attr_payload
Quoted 5 lines
tools/net/ynl/pyynl/lib/ynl.py class YnlFamily(SpecFamily): · line 641
Quoted 3 lines
tools/net/ynl/pyynl/lib/ynl.py +3
-0+ def _encode_indexed_array(self, vals, sub_space, search_attrs): + attr_payload = b'' + nested_flag = Netlink.NLA_F_NESTEDThis line is not doing anything, right?
Right, that line shouldn't be there, it is a remain of an early version, where I didn't add the indexes, as NLA_NESTED_ARRAY is actually an unindexed-array.
The wireguard kernel code only sends zero types, and it doesn't care that user- space sends an indexed array back, eg. when setting multiple allowed ips.
Quoted 9 lines
Quoted 9 lines
tools/net/ynl/pyynl/lib/ynl.py +6
-0+ for i, val in enumerate(vals): + idx = i | Netlink.NLA_F_NESTED + val_payload = self._add_nest_attrs(val, sub_space, search_attrs) + attr_payload += self._add_attr_raw(idx, val_payload) + return attr_payload + def _get_enum_or_unknown(self, enum, raw): try: name = enum.entries_by_val[raw].name
Signature · 1 line
pw-bot: cr
PATCH 10/11 tools: ynl: decode hex input
In reply to Asbjørn Sloth TønnesenThis patch add support for decoding hex input, so that binary attributes can be read through --json.
Example (using future wireguard.yaml):
$ sudo ./tools/net/ynl/pyynl/cli.py --family wireguard \
--do set-device --json '{"ifindex":3,
"private-key":"2a ae 6c 35 c9 4f cf <... to 32 bytes>"}'--- tools/net/ynl/pyynl/lib/ynl.py | 2 ++ 1 file changed, 2 insertions(+)
tools/net/ynl/pyynl/lib/ynl.py +2 -0
@@ -973,6 +973,8 @@ class YnlFamily(SpecFamily): raw = ip.packed else: raw = int(ip) + elif attr_spec.display_hint == 'hex': + raw = bytes.fromhex(string) else: raise Exception(f"Display hint '{attr_spec.display_hint}' not implemented" f" when parsing '{attr_spec['name']}'")
Signature · 1 line
2.51.0
Re: [PATCH net-next 10/11] tools: ynl: decode hex input
Quoted 9 lines · Asbjørn Sloth Tønnesen
This patch add support for decoding hex input, so that binary attributes can be read through --json.
Example (using future
wireguard.yaml):$ sudo ./tools/net/ynl/pyynl/cli.py --family wireguard \ --do set-device --json '{"ifindex":3, "private-key":"2a ae 6c 35 c9 4f cf <... to 32 bytes>"}'Signed-off-by Asbjørn Sloth Tønnesen <[email protected]>
FWIW, the hex can include spaces or not when using bytes.fromhex(). When formatting hex for output, I chose to include spaces, but I don't really know if that was a good choice or not.
Re: [PATCH net-next 10/11] tools: ynl: decode hex input
Quoted 10 lines · Donald Hunter
Quoted 8 lines · Asbjørn Sloth Tønnesen
This patch add support for decoding hex input, so that binary attributes can be read through --json.
Example (using future
wireguard.yaml):$ sudo ./tools/net/ynl/pyynl/cli.py --family wireguard \ --do set-device --json '{"ifindex":3, "private-key":"2a ae 6c 35 c9 4f cf <... to 32 bytes>"}'
Quoted 7 lines
Quoted 1 line
Signed-off-by Asbjørn Sloth Tønnesen <[email protected]>Reviewed-by Donald Hunter <[email protected]>FWIW, the hex can include spaces or not when using
bytes.fromhex(). When formatting hex for output, I chose to include spaces, but I don't really know if that was a good choice or not.
I also prefer the spaces for readability.
Re: [PATCH net-next 10/11] tools: ynl: decode hex input
Quoted 13 lines · Jacob Keller
Quoted 12 lines · Donald Hunter
Quoted 9 lines · Asbjørn Sloth Tønnesen
This patch add support for decoding hex input, so that binary attributes can be read through --json.
Example (using future
wireguard.yaml):$ sudo ./tools/net/ynl/pyynl/cli.py --family wireguard \ --do set-device --json '{"ifindex":3, "private-key":"2a ae 6c 35 c9 4f cf <... to 32 bytes>"}'Signed-off-by Asbjørn Sloth Tønnesen <[email protected]>
Quoted 7 lines
Quoted 5 lines
Reviewed-by Donald Hunter <[email protected]>FWIW, the hex can include spaces or not when using
bytes.fromhex(). When formatting hex for output, I chose to include spaces, but I don't really know if that was a good choice or not.I also prefer the spaces for readability.
I formatted it with spaces for clarity, even without spaces it was a bit long for one line. Spaces also has the advantage that you don't have to think about endianness.
Should we define the display hints a bit more in a .rst, or is it OK that they end up being implementation specific for each language library? Do we want them to behave the same in a Rust YNL library, as they do in Python?
BTW: The rest of the key used in the example can be found with this key-gen:
$ printf "hello world" | sha1sum [redacted key material]
Donald Hunter
maintainerRe: [PATCH net-next 10/11] tools: ynl: decode hex input
Quoted 19 lines · Asbjørn Sloth Tønnesen
Quoted 18 lines · Jacob Keller
Quoted 17 lines · Donald Hunter
Quoted 9 lines · Asbjørn Sloth Tønnesen
This patch add support for decoding hex input, so that binary attributes can be read through --json.
Example (using future
wireguard.yaml):$ sudo ./tools/net/ynl/pyynl/cli.py --family wireguard \ --do set-device --json '{"ifindex":3, "private-key":"2a ae 6c 35 c9 4f cf <... to 32 bytes>"}'Signed-off-by Asbjørn Sloth Tønnesen <[email protected]>Reviewed-by Donald Hunter <[email protected]>FWIW, the hex can include spaces or not when using
bytes.fromhex(). When formatting hex for output, I chose to include spaces, but I don't really know if that was a good choice or not.
Quoted 8 lines
Quoted 1 line
I also prefer the spaces for readability.
I formatted it with spaces for clarity, even without spaces it was a bit long for one line. Spaces also has the advantage that you don't have to think about endianness.
Should we define the display hints a bit more in a .rst, or is it OK that they end up being implementation specific for each language library? Do we want them to behave the same in a Rust YNL library, as they do in Python?
Yes we should probably extend the existing doc to at least describe some of the defacto behaviour.
https://docs.kernel.org/userspace-api/netlink/specs.html#display-hint
Quoted 3 lines
BTW: The rest of the key used in the example can be found with this key-gen:
$ printf "hello world" | sha1sum [redacted key material]
Re: [PATCH net-next 10/11] tools: ynl: decode hex input
In reply to Asbjørn Sloth TønnesenQuoted 18 lines · Asbjørn Sloth Tønnesen
This patch add support for decoding hex input, so that binary attributes can be read through --json.
Example (using future
wireguard.yaml):$ sudo ./tools/net/ynl/pyynl/cli.py --family wireguard \ --do set-device --json '{"ifindex":3, "private-key":"2a ae 6c 35 c9 4f cf <... to 32 bytes>"}'Signed-off-by Asbjørn Sloth Tønnesen <[email protected]>--- tools/net/ynl/pyynl/lib/ynl.py | 2 ++ 1 file changed, 2 insertions(+)tools/net/ynl/pyynl/lib/ynl.py +0
-0
tools/net/ynl/pyynl/lib/ynl.py class YnlFamily(SpecFamily): · line 977
Quoted 5 lines
tools/net/ynl/pyynl/lib/ynl.py +2
-0@@ -973,6 +973,8 @@ class YnlFamily(SpecFamily): raw = ip.packed else: raw = int(ip) + elif attr_spec.display_hint == 'hex': + raw = bytes.fromhex(string)
I'm working on a spec for macsec and ended up with a similar change, but doing instead:
+ elif attr_spec.display_hint == 'hex':
+ raw = int(string, 16)
since the destination attribute is u32/u64 and not binary for macsec.
So maybe this should be:
+ if attr_spec['type'] == 'binary':
+ raw = bytes.fromhex(string)
+ else:
+ raw = int(string, 16)
to cover both cases?
I think it matches better what's already in _formatted_string.
(I don't mind having the current patch go in and making this change together with the macsec spec when it's ready)
Quoted 7 lines
tools/net/ynl/pyynl/lib/ynl.py +0
-0else: raise Exception(f"Display hint '{attr_spec.display_hint}' not implemented" f" when parsing '{attr_spec['name']}'")Signature · 1 line
2.51.0
Signature · 1 line
Sabrina
Re: [PATCH net-next 10/11] tools: ynl: decode hex input
Quoted 40 lines · Sabrina Dubroca
Quoted 18 lines · Asbjørn Sloth Tønnesen
This patch add support for decoding hex input, so that binary attributes can be read through --json.
Example (using future
wireguard.yaml):$ sudo ./tools/net/ynl/pyynl/cli.py --family wireguard \ --do set-device --json '{"ifindex":3, "private-key":"2a ae 6c 35 c9 4f cf <... to 32 bytes>"}'Signed-off-by Asbjørn Sloth Tønnesen <[email protected]>--- tools/net/ynl/pyynl/lib/ynl.py | 2 ++ 1 file changed, 2 insertions(+)tools/net/ynl/pyynl/lib/ynl.py +0
-0tools/net/ynl/pyynl/lib/ynl.py class YnlFamily(SpecFamily): · line 977
Quoted 5 lines
tools/net/ynl/pyynl/lib/ynl.py +2
-0@@ -973,6 +973,8 @@ class YnlFamily(SpecFamily): raw = ip.packed else: raw = int(ip) + elif attr_spec.display_hint == 'hex': + raw = bytes.fromhex(string)I'm working on a spec for macsec and ended up with a similar change, but doing instead:
(quoted diff) +2
-0+ elif attr_spec.display_hint == 'hex': + raw = int(string, 16)since the destination attribute is u32/u64 and not binary for macsec.
So maybe this should be:
(quoted diff) +4
-0+ if attr_spec['type'] == 'binary': + raw = bytes.fromhex(string) + else: + raw = int(string, 16)
Quoted 6 lines
to cover both cases?
I think it matches better what's already in
_formatted_string.(I don't mind having the current patch go in and making this change together with the macsec spec when it's ready)
Cool, I will include it in v2, which I hope to get out tomorrow.
PATCH 11/11 tools: ynl: add ipv4-or-v6 display hint
In reply to Asbjørn Sloth TønnesenThe attribute WGALLOWEDIP_A_IPADDR can contain either an IPv4 or an IPv6 address depending on WGALLOWEDIP_A_FAMILY, however in practice it is enough to look at the attribute length.
This patch implements an ipv4-or-v6 display hint, that can deal with this kind of attribute.
It only implements this display hint for genetlink-legacy, it can be added to other protocol variants if needed, but we don't want to encourage it's use.
--- Documentation/netlink/genetlink-legacy.yaml | 2 +- tools/net/ynl/pyynl/lib/ynl.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-)
Documentation/netlink/genetlink-legacy.yaml +1 -1
@@ -154,7 +154,7 @@ properties: Optional format indicator that is intended only for choosing the right formatting mechanism when displaying values of this type. - enum: [ hex, mac, fddi, ipv4, ipv6, uuid ] + enum: [ hex, mac, fddi, ipv4, ipv6, ipv4-or-v6, uuid ] struct: description: Name of the nested struct type. type: string
tools/net/ynl/pyynl/lib/ynl.py +2 -2
@@ -958,7 +958,7 @@ class YnlFamily(SpecFamily): formatted = hex(raw) else: formatted = bytes.hex(raw, ' ') - elif display_hint in [ 'ipv4', 'ipv6' ]: + elif display_hint in [ 'ipv4', 'ipv6', 'ipv4-or-v6' ]: formatted = format(ipaddress.ip_address(raw)) elif display_hint == 'uuid': formatted = str(uuid.UUID(bytes=raw))
@@ -967,7 +967,7 @@ class YnlFamily(SpecFamily): return formatted def _from_string(self, string, attr_spec): - if attr_spec.display_hint in ['ipv4', 'ipv6']: + if attr_spec.display_hint in ['ipv4', 'ipv6', 'ipv4-or-v6']: ip = ipaddress.ip_address(string) if attr_spec['type'] == 'binary': raw = ip.packed
Signature · 1 line
2.51.0
Re: [PATCH net-next 11/11] tools: ynl: add ipv4-or-v6 display hint
Quoted 4 lines · Asbjørn Sloth Tønnesen
The attribute
WGALLOWEDIP_A_IPADDRcan contain either an IPv4 or an IPv6 address depending onWGALLOWEDIP_A_FAMILY, however in practice it is enough to look at the attribute length.
Quoted 8 lines
This patch implements an ipv4-or-v6 display hint, that can deal with this kind of attribute.
It only implements this display hint for genetlink-legacy, it can be added to other protocol variants if needed, but we don't want to encourage it's use.
Signed-off-by Asbjørn Sloth Tønnesen <[email protected]>
I suspect there are occurrences of ipv4 or ipv6 in the existing specs that really should be ipv4-or-ipv6 but the python code doesn't care.
Re: [PATCH net-next 11/11] tools: ynl: add ipv4-or-v6 display hint
Quoted 12 lines · Donald Hunter
Quoted 11 lines · Asbjørn Sloth Tønnesen
The attribute
WGALLOWEDIP_A_IPADDRcan contain either an IPv4 or an IPv6 address depending onWGALLOWEDIP_A_FAMILY, however in practice it is enough to look at the attribute length.This patch implements an ipv4-or-v6 display hint, that can deal with this kind of attribute.
It only implements this display hint for genetlink-legacy, it can be added to other protocol variants if needed, but we don't want to encourage it's use.
Quoted 6 lines
Quoted 1 line
Signed-off-by Asbjørn Sloth Tønnesen <[email protected]>Reviewed-by Donald Hunter <[email protected]>I suspect there are occurrences of ipv4 or ipv6 in the existing specs that really should be ipv4-or-ipv6 but the python code doesn't care.
I haven't been able to find any, containing 'ip' or 'addr'.
Speaking of display hints, then WGPEER_A_ENDPOINT is another interesting case, it is struct sockaddr_in or struct sockaddr_in6, I have left that as a plain binary for now, but maybe that could be a struct map, based on struct length.
attribute-sets:
-
name: wgpeer
[..]
attributes:
[..]
-
name: endpoint
type: binary
struct-map:
- sockaddr_in
- sockaddr_in6With the requirement being, that all structs must have a unique length.