This is an automated email from the ASF dual-hosted git repository.

xiaoxiang781216 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/nuttx.git

commit a05d365d853135e68948dd4709dc055e5466a722
Author: wangjinjing1 <[email protected]>
AuthorDate: Tue Apr 14 16:37:45 2026 +0800

    net/netlink: add CAN gateway rules over rtnetlink.
    
    net/netforward/can_forward.c walks dev->d_cangw_rules on every received
    CAN frame and forwards the frame to the device that a matching rule
    names, but nothing ever put a rule on that list: the list stayed empty,
    so CAN gateway forwarding could not be used at all.
    
    Accept AF_CAN in RTM_NEWROUTE and build a rule from the request:
    
      - struct rtcanmsg carries the gateway type and the rule flags;
        CGW_FILTER carries the struct can_filter that selects the frames to
        forward, and CGW_SRC_IF and CGW_DST_IF the two devices.
      - netlink_new_can_route() parses the attributes against g_cgw_policy,
        then dispatches on rtcanmsg.gwtype.  Only CGW_TYPE_CAN_CAN is
        handled here; another type gets EAFNOSUPPORT.
      - netlink_add_cangw_rule() refuses a request that names no device, or
        a device that does not exist, before add_cangw_rule() appends the
        rule under the device lock, because the receive path walks the same
        list.
    
    The request is answered with an NLMSG_ERROR response when NLM_F_ACK is
    set, so the caller learns whether the rule was accepted.
    
    include/netpacket/cangw.h holds struct rtcanmsg, the CGW_TYPE_* values
    that its gwtype field takes, and the attribute and flag definitions, so
    a client can build a request without a kernel header; the rule itself
    stays in the existing struct cangw_rule_s.
    
    Assisted-by: Kiro:claude-opus-4
    Signed-off-by: wangjinjing1 <[email protected]>
---
 include/netpacket/cangw.h    | 167 +++++++++++++++++++++++++++++
 include/nuttx/net/cangw.h    |  19 ++--
 net/netforward/can_forward.c |  44 ++++++++
 net/netlink/Kconfig          |   2 +-
 net/netlink/netlink.h        |  13 +++
 net/netlink/netlink_attr.c   |  22 ++++
 net/netlink/netlink_route.c  | 246 ++++++++++++++++++++++++++++++++++++++++++-
 7 files changed, 499 insertions(+), 14 deletions(-)

diff --git a/include/netpacket/cangw.h b/include/netpacket/cangw.h
new file mode 100644
index 00000000000..434fae23d4b
--- /dev/null
+++ b/include/netpacket/cangw.h
@@ -0,0 +1,167 @@
+/****************************************************************************
+ * include/netpacket/cangw.h
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+#ifndef __INCLUDE_NETPACKET_CANGW_H
+#define __INCLUDE_NETPACKET_CANGW_H
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <nuttx/config.h>
+
+#include <nuttx/can.h>
+#include <stdint.h>
+
+/****************************************************************************
+ * Public Type Definitions
+ ****************************************************************************/
+
+#ifdef CONFIG_NET_CANFORWARD
+
+/* Gateway types, the value of rtcanmsg.gwtype */
+
+enum
+{
+  CGW_TYPE_UNSPEC,
+  CGW_TYPE_CAN_CAN,     /* CAN->CAN routing */
+  CGW_TYPE_CAN_ETH1722, /* CAN->Ethernet routing */
+  CGW_TYPE_ETH1722_CAN, /* Ethernet->CAN routing */
+  __CGW_TYPE_MAX
+};
+
+#define CGW_TYPE_MAX (__CGW_TYPE_MAX - 1)
+
+struct rtcanmsg
+{
+  uint8_t  can_family;
+  uint8_t  gwtype;
+  uint16_t flags;
+};
+
+begin_packed_struct struct cgw_frame_mod
+{
+  struct can_frame cf;
+  uint8_t modtype;
+}end_packed_struct;
+
+begin_packed_struct struct cgw_fdframe_mod
+{
+  struct canfd_frame cf;
+  uint8_t modtype;
+}end_packed_struct;
+
+begin_packed_struct struct cgw_csum_xor
+{
+  int8_t from_idx;
+  int8_t to_idx;
+  int8_t result_idx;
+  uint8_t init_xor_val;
+}end_packed_struct;
+
+begin_packed_struct struct cgw_csum_crc8
+{
+  int8_t from_idx;
+  int8_t to_idx;
+  int8_t result_idx;
+  uint8_t init_crc_val;
+  uint8_t final_xor_val;
+  uint8_t crctab[256];
+  uint8_t profile;
+  uint8_t profile_data[20];
+}end_packed_struct;
+
+/* CRC8 profiles (compute CRC for additional data elements - see below) */
+
+enum
+{
+  CGW_CRC8PRF_UNSPEC,
+  CGW_CRC8PRF_1U8,        /* compute one additional u8 value */
+  CGW_CRC8PRF_16U8,       /* u8 value table indexed by data[1] & 0xF */
+  CGW_CRC8PRF_SFFID_XOR,  /* (can_id & 0xFF) ^ (can_id >> 8 & 0xFF) */
+  __CGW_CRC8PRF_MAX
+};
+
+/* CAN->CAN rtnetlink attribute definitions */
+
+enum
+{
+  CGW_UNSPEC,
+  CGW_MOD_AND,    /* CAN frame modification binary AND */
+  CGW_MOD_OR,     /* CAN frame modification binary OR */
+  CGW_MOD_XOR,    /* CAN frame modification binary XOR */
+  CGW_MOD_SET,    /* CAN frame modification set alternate values */
+  CGW_CS_XOR,     /* set data[] XOR checksum into data[index] */
+  CGW_CS_CRC8,    /* set data[] CRC8 checksum into data[index] */
+  CGW_HANDLED,    /* number of handled CAN frames */
+  CGW_DROPPED,    /* number of dropped CAN frames */
+  CGW_SRC_IF,     /* ifindex of source network interface */
+  CGW_DST_IF,     /* ifindex of destination network interface */
+  CGW_FILTER,     /* specify struct can_filter on source CAN device */
+  CGW_DELETED,    /* number of deleted CAN frames (see max_hops param) */
+  CGW_LIM_HOPS,   /* limit the number of hops of this specific rule */
+  CGW_MOD_UID,    /* user defined identifier for modification updates */
+  CGW_FDMOD_AND,  /* CAN FD frame modification binary AND */
+  CGW_FDMOD_OR,   /* CAN FD frame modification binary OR */
+  CGW_FDMOD_XOR,  /* CAN FD frame modification binary XOR */
+  CGW_FDMOD_SET,  /* CAN FD frame modification set alternate values */
+
+  __CGW_MAX
+};
+
+/****************************************************************************
+ * Pre-processor Definitions
+ ****************************************************************************/
+
+#define CGW_MAX (__CGW_MAX - 1)
+
+#define CGW_MOD_FUNCS 4 /* AND OR XOR SET */
+
+/* CAN frame elements that are affected by curr. 3 CAN frame modifications */
+
+#define CGW_MOD_ID      0x01
+#define CGW_MOD_DLC     0x02          /* Classical CAN data length code */
+#define CGW_MOD_LEN     CGW_MOD_DLC   /* CAN FD (plain) data length */
+#define CGW_MOD_DATA    0x04
+#define CGW_MOD_FLAGS   0x08          /* CAN FD flags */
+
+#define CGW_FRAME_MODS  4             /* ID DLC/LEN DATA FLAGS */
+
+#define MAX_MODFUNCTIONS (CGW_MOD_FUNCS * CGW_FRAME_MODS)
+
+#define CGW_FLAGS_CAN_ECHO       0x01
+#define CGW_FLAGS_CAN_SRC_TSTAMP 0x02
+#define CGW_FLAGS_CAN_IIF_TX_OK  0x04
+#define CGW_FLAGS_CAN_FD         0x08
+
+/* length of checksum operation parameters.
+ * idx = index in CAN frame data[]
+ */
+
+#define CGW_CS_XOR_LEN  sizeof(struct cgw_csum_xor)
+#define CGW_CS_CRC8_LEN  sizeof(struct cgw_csum_crc8)
+
+#define CGW_MODATTR_LEN sizeof(struct cgw_frame_mod)
+#define CGW_FDMODATTR_LEN sizeof(struct cgw_fdframe_mod)
+
+#endif /* CONFIG_NET_CANFORWARD */
+#endif /* __INCLUDE_NETPACKET_CANGW_H */
diff --git a/include/nuttx/net/cangw.h b/include/nuttx/net/cangw.h
index 28e5d1e8044..29975342185 100644
--- a/include/nuttx/net/cangw.h
+++ b/include/nuttx/net/cangw.h
@@ -34,6 +34,7 @@
 #include <nuttx/net/netconfig.h>
 #include <nuttx/net/net.h>
 #include <nuttx/can.h>
+#include <netpacket/cangw.h>
 
 /****************************************************************************
  * Pre-processor Definitions
@@ -41,17 +42,6 @@
 
 /* CAN gateway types */
 
-enum
-{
-  CGW_TYPE_UNSPEC,
-  CGW_TYPE_CAN_CAN,     /* CAN->CAN routing */
-  CGW_TYPE_CAN_ETH1722, /* CAN->Ethernet routing */
-  CGW_TYPE_ETH1722_CAN, /* Ethernet->CAN routing */
-  __CGW_TYPE_MAX
-};
-
-#define CGW_TYPE_MAX (__CGW_TYPE_MAX - 1)
-
 /****************************************************************************
  * Public Type Definitions
  ****************************************************************************/
@@ -107,6 +97,13 @@ extern "C"
  * Public Function Prototypes
  ****************************************************************************/
 
+void add_cangw_rule(FAR struct net_driver_s *dev,
+                    FAR struct cangw_rule_s *cgw_rules);
+
+void remove_cangw_rule(FAR struct net_driver_s *dev,
+                       FAR struct cangw_rule_s *cgw_rules,
+                       size_t size);
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/net/netforward/can_forward.c b/net/netforward/can_forward.c
index 5581e5b7979..607b6dc93e3 100644
--- a/net/netforward/can_forward.c
+++ b/net/netforward/can_forward.c
@@ -168,6 +168,50 @@ static inline_function int can_forward_filter(FAR struct 
can_filter *filter,
  * Public Functions
  ****************************************************************************/
 
+/****************************************************************************
+ * Name: add_cangw_rule
+ *
+ * Description:
+ *   Add a CAN->CAN gateway rule to a dev gw rule list.
+ *
+ ****************************************************************************/
+
+void add_cangw_rule(FAR struct net_driver_s *dev,
+                    FAR struct cangw_rule_s *cgw_rules)
+{
+  DEBUGASSERT(dev && cgw_rules);
+
+  netdev_lock(dev);
+  sq_addlast(&cgw_rules->node, &dev->d_cangw_rules);
+  netdev_unlock(dev);
+}
+
+/****************************************************************************
+ * Name: remove_cangw_rule
+ *
+ * Description:
+ *   Remove a CAN->CAN gateway rule from device.
+ *
+ ****************************************************************************/
+
+void remove_cangw_rule(FAR struct net_driver_s *dev,
+                       FAR struct cangw_rule_s *cgw_rules,
+                       size_t size)
+{
+  size_t i;
+
+  DEBUGASSERT(dev && cgw_rules);
+
+  netdev_lock(dev);
+
+  for (i = 0; i < size; i++)
+    {
+      sq_rem(&cgw_rules[i].node, &dev->d_cangw_rules);
+    }
+
+  netdev_unlock(dev);
+}
+
 /****************************************************************************
  * Name: can_forward
  *
diff --git a/net/netlink/Kconfig b/net/netlink/Kconfig
index 7d660faf70c..239fb33ae75 100644
--- a/net/netlink/Kconfig
+++ b/net/netlink/Kconfig
@@ -110,7 +110,7 @@ config NETLINK_DISABLE_NEWROUTE
        bool "Disable RTM_NEWROUTE support"
        default n
        ---help---
-               RTM_NEWROUTE is used to add a route.
+               RTM_NEWROUTE is used to add a route or a gateway rule.
 
 config NETLINK_DISABLE_GETROUTE
        bool "Disable RTM_GETROUTE support"
diff --git a/net/netlink/netlink.h b/net/netlink/netlink.h
index 538c92571ef..2f54a6f8f09 100644
--- a/net/netlink/netlink.h
+++ b/net/netlink/netlink.h
@@ -32,6 +32,7 @@
 #include <sys/types.h>
 #include <poll.h>
 
+#include <netpacket/cangw.h>
 #include <netpacket/netlink.h>
 #include <nuttx/queue.h>
 #include <nuttx/net/icmpv6.h>
@@ -614,6 +615,18 @@ int nla_parse(FAR struct nlattr **tb, int maxtype,
               FAR const struct nlattr *head,
               int len, FAR const struct nla_policy *policy,
               FAR struct netlink_ext_ack *extack);
+
+/****************************************************************************
+ * nla_memcpy - Copy a netlink attribute into another memory area
+ *
+ * Note: The number of bytes copied is limited by the length of
+ *       attribute's payload. memcpy
+ *
+ * Returns the number of bytes copied.
+ ****************************************************************************/
+
+int nla_memcpy(FAR void *dest, FAR const struct nlattr *src, int count);
+
 #endif /* CONFIG_NETLINK_ROUTE */
 
 /****************************************************************************
diff --git a/net/netlink/netlink_attr.c b/net/netlink/netlink_attr.c
index 33d39da09a1..7eeea4e99ae 100644
--- a/net/netlink/netlink_attr.c
+++ b/net/netlink/netlink_attr.c
@@ -332,3 +332,25 @@ int nla_parse(FAR struct nlattr **tb, int maxtype,
 errout:
   return err;
 }
+
+/****************************************************************************
+ * nla_memcpy - Copy a netlink attribute into another memory area
+ *
+ * Note: The number of bytes copied is limited by the length of
+ *       attribute's payload. memcpy
+ *
+ * Returns the number of bytes copied.
+ ****************************************************************************/
+
+int nla_memcpy(FAR void *dest, FAR const struct nlattr *src, int count)
+{
+  int minlen = MIN(count, nla_len(src));
+
+  memcpy(dest, nla_data(src), minlen);
+  if (count > minlen)
+    {
+      memset(dest + minlen, 0, count - minlen);
+    }
+
+  return minlen;
+}
diff --git a/net/netlink/netlink_route.c b/net/netlink/netlink_route.c
index d0e354fdf9f..0f5ae12661a 100644
--- a/net/netlink/netlink_route.c
+++ b/net/netlink/netlink_route.c
@@ -43,7 +43,9 @@
 #include <nuttx/net/ip.h>
 #include <nuttx/net/neighbor.h>
 #include <nuttx/net/netlink.h>
-
+#ifdef CONFIG_NET_CANFORWARD
+#include <nuttx/net/cangw.h>
+#endif
 #include "netdev/netdev.h"
 #include "arp/arp.h"
 #include "inet/inet.h"
@@ -210,6 +212,20 @@ struct getprefix_recvfrom_rsplist_s
   struct getprefix_recvfrom_response_s payload;
 };
 
+/* RTM_NEWROUTE:  response the ack of adding a new route */
+
+struct new_ccgw_rule_response_s
+{
+  struct nlmsghdr hdr;
+  struct nlmsgerr err;
+};
+
+struct new_ccgw_rule_resplist_s
+{
+  sq_entry_t flink;
+  struct new_ccgw_rule_response_s payload;
+};
+
 /* netdev_foreach() callback */
 
 struct nlroute_sendto_request_s
@@ -272,6 +288,87 @@ static_assert(nitems(g_ifa_ipv6_policy) ==
 #  define g_ifa_ipv6_policy NULL
 #endif
 
+#if !defined(CONFIG_NETLINK_DISABLE_NEWROUTE) && \
+    defined(CONFIG_NET_CANFORWARD)
+const struct nla_policy g_cgw_policy[CGW_MAX + 1] =
+{
+  [CGW_MOD_AND] =
+    {
+      .len = sizeof(struct cgw_frame_mod)
+    },
+
+  [CGW_MOD_OR] =
+    {
+      .len = sizeof(struct cgw_frame_mod)
+    },
+
+  [CGW_MOD_XOR] =
+    {
+      .len = sizeof(struct cgw_frame_mod)
+    },
+
+  [CGW_MOD_SET] =
+    {
+      .len = sizeof(struct cgw_frame_mod)
+    },
+
+  [CGW_CS_XOR] =
+    {
+      .len = sizeof(struct cgw_csum_xor)
+    },
+
+  [CGW_CS_CRC8] =
+    {
+      .len = sizeof(struct cgw_csum_crc8)
+    },
+
+  [CGW_SRC_IF] =
+    {
+      .type = NLA_U32
+    },
+
+  [CGW_DST_IF] =
+    {
+      .type = NLA_U32
+    },
+
+  [CGW_FILTER] =
+    {
+      .len = sizeof(struct can_filter)
+    },
+
+  [CGW_LIM_HOPS] =
+    {
+      .type = NLA_U8
+    },
+
+  [CGW_MOD_UID] =
+    {
+      .type = NLA_U32
+    },
+
+  [CGW_FDMOD_AND] =
+    {
+      .len = sizeof(struct cgw_fdframe_mod)
+    },
+
+  [CGW_FDMOD_OR] =
+    {
+      .len = sizeof(struct cgw_fdframe_mod)
+    },
+
+  [CGW_FDMOD_XOR] =
+    {
+      .len = sizeof(struct cgw_fdframe_mod)
+    },
+
+  [CGW_FDMOD_SET] =
+    {
+      .len = sizeof(struct cgw_fdframe_mod)
+    },
+};
+#endif
+
 /****************************************************************************
  * Private Functions
  ****************************************************************************/
@@ -1410,6 +1507,139 @@ netlink_fill_ipv6prefix(FAR struct net_driver_s *dev, 
int type,
 }
 #endif
 
+#if !defined(CONFIG_NETLINK_DISABLE_NEWROUTE) && \
+    defined(CONFIG_NET_CANFORWARD)
+
+static int netlink_add_cangw_rule(FAR struct rtcanmsg *rt_msg,
+                                  FAR struct nlattr *tb[])
+{
+  FAR struct cangw_rule_s *cgw_rule;
+  FAR struct net_driver_s *src_dev;
+  uint32_t src_if;
+  uint32_t dst_if;
+  int ret;
+
+  /* Allocate and zero-initialize cangw_rule structure */
+
+  cgw_rule = kmm_zalloc(sizeof(struct cangw_rule_s));
+  if (cgw_rule == NULL)
+    {
+      nwarn("Failed to allocate cangw_rule structure\n");
+      ret = -ENOMEM;
+      goto errout;
+    }
+
+  cgw_rule->gwtype = rt_msg->gwtype;
+  cgw_rule->flags  = rt_msg->flags;
+
+  /* check for can_filter in attributes */
+
+  if (tb[CGW_FILTER])
+    {
+      nla_memcpy(&cgw_rule->gw.ccgw.filter, tb[CGW_FILTER],
+                  sizeof(struct can_filter));
+    }
+
+  ret = -ENODEV;
+
+  /* specifying two interfaces is mandatory */
+
+  if (!tb[CGW_SRC_IF] || !tb[CGW_DST_IF])
+    {
+      goto errout_with_rule;
+    }
+
+  src_if = *(FAR uint32_t *)nla_data(tb[CGW_SRC_IF]);
+  dst_if = *(FAR uint32_t *)nla_data(tb[CGW_DST_IF]);
+
+  src_dev = netdev_findbyindex(src_if);
+  cgw_rule->dest_dev = netdev_findbyindex(dst_if);
+
+  if (src_dev == NULL || cgw_rule->dest_dev == NULL)
+    {
+      goto errout_with_rule;
+    }
+
+  add_cangw_rule(src_dev, cgw_rule);
+  return OK;
+
+errout_with_rule:
+  if (cgw_rule != NULL)
+    {
+      kmm_free(cgw_rule);
+    }
+
+errout:
+  return ret;
+}
+
+static int netlink_new_can_route(FAR const struct nlmsghdr *nlmsg)
+{
+  FAR struct nlattr *tb[CGW_MAX + 1];
+  FAR struct rtcanmsg *rt_msg = nlmsg_data(nlmsg);
+  int ret;
+
+  /* nlmsg boundary check */
+
+  if (nlmsg->nlmsg_len < nlmsg_msg_size(sizeof(struct rtcanmsg)))
+    {
+      return -EINVAL;
+    }
+
+  /* parse nlmsg and acquire tb. */
+
+  ret = nlmsg_parse(nlmsg, sizeof(struct rtcanmsg), tb, CGW_MAX,
+                    g_cgw_policy, NULL);
+  if (ret < 0)
+    {
+      nwarn("nlmsg_parse failed: %d\n", ret);
+      return ret;
+    }
+
+  /* get r->gwtype and switch r->gwtype */
+
+  switch (rt_msg->gwtype)
+    {
+      case CGW_TYPE_CAN_CAN:
+        return netlink_add_cangw_rule(rt_msg, tb);
+
+      default:
+        return -EAFNOSUPPORT;
+    }
+}
+
+static void netlink_can_ack(NETLINK_HANDLE handle,
+                            FAR const struct nlmsghdr *nlmsg,
+                            int err)
+{
+  FAR struct new_ccgw_rule_response_s *resp;
+  FAR struct new_ccgw_rule_resplist_s *alloc =
+             kmm_zalloc(sizeof(struct new_ccgw_rule_resplist_s));
+
+  if (alloc == NULL)
+    {
+      nerr("ERROR: Failed to allocate response buffer "
+           "about new ccgw rule.\n");
+      return;
+    }
+
+  resp = &alloc->payload;
+  resp->hdr.nlmsg_len   = sizeof(struct new_ccgw_rule_response_s);
+  resp->hdr.nlmsg_type  = NLMSG_ERROR;
+  resp->hdr.nlmsg_flags = nlmsg->nlmsg_flags;
+  resp->hdr.nlmsg_seq   = nlmsg->nlmsg_seq;
+  resp->hdr.nlmsg_pid   = nlmsg->nlmsg_pid;
+  resp->err.error       = err;
+  resp->err.msg         = *nlmsg;
+
+  /* Finally, add the response to the list of pending responses */
+
+  netlink_add_response(handle,
+                       (FAR struct netlink_response_s *)alloc);
+}
+
+#endif /* CONFIG_NETLINK_DISABLE_NEWROUTE && CONFIG_NET_CANFORWARD */
+
 /****************************************************************************
  * Public Functions
  ****************************************************************************/
@@ -1760,7 +1990,7 @@ ssize_t netlink_route_sendto(NETLINK_HANDLE handle,
         break;
 #endif
 #ifndef CONFIG_NETLINK_DISABLE_NEWROUTE
-      /* Add a route */
+      /* Add a route or a CAN gateway rule */
 
       case RTM_NEWROUTE:
 #ifdef CONFIG_NET_IPv4
@@ -1776,6 +2006,17 @@ ssize_t netlink_route_sendto(NETLINK_HANDLE handle,
             ret = netlink_new_ipv6route(nlmsg);
           }
         else
+#endif
+#ifdef CONFIG_NET_CANFORWARD
+        if (req->gen.rtgen_family == AF_CAN)
+          {
+            ret = netlink_new_can_route(nlmsg);
+            if (nlmsg->nlmsg_flags & NLM_F_ACK)
+              {
+                netlink_can_ack(handle, nlmsg, ret);
+              }
+          }
+        else
 #endif
           {
             ret = -EAFNOSUPPORT;
@@ -1784,6 +2025,7 @@ ssize_t netlink_route_sendto(NETLINK_HANDLE handle,
           }
         break;
 #endif
+
       default:
         ret = -ENOSYS;
         break;

Reply via email to