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-apps.git

commit 986e003f098f2384fb8b508bbb11ba6481194278
Author: daichuan <[email protected]>
AuthorDate: Wed Feb 19 18:31:38 2025 +0800

    netutils/rpmsg_tun: forward a TUN device over an RPMsg socket.
    
    Add rpmsg_tun_server and rpmsg_tun_client, which bridge a local TUN
    interface to a peer CPU through an AF_RPMSG stream socket, so one core
    can offload IP traffic to the network stack of another.
    
      rpmsg_tun_server <tunname> <ip> <mask> [<ifname>]
      rpmsg_tun_client <tunname> <ip> <mask> <cpu>
    
    Each side configures the TUN interface, then copies packets between the
    TUN fd and the RPMsg socket.  When <ifname> is given, the server watches
    that interface through netlink and only serves the peer while it is
    running and has an IPv4 address; it drops the link when the interface
    goes down, so DHCP traffic is not forwarded to the wrong interface.
    The client retries the connection every 3 seconds until the server is
    available instead of spinning on the CPU.
    
    Signed-off-by: daichuan <[email protected]>
    Assisted-by: Kiro:claude-opus-4
---
 netutils/rpmsg_tun/CMakeLists.txt     |  51 +++
 netutils/rpmsg_tun/Kconfig            |  35 ++
 netutils/rpmsg_tun/Make.defs          |  25 ++
 netutils/rpmsg_tun/Makefile           |  43 ++
 netutils/rpmsg_tun/rpmsg_tun_client.c |  90 ++++
 netutils/rpmsg_tun/rpmsg_tun_server.c | 200 +++++++++
 netutils/rpmsg_tun/rpmsg_tun_util.c   | 794 ++++++++++++++++++++++++++++++++++
 netutils/rpmsg_tun/rpmsg_tun_util.h   | 206 +++++++++
 8 files changed, 1444 insertions(+)

diff --git a/netutils/rpmsg_tun/CMakeLists.txt 
b/netutils/rpmsg_tun/CMakeLists.txt
new file mode 100644
index 000000000..72a6d4b14
--- /dev/null
+++ b/netutils/rpmsg_tun/CMakeLists.txt
@@ -0,0 +1,51 @@
+# 
##############################################################################
+# apps/netutils/rpmsg_tun/CMakeLists.txt
+#
+# 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.
+#
+# 
##############################################################################
+
+if(CONFIG_NETUTILS_RPMSG_TUN_CLIENT)
+  nuttx_add_application(
+    NAME
+    "rpmsg_tun_client"
+    SRCS
+    rpmsg_tun_client.c
+    rpmsg_tun_util.c
+    MODULE
+    ${CONFIG_NETUTILS_RPMSG_TUN_CLIENT}
+    STACKSIZE
+    ${CONFIG_NETUTILS_RPMSG_TUN_STACKSIZE}
+    PRIORITY
+    ${CONFIG_NETUTILS_RPMSG_TUN_PRIORITY})
+endif()
+
+if(CONFIG_NETUTILS_RPMSG_TUN_SERVER)
+  nuttx_add_application(
+    NAME
+    "rpmsg_tun_server"
+    SRCS
+    rpmsg_tun_server.c
+    rpmsg_tun_util.c
+    MODULE
+    ${CONFIG_NETUTILS_RPMSG_TUN_SERVER}
+    STACKSIZE
+    ${CONFIG_NETUTILS_RPMSG_TUN_STACKSIZE}
+    PRIORITY
+    ${CONFIG_NETUTILS_RPMSG_TUN_PRIORITY})
+endif()
diff --git a/netutils/rpmsg_tun/Kconfig b/netutils/rpmsg_tun/Kconfig
new file mode 100644
index 000000000..f4767e2a4
--- /dev/null
+++ b/netutils/rpmsg_tun/Kconfig
@@ -0,0 +1,35 @@
+#
+# For a description of the syntax of this configuration file,
+# see the file kconfig-language.txt in the NuttX tools repository.
+#
+
+config NETUTILS_RPMSG_TUN
+       bool
+       depends on RPMSG && NET_TUN
+       default n
+       ---help---
+               If NETUTILS_RPMSG_TUN is enabled, it allows using
+               a TUN device to send and receive data via RPMsg socket.
+
+config NETUTILS_RPMSG_TUN_CLIENT
+       tristate "Remote tun device with rpmsg socket client"
+       select NETUTILS_RPMSG_TUN
+       default n
+
+config NETUTILS_RPMSG_TUN_SERVER
+       tristate "Remote tun device with rpmsg socket server"
+       depends on NET_NETLINK
+       select NETUTILS_RPMSG_TUN
+       default n
+
+if NETUTILS_RPMSG_TUN
+
+config NETUTILS_RPMSG_TUN_PRIORITY
+       int "Remote tun device with rpmsg socket task priority"
+       default 100
+
+config NETUTILS_RPMSG_TUN_STACKSIZE
+       int "Remote tun device with rpmsg socket task stack size"
+       default 4096
+
+endif
diff --git a/netutils/rpmsg_tun/Make.defs b/netutils/rpmsg_tun/Make.defs
new file mode 100644
index 000000000..2b58caca5
--- /dev/null
+++ b/netutils/rpmsg_tun/Make.defs
@@ -0,0 +1,25 @@
+############################################################################
+# apps/netutils/rpmsg_tun/Make.defs
+#
+# 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.
+#
+############################################################################
+
+ifneq ($(CONFIG_NETUTILS_RPMSG_TUN),)
+CONFIGURED_APPS += $(APPDIR)/netutils/rpmsg_tun
+endif
diff --git a/netutils/rpmsg_tun/Makefile b/netutils/rpmsg_tun/Makefile
new file mode 100644
index 000000000..c98d56831
--- /dev/null
+++ b/netutils/rpmsg_tun/Makefile
@@ -0,0 +1,43 @@
+############################################################################
+# apps/netutils/rpmsg_tun/Makefile
+#
+# 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.
+#
+############################################################################
+
+include $(APPDIR)/Make.defs
+
+ifneq ($(CONFIG_NETUTILS_RPMSG_TUN_CLIENT),)
+  PROGNAME  += rpmsg_tun_client
+  MAINSRC   += rpmsg_tun_client.c
+  MODULE    += $(CONFIG_NETUTILS_RPMSG_TUN_CLIENT)
+  PRIORITY  += $(CONFIG_NETUTILS_RPMSG_TUN_PRIORITY)
+  STACKSIZE += $(CONFIG_NETUTILS_RPMSG_TUN_STACKSIZE)
+endif
+
+ifneq ($(CONFIG_NETUTILS_RPMSG_TUN_SERVER),)
+  PROGNAME  += rpmsg_tun_server
+  MAINSRC   += rpmsg_tun_server.c
+  MODULE    += $(CONFIG_NETUTILS_RPMSG_TUN_SERVER)
+  PRIORITY  += $(CONFIG_NETUTILS_RPMSG_TUN_PRIORITY)
+  STACKSIZE += $(CONFIG_NETUTILS_RPMSG_TUN_STACKSIZE)
+endif
+
+CSRCS += rpmsg_tun_util.c
+
+include $(APPDIR)/Application.mk
diff --git a/netutils/rpmsg_tun/rpmsg_tun_client.c 
b/netutils/rpmsg_tun/rpmsg_tun_client.c
new file mode 100644
index 000000000..621e896a0
--- /dev/null
+++ b/netutils/rpmsg_tun/rpmsg_tun_client.c
@@ -0,0 +1,90 @@
+/****************************************************************************
+ * apps/netutils/rpmsg_tun/rpmsg_tun_client.c
+ *
+ * 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.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "rpmsg_tun_util.h"
+
+/****************************************************************************
+ * Public Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: main
+ ****************************************************************************/
+
+int main(int argc, char *argv[])
+{
+  int rpmsgfd;
+  int tunfd;
+  int ret;
+
+  if (argc != 5)
+    {
+      fprintf(stderr, "Usage: %s <tunname> <ip> <mask> <cpu>\n", argv[0]);
+      return -EINVAL;
+    }
+
+  tunfd = rpmsg_tun_setup(argv[1], argv[2], argv[3]);
+  if (tunfd < 0)
+    {
+      return tunfd;
+    }
+
+  for (; ; )
+    {
+      rpmsgfd = rpmsg_tun_connect(argv[4], argv[1]);
+      if (rpmsgfd < 0)
+        {
+          sleep(3);
+          continue;
+        }
+
+      ret = rpmsg_tun_set_running(tunfd, true);
+      if (ret < 0)
+        {
+          break;
+        }
+
+      rpmsg_tun_loop(tunfd, rpmsgfd);
+
+      ret = rpmsg_tun_set_running(tunfd, false);
+      if (ret < 0)
+        {
+          break;
+        }
+
+      close(rpmsgfd);
+    }
+
+  close(rpmsgfd);
+  close(tunfd);
+
+  return ret;
+}
diff --git a/netutils/rpmsg_tun/rpmsg_tun_server.c 
b/netutils/rpmsg_tun/rpmsg_tun_server.c
new file mode 100644
index 000000000..f5439ae94
--- /dev/null
+++ b/netutils/rpmsg_tun/rpmsg_tun_server.c
@@ -0,0 +1,200 @@
+/****************************************************************************
+ * apps/netutils/rpmsg_tun/rpmsg_tun_server.c
+ *
+ * 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.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <errno.h>
+#include <poll.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "rpmsg_tun_util.h"
+
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: rpmsg_tun_netlink_loop
+ *
+ * Description:
+ *   Poll tunfd and rpmsgfd and nlfd when fds return POLLIN
+ *   then read buffer from tunfd and send to rpmsgfd
+ *   or read buffer from rpmsgfd and send to tunfd
+ *
+ * Parameters:
+ *   tunfd   - tun device fd
+ *   rpmsgfd - rpmsg socket fd
+ *   nlfd    - netlink socket fd
+ *   name    - network device name
+ *
+ * Returned Value:
+ *   None
+ ****************************************************************************/
+
+static void
+rpmsg_tun_netlink_loop(int tunfd, int rpmsgfd, int nlfd, const char *name)
+{
+  struct pollfd fds[3];
+
+  memset(fds, 0, sizeof(fds));
+  fds[0].fd = tunfd;
+  fds[0].events = POLLIN;
+  fds[1].fd = rpmsgfd;
+  fds[1].events = POLLIN;
+  fds[2].fd = nlfd;
+  fds[2].events = POLLIN;
+
+  for (; ; )
+    {
+      if (poll(fds, 3, -1) < 0)
+        {
+          break;
+        }
+
+      if ((fds[0].revents | fds[1].revents | fds[2].revents) & POLLIN)
+        {
+          if (fds[0].revents & POLLIN)
+            {
+              if (rpmsg_tun_to_socket(tunfd, rpmsgfd) < 0)
+                {
+                  break;
+                }
+            }
+
+          if (fds[1].revents & POLLIN)
+            {
+              if (rpmsg_tun_from_socket(tunfd, rpmsgfd) < 0)
+                {
+                  break;
+                }
+            }
+
+          if (fds[2].revents & POLLIN)
+            {
+              if (rpmsg_tun_process_netlink(nlfd, name) <= 0)
+                {
+                  break;
+                }
+            }
+        }
+      else if ((fds[0].revents | fds[1].revents |
+                fds[2].revents) & (POLLHUP | POLLERR))
+        {
+          break;
+        }
+    }
+}
+
+/****************************************************************************
+ * Public Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: main
+ ****************************************************************************/
+
+int main(int argc, char *argv[])
+{
+  int nlfd = -1;
+  int rpmsgfd;
+  int tunfd;
+  int ret;
+
+  if (argc != 4 && argc != 5)
+    {
+      fprintf(stderr, "Usage: %s <tunname> <ip> <mask> <ifname> or\n"
+                      "Usage: %s <tunname> <ip> <mask>\n", argv[0], argv[0]);
+      return -EINVAL;
+    }
+
+  tunfd = rpmsg_tun_setup(argv[1], argv[2], argv[3]);
+  if (tunfd < 0)
+    {
+      return tunfd;
+    }
+
+  if (argc == 5)
+    {
+      nlfd = rpmsg_tun_connect_netlink();
+      if (nlfd < 0)
+        {
+          close(tunfd);
+          return nlfd;
+        }
+    }
+
+  for (; ; )
+    {
+      if (nlfd >= 0)
+        {
+          ret = rpmsg_tun_wait_running(nlfd, argv[4]);
+          if (ret < 0)
+            {
+              goto out;
+            }
+        }
+
+      rpmsgfd = rpmsg_tun_accept(argv[1]);
+      if (rpmsgfd < 0)
+        {
+          continue;
+        }
+
+      ret = rpmsg_tun_set_running(tunfd, true);
+      if (ret < 0)
+        {
+          break;
+        }
+
+      if (nlfd >= 0)
+        {
+          rpmsg_tun_netlink_loop(tunfd, rpmsgfd, nlfd, argv[4]);
+        }
+      else
+        {
+          rpmsg_tun_loop(tunfd, rpmsgfd);
+        }
+
+      ret = rpmsg_tun_set_running(tunfd, false);
+      if (ret < 0)
+        {
+          break;
+        }
+
+      close(rpmsgfd);
+    }
+
+  close(rpmsgfd);
+
+out:
+  if (nlfd >= 0)
+    {
+      close(nlfd);
+    }
+
+  close(tunfd);
+  return ret;
+}
diff --git a/netutils/rpmsg_tun/rpmsg_tun_util.c 
b/netutils/rpmsg_tun/rpmsg_tun_util.c
new file mode 100644
index 000000000..800515590
--- /dev/null
+++ b/netutils/rpmsg_tun/rpmsg_tun_util.c
@@ -0,0 +1,794 @@
+/****************************************************************************
+ * apps/netutils/rpmsg_tun/rpmsg_tun_util.c
+ *
+ * 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.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <arpa/inet.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <net/if.h>
+#include <netinet/in.h>
+#include <netpacket/rpmsg.h>
+#ifdef __NuttX__
+#  include <netpacket/netlink.h>
+#  include <nuttx/net/tun.h>
+#else
+#  include <linux/if_tun.h>
+#  include <linux/rtnetlink.h>
+#endif
+#include <poll.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/socket.h>
+#include <unistd.h>
+
+#include "rpmsg_tun_util.h"
+
+/****************************************************************************
+ * Pre-processor Definitions
+ ****************************************************************************/
+
+#define RPMSG_TUN_BUFFER_SIZE     2048
+
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: rpmsg_tun_set_addr
+ *
+ * Description:
+ *   Set ip/mask address to tun device
+ *
+ * Parameters:
+ *   name - tun device name
+ *   cmd  - ioctl cmd
+ *   addr - ip/mask address
+ *
+ * Returned Value:
+ *   0 on success, -errno on failure.
+ ****************************************************************************/
+
+static int rpmsg_tun_set_addr(const char *name, int cmd, const char *addr)
+{
+  struct sockaddr_in *sin;
+  struct ifreq ifr;
+  int fd;
+
+  fd = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
+  if (fd < 0)
+    {
+      return -errno;
+    }
+
+  memset(&ifr, 0, sizeof(ifr));
+  strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name) - 1);
+
+  sin = (struct sockaddr_in *)&ifr.ifr_addr;
+  sin->sin_family = AF_INET;
+  inet_aton(addr, &sin->sin_addr);
+
+  if (ioctl(fd, cmd, &ifr) < 0)
+    {
+      close(fd);
+      return -errno;
+    }
+
+  close(fd);
+  return 0;
+}
+
+/****************************************************************************
+ * Name: rpmsg_tun_send_all
+ *
+ * Description:
+ *   Send all data buffer to file handle
+ *
+ * Parameters:
+ *   fd  - file handle
+ *   buf - data buffer
+ *   len - data length
+ *
+ * Returned Value:
+ *   int - 0 on success, -errno on failure.
+ ****************************************************************************/
+
+static int rpmsg_tun_send_all(int fd, const void *buf_, size_t len)
+{
+  const char *buf = buf_;
+
+  while (len > 0)
+    {
+      ssize_t ret = send(fd, buf, len, 0);
+
+      if (ret < 0)
+        {
+          return -errno;
+        }
+
+      len -= ret;
+      buf += ret;
+    }
+
+  return 0;
+}
+
+/****************************************************************************
+ * Name: rpmsg_tun_recv_all
+ *
+ * Description:
+ *   Receive all data buffer from file handle
+ *
+ * Parameters:
+ *   fd  - file handle
+ *   buf - data buffer
+ *   len - data length
+ *
+ * Returned Value:
+ *   int - 0 on success, -errno on failure.
+ ****************************************************************************/
+
+static int rpmsg_tun_recv_all(int fd, void *buf_, size_t len)
+{
+  char *buf = buf_;
+
+  while (len > 0)
+    {
+      ssize_t ret = recv(fd, buf, len, 0);
+
+      if (ret <= 0)
+        {
+          return ret ? -errno : -EPIPE;
+        }
+
+      len -= ret;
+      buf += ret;
+    }
+
+  return 0;
+}
+
+/****************************************************************************
+ * Name: rpmsg_tun_is_running
+ *
+ * Description:
+ *   Check network device running status
+ *
+ * Parameters:
+ *   name - network device name
+ *
+ * Returned Value:
+ *   1 is running and get ip address, 0 is down or not set ip addr,
+ *   -errno on failure.
+ ****************************************************************************/
+
+static int rpmsg_tun_is_running(const char *name)
+{
+  struct ifreq ifr;
+  int fd;
+
+  fd = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
+  if (fd < 0)
+    {
+      return -errno;
+    }
+
+  memset(&ifr, 0, sizeof(ifr));
+  strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name) - 1);
+
+  if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0)
+    {
+      close(fd);
+      return -errno;
+    }
+
+  if ((ifr.ifr_flags & IFF_RUNNING) != 0)
+    {
+      if (ioctl(fd, SIOCGIFADDR, &ifr) < 0)
+        {
+          close(fd);
+          return -errno;
+        }
+
+      struct sockaddr_in *addr = (struct sockaddr_in *)&ifr.ifr_addr;
+
+      if (addr->sin_addr.s_addr != INADDR_ANY)
+        {
+          close(fd);
+          return 1;
+        }
+    }
+
+  close(fd);
+  return 0;
+}
+
+/****************************************************************************
+ * Public Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: rpmsg_tun_setup
+ *
+ * Description:
+ *   Setup tun device
+ *
+ * Parameters:
+ *   name - tun device name
+ *   ip   - tun device ip
+ *   mask - tun device mask
+ *
+ * Returned Value:
+ *   int - tun fd on success, -errno on failure.
+ ****************************************************************************/
+
+int rpmsg_tun_setup(const char *name, const char *ip, const char *mask)
+{
+  struct ifreq ifr;
+  int fd;
+
+  /* Open the tun device */
+
+  fd = open("/dev/net/tun", O_RDWR | O_CLOEXEC);
+  if (fd < 0)
+    {
+      return -errno;
+    }
+
+  /* Configure the tun device */
+
+  memset(&ifr, 0, sizeof(ifr));
+  ifr.ifr_flags = IFF_TUN | IFF_NO_PI;
+  strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name) - 1);
+
+  if (ioctl(fd, TUNSETIFF, &ifr) < 0)
+    {
+      goto out;
+    }
+
+  if (rpmsg_tun_set_addr(name, SIOCSIFADDR, ip) < 0)
+    {
+      goto out;
+    }
+
+  if (rpmsg_tun_set_addr(name, SIOCSIFNETMASK, mask) < 0)
+    {
+      goto out;
+    }
+
+  return fd;
+
+out:
+  close(fd);
+  return -errno;
+}
+
+/****************************************************************************
+ * Name: rpmsg_tun_set_running
+ *
+ * Description:
+ *   Set tun device running status
+ *
+ * Parameters:
+ *   fd      - tun device fd
+ *   running - true is running and false is down
+ *
+ * Returned Value:
+ *   0 on success, -errno on failure.
+ ****************************************************************************/
+
+int rpmsg_tun_set_running(int fd, bool running)
+{
+  struct ifreq ifr;
+  int carrier = running;
+  int sockfd;
+
+  memset(&ifr, 0, sizeof(ifr));
+
+  /* Get tun device name */
+
+  if (ioctl(fd, TUNGETIFF, &ifr) < 0)
+    {
+      return -errno;
+    }
+
+  sockfd = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
+  if (sockfd < 0)
+    {
+      return -errno;
+    }
+
+  if (ioctl(sockfd, SIOCGIFFLAGS, &ifr) < 0)
+    {
+      goto out;
+    }
+
+  if (running)
+    {
+      ifr.ifr_flags |= IFF_UP;
+
+      if (ioctl(sockfd, SIOCSIFFLAGS, &ifr) < 0)
+        {
+          goto out;
+        }
+
+      if (ioctl(fd, TUNSETCARRIER, &carrier) < 0)
+        {
+          goto out;
+        }
+    }
+  else
+    {
+      ifr.ifr_flags &= ~IFF_UP;
+
+      if (ioctl(fd, TUNSETCARRIER, &carrier) < 0)
+        {
+          goto out;
+        }
+
+      if (ioctl(sockfd, SIOCSIFFLAGS, &ifr) < 0)
+        {
+          goto out;
+        }
+    }
+
+  close(sockfd);
+  return 0;
+
+out:
+  close(sockfd);
+  return -errno;
+}
+
+/****************************************************************************
+ * Name: rpmsg_tun_connect
+ *
+ * Description:
+ *   Create rpmsg socket and connect to server
+ *
+ * Parameters:
+ *   cpu  - remote cpu name
+ *   name - tun device name
+ *
+ * Returned Value:
+ *   int - rpmsg socket fd on success, -errno on failure.
+ ****************************************************************************/
+
+int rpmsg_tun_connect(const char *cpu, const char *name)
+{
+  struct sockaddr_rpmsg addr;
+  int fd;
+
+  /* Create rpmsg socket */
+
+  fd = socket(AF_RPMSG, SOCK_STREAM | SOCK_CLOEXEC, 0);
+  if (fd < 0)
+    {
+      return -errno;
+    }
+
+  /* Initialize address */
+
+  memset(&addr, 0, sizeof(addr));
+  addr.rp_family = AF_RPMSG;
+  strncpy(addr.rp_cpu, cpu, sizeof(addr.rp_cpu) - 1);
+  strncpy(addr.rp_name, name, sizeof(addr.rp_name) - 1);
+
+  /* Connect to remote server */
+
+  if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
+    {
+      close(fd);
+      return -errno;
+    }
+
+  return fd;
+}
+
+/****************************************************************************
+ * Name: rpmsg_tun_accept
+ *
+ * Description:
+ *   Create rpmsg socket and accept the connection from client
+ *
+ * Parameters:
+ *   name - tun device name
+ *
+ * Returned Value:
+ *   int - rpmsg socket fd on success, -errno on failure.
+ ****************************************************************************/
+
+int rpmsg_tun_accept(const char *name)
+{
+  struct sockaddr_rpmsg addr;
+  int ret;
+  int fd;
+
+  /* Create rpmsg socket */
+
+  fd = socket(AF_RPMSG, SOCK_STREAM | SOCK_CLOEXEC, 0);
+  if (fd < 0)
+    {
+      return -errno;
+    }
+
+  /* Initialize address */
+
+  memset(&addr, 0, sizeof(addr));
+  addr.rp_family = AF_RPMSG;
+  strncpy(addr.rp_name, name, sizeof(addr.rp_name) - 1);
+
+  /* Bind to local address */
+
+  if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
+    {
+      goto out;
+    }
+
+  /* Listen for incoming connections */
+
+  if (listen(fd, 1) < 0)
+    {
+      goto out;
+    }
+
+  /* Accept the connection */
+
+  ret = accept4(fd, NULL, NULL, SOCK_CLOEXEC);
+  if (ret < 0)
+    {
+      goto out;
+    }
+
+  close(fd);
+  return ret;
+
+out:
+  close(fd);
+  return -errno;
+}
+
+/****************************************************************************
+ * Name: rpmsg_tun_to_socket
+ *
+ * Description:
+ *   Read buffer from tun device and send to rpmsg socket
+ *
+ * Parameters:
+ *   tunfd   - tun device fd
+ *   rpmsgfd - rpmsg socket fd
+ *
+ * Returned Value:
+ *   int - 0 on success, -errno on failure.
+ ****************************************************************************/
+
+int rpmsg_tun_to_socket(int tunfd, int rpmsgfd)
+{
+  char buf[RPMSG_TUN_BUFFER_SIZE];
+  int32_t ret;
+
+  /* Read from tun device */
+
+  ret = read(tunfd, buf + sizeof(ret), sizeof(buf) - sizeof(ret));
+  if (ret <= 0)
+    {
+      return ret < 0 ? -errno : -EPIPE;
+    }
+
+  /* Pretend the buffer length */
+
+  memcpy(buf, &ret, sizeof(ret));
+
+  /* Send to the remote side */
+
+  return rpmsg_tun_send_all(rpmsgfd, buf, ret + sizeof(ret));
+}
+
+/****************************************************************************
+ * Name: rpmsg_tun_from_socket
+ *
+ * Description:
+ *   Read buffer from rpmsg socket and send to tun device
+ *
+ * Parameters:
+ *   tunfd   - tun device fd
+ *   rpmsgfd - rpmsg socket fd
+ *
+ * Returned Value:
+ *   int - 0 on success, -errno on failure.
+ ****************************************************************************/
+
+int rpmsg_tun_from_socket(int tunfd, int rpmsgfd)
+{
+  char buf[RPMSG_TUN_BUFFER_SIZE];
+  int32_t len;
+  int ret;
+
+  ret = rpmsg_tun_recv_all(rpmsgfd, &len, sizeof(len));
+  if (ret < 0)
+    {
+      return ret;
+    }
+
+  if (len < 0 || len > sizeof(buf))
+    {
+      return -EINVAL;
+    }
+
+  ret = rpmsg_tun_recv_all(rpmsgfd, buf, len);
+  if (ret < 0)
+    {
+      return ret;
+    }
+
+  ret = write(tunfd, buf, len);
+  if (ret != len)
+    {
+      return ret < 0 ? -errno : -EPIPE;
+    }
+
+  return 0;
+}
+
+/****************************************************************************
+ * Name: rpmsg_tun_connect_netlink
+ *
+ * Description:
+ *   Create netlink socket and monitor the route message
+ *
+ * Parameters:
+ *   None
+ *
+ * Returned Value:
+ *   int - netlink fd on success, -errno on failure.
+ ****************************************************************************/
+
+int rpmsg_tun_connect_netlink(void)
+{
+  struct sockaddr_nl addr;
+  int fd;
+
+  /* Create netlink socket */
+
+  fd = socket(AF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_ROUTE);
+  if (fd < 0)
+    {
+      return -errno;
+    }
+
+  /* Initialize address */
+
+  memset(&addr, 0, sizeof(addr));
+  addr.nl_family = AF_NETLINK;
+  addr.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR;
+
+  /* Bind to local address */
+
+  if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
+    {
+      close(fd);
+      return -errno;
+    }
+
+  return fd;
+}
+
+/****************************************************************************
+ * Name: rpmsg_tun_process_netlink
+ *
+ * Description:
+ *   Process netlink message
+ *
+ * Parameters:
+ *   fd   - netlink socket fd
+ *   name - netdev to monitor
+ *
+ * Returned Value:
+ *   1 is running/unknown or have ip addr, 0 is down and -errno on failure.
+ ****************************************************************************/
+
+int rpmsg_tun_process_netlink(int fd, const char *name)
+{
+  char buf[RPMSG_TUN_BUFFER_SIZE];
+  struct nlmsghdr *hdr = (struct nlmsghdr *)buf;
+  ssize_t len;
+
+  len = read(fd, buf, sizeof(buf));
+  if (len <= 0)
+    {
+      return len < 0 ? -errno : -EPIPE;
+    }
+
+  for (; NLMSG_OK(hdr, len); hdr = NLMSG_NEXT(hdr, len))
+    {
+      struct ifinfomsg *info;
+      struct ifaddrmsg *ifaddr;
+      struct rtattr *attr;
+      size_t attrlen;
+      char devname[IFNAMSIZ];
+
+      if (hdr->nlmsg_type != RTM_NEWLINK &&
+          hdr->nlmsg_type != RTM_DELLINK &&
+          hdr->nlmsg_type != RTM_SETLINK &&
+          hdr->nlmsg_type != RTM_NEWADDR &&
+          hdr->nlmsg_type != RTM_DELADDR)
+        {
+          continue;
+        }
+
+      switch (hdr->nlmsg_type)
+        {
+          case RTM_NEWLINK:
+          case RTM_DELLINK:
+          case RTM_SETLINK:
+            info = (struct ifinfomsg *)NLMSG_DATA(hdr);
+            attr = IFLA_RTA(info);
+            attrlen = IFLA_PAYLOAD(hdr);
+
+            for (; RTA_OK(attr, attrlen); attr = RTA_NEXT(attr, attrlen))
+              {
+                if (attr->rta_type != IFLA_IFNAME)
+                  {
+                    continue;
+                  }
+
+                if (strcmp(name, RTA_DATA(attr)))
+                  {
+                    break;
+                  }
+
+                return (info->ifi_flags & IFF_RUNNING) != 0;
+              }
+
+            break;
+
+          case RTM_NEWADDR:
+          case RTM_DELADDR:
+            ifaddr = (struct ifaddrmsg *)NLMSG_DATA(hdr);
+            attr = IFA_RTA(ifaddr);
+            attrlen = IFA_PAYLOAD(hdr);
+
+            for (; RTA_OK(attr, attrlen); attr = RTA_NEXT(attr, attrlen))
+              {
+                if (attr->rta_type != IFA_LOCAL)
+                  {
+                    continue;
+                  }
+
+                if (if_indextoname(ifaddr->ifa_index, devname) == NULL)
+                  {
+                    continue;
+                  }
+
+                if (strcmp(name, devname))
+                  {
+                    break;
+                  }
+
+                return hdr->nlmsg_type == RTM_NEWADDR;
+              }
+
+            break;
+
+          default:
+            break;
+        }
+    }
+
+  return 1;
+}
+
+/****************************************************************************
+ * Name: rpmsg_tun_wait_running
+ *
+ * Description:
+ *   Wait network device running
+ *
+ * Parameters:
+ *   fd   - netlink socket fd
+ *   name - network device name
+ *
+ * Returned Value:
+ *   1 is running, -errno on failure.
+ ****************************************************************************/
+
+int rpmsg_tun_wait_running(int fd, const char *name)
+{
+  int ret;
+
+  for (; ; )
+    {
+      ret = rpmsg_tun_is_running(name);
+      if (ret == 1)
+        {
+          break;
+        }
+
+      ret = rpmsg_tun_process_netlink(fd, name);
+      if (ret < 0)
+        {
+          break;
+        }
+    }
+
+  return ret;
+}
+
+/****************************************************************************
+ * Name: rpmsg_tun_loop
+ *
+ * Description:
+ *   Poll tunfd and rpmsgfd when fds return POLLIN
+ *   then read buffer from tunfd and send to rpmsgfd
+ *   or read buffer from rpmsgfd and send to tunfd
+ *
+ * Parameters:
+ *   tunfd   - tun device fd
+ *   rpmsgfd - rpmsg socket fd
+ *
+ * Returned Value:
+ *   None
+ ****************************************************************************/
+
+void rpmsg_tun_loop(int tunfd, int rpmsgfd)
+{
+  struct pollfd fds[2];
+
+  memset(fds, 0, sizeof(fds));
+  fds[0].fd = tunfd;
+  fds[0].events = POLLIN;
+  fds[1].fd = rpmsgfd;
+  fds[1].events = POLLIN;
+
+  for (; ; )
+    {
+      if (poll(fds, 2, -1) < 0)
+        {
+          break;
+        }
+
+      if ((fds[0].revents | fds[1].revents) & POLLIN)
+        {
+          if (fds[0].revents & POLLIN)
+            {
+              if (rpmsg_tun_to_socket(tunfd, rpmsgfd) < 0)
+                {
+                  break;
+                }
+            }
+
+          if (fds[1].revents & POLLIN)
+            {
+              if (rpmsg_tun_from_socket(tunfd, rpmsgfd) < 0)
+                {
+                  break;
+                }
+            }
+        }
+      else if ((fds[0].revents | fds[1].revents) & (POLLHUP | POLLERR))
+        {
+          break;
+        }
+    }
+}
diff --git a/netutils/rpmsg_tun/rpmsg_tun_util.h 
b/netutils/rpmsg_tun/rpmsg_tun_util.h
new file mode 100644
index 000000000..729c176a3
--- /dev/null
+++ b/netutils/rpmsg_tun/rpmsg_tun_util.h
@@ -0,0 +1,206 @@
+/****************************************************************************
+ * apps/netutils/rpmsg_tun/rpmsg_tun_util.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 __APPS_NETUTILS_RPMSG_TUN_RPMSG_TUN_UTIL_H
+#define __APPS_NETUTILS_RPMSG_TUN_RPMSG_TUN_UTIL_H
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <stdbool.h>
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/****************************************************************************
+ * Public Function Prototypes
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: rpmsg_tun_setup
+ *
+ * Description:
+ *   Setup tun device
+ *
+ * Parameters:
+ *   name - tun device name
+ *   ip   - tun device ip
+ *   mask - tun device mask
+ *
+ * Returned Value:
+ *   int - tun fd on success, -errno on failure.
+ ****************************************************************************/
+
+int rpmsg_tun_setup(const char *name, const char *ip, const char *mask);
+
+/****************************************************************************
+ * Name: rpmsg_tun_set_running
+ *
+ * Description:
+ *   Set tun device running status
+ *
+ * Parameters:
+ *   fd      - tun device fd
+ *   running - true is running and false is down
+ *
+ * Returned Value:
+ *   0 on success, -errno on failure.
+ ****************************************************************************/
+
+int rpmsg_tun_set_running(int fd, bool running);
+
+/****************************************************************************
+ * Name: rpmsg_tun_connect
+ *
+ * Description:
+ *   Create rpmsg socket and connect to server
+ *
+ * Parameters:
+ *   cpu  - remote cpu name
+ *   name - tun device name
+ *
+ * Returned Value:
+ *   int - rpmsg socket fd on success, -errno on failure.
+ ****************************************************************************/
+
+int rpmsg_tun_connect(const char *cpu, const char *name);
+
+/****************************************************************************
+ * Name: rpmsg_tun_accept
+ *
+ * Description:
+ *   Create rpmsg socket and accept the connection from client
+ *
+ * Parameters:
+ *   name - tun device name
+ *
+ * Returned Value:
+ *   int - rpmsg socket fd on success, -errno on failure.
+ ****************************************************************************/
+
+int rpmsg_tun_accept(const char *name);
+
+/****************************************************************************
+ * Name: rpmsg_tun_to_socket
+ *
+ * Description:
+ *   Read buffer from tun device and send to rpmsg socket
+ *
+ * Parameters:
+ *   tunfd   - tun device fd
+ *   rpmsgfd - rpmsg socket fd
+ *
+ * Returned Value:
+ *   int - 0 on success, -errno on failure.
+ ****************************************************************************/
+
+int rpmsg_tun_to_socket(int tunfd, int rpmsgfd);
+
+/****************************************************************************
+ * Name: rpmsg_tun_from_socket
+ *
+ * Description:
+ *   Read buffer from rpmsg socket and send to tun device
+ *
+ * Parameters:
+ *   tunfd   - tun device fd
+ *   rpmsgfd - rpmsg socket fd
+ *
+ * Returned Value:
+ *   int - 0 on success, -errno on failure.
+ ****************************************************************************/
+
+int rpmsg_tun_from_socket(int tunfd, int rpmsgfd);
+
+/****************************************************************************
+ * Name: rpmsg_tun_connect_netlink
+ *
+ * Description:
+ *   Create netlink socket and monitor the route message
+ *
+ * Parameters:
+ *   None
+ *
+ * Returned Value:
+ *   int - netlink fd on success, -errno on failure.
+ ****************************************************************************/
+
+int rpmsg_tun_connect_netlink(void);
+
+/****************************************************************************
+ * Name: rpmsg_tun_process_netlink
+ *
+ * Description:
+ *   Process netlink message
+ *
+ * Parameters:
+ *   fd   - netlink socket fd
+ *   name - netdev to monitor
+ *
+ * Returned Value:
+ *   1 is running, 0 is down/unknown and -errno on failure.
+ ****************************************************************************/
+
+int rpmsg_tun_process_netlink(int fd, const char *name);
+
+/****************************************************************************
+ * Name: rpmsg_tun_wait_running
+ *
+ * Description:
+ *   Wait network device running
+ *
+ * Parameters:
+ *   fd   - netlink socket fd
+ *   name - network device name
+ *
+ * Returned Value:
+ *   1 is running, -errno on failure.
+ ****************************************************************************/
+
+int rpmsg_tun_wait_running(int fd, const char *name);
+
+/****************************************************************************
+ * Name: rpmsg_tun_loop
+ *
+ * Description:
+ *   Poll tunfd and rpmsgfd and when fds return POLLIN
+ *   then read buffer from tunfd and send to rpmsgfd
+ *   or read buffer from rpmsgfd and send to tunfd
+ *
+ * Parameters:
+ *   tunfd   - tun device fd
+ *   rpmsgfd - rpmsg socket fd
+ *
+ * Returned Value:
+ *   None
+ ****************************************************************************/
+
+void rpmsg_tun_loop(int tunfd, int rpmsgfd);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __APPS_NETUTILS_RPMSG_TUN_RPMSG_TUN_UTIL_H */

Reply via email to