xref: /linux/net/ipv4/metrics.c (revision 41e0d49104dbff888ef6446ea46842fde66c0a76)
1 // SPDX-License-Identifier: GPL-2.0-only
2 #include <linux/netlink.h>
3 #include <linux/rtnetlink.h>
4 #include <linux/types.h>
5 #include <net/ip.h>
6 #include <net/net_namespace.h>
7 #include <net/tcp.h>
8 
9 static int ip_metrics_convert(struct net *net, struct nlattr *fc_mx,
10 			      int fc_mx_len, u32 *metrics,
11 			      struct netlink_ext_ack *extack)
12 {
13 	bool ecn_ca = false;
14 	struct nlattr *nla;
15 	int remaining;
16 
17 	nla_for_each_attr(nla, fc_mx, fc_mx_len, remaining) {
18 		int type = nla_type(nla);
19 		u32 val;
20 
21 		if (!type)
22 			continue;
23 		if (type > RTAX_MAX) {
24 			NL_SET_ERR_MSG(extack, "Invalid metric type");
25 			return -EINVAL;
26 		}
27 
28 		if (type == RTAX_CC_ALGO) {
29 			char tmp[TCP_CA_NAME_MAX];
30 
31 			nla_strscpy(tmp, nla, sizeof(tmp));
32 			val = tcp_ca_get_key_by_name(net, tmp, &ecn_ca);
33 			if (val == TCP_CA_UNSPEC) {
34 				NL_SET_ERR_MSG(extack, "Unknown tcp congestion algorithm");
35 				return -EINVAL;
36 			}
37 		} else {
38 			if (nla_len(nla) != sizeof(u32)) {
39 				NL_SET_ERR_MSG_ATTR(extack, nla,
40 						    "Invalid attribute in metrics");
41 				return -EINVAL;
42 			}
43 			val = nla_get_u32(nla);
44 		}
45 		if (type == RTAX_ADVMSS && val > 65535 - 40)
46 			val = 65535 - 40;
47 		if (type == RTAX_MTU && val > 65535 - 15)
48 			val = 65535 - 15;
49 		if (type == RTAX_HOPLIMIT && val > 255)
50 			val = 255;
51 		if (type == RTAX_FEATURES && (val & ~RTAX_FEATURE_MASK)) {
52 			NL_SET_ERR_MSG(extack, "Unknown flag set in feature mask in metrics attribute");
53 			return -EINVAL;
54 		}
55 		metrics[type - 1] = val;
56 	}
57 
58 	if (ecn_ca)
59 		metrics[RTAX_FEATURES - 1] |= DST_FEATURE_ECN_CA;
60 
61 	return 0;
62 }
63 
64 struct dst_metrics *ip_fib_metrics_init(struct net *net, struct nlattr *fc_mx,
65 					int fc_mx_len,
66 					struct netlink_ext_ack *extack)
67 {
68 	struct dst_metrics *fib_metrics;
69 	int err;
70 
71 	if (!fc_mx)
72 		return (struct dst_metrics *)&dst_default_metrics;
73 
74 	fib_metrics = kzalloc(sizeof(*fib_metrics), GFP_KERNEL);
75 	if (unlikely(!fib_metrics))
76 		return ERR_PTR(-ENOMEM);
77 
78 	err = ip_metrics_convert(net, fc_mx, fc_mx_len, fib_metrics->metrics,
79 				 extack);
80 	if (!err) {
81 		refcount_set(&fib_metrics->refcnt, 1);
82 	} else {
83 		kfree(fib_metrics);
84 		fib_metrics = ERR_PTR(err);
85 	}
86 
87 	return fib_metrics;
88 }
89 EXPORT_SYMBOL_GPL(ip_fib_metrics_init);
90