Skip to contentSkip to conversation

net: lwip: add httpd command for browser based uploads

RFC PATCH In review Vitaliy Sochnev 2 participants 10 messages Sep 28 – Sep 29 Networking

lore
Share & tools
lore
#0 lore raw

cover net: lwip: add httpd command for browser based uploads

This series adds an httpd command which receives a file uploaded from a web browser into memory. It is meant for recovering a device, typically a router, without a serial console or a TFTP server on the host. Downstream forks, such as the MediaTek SDK "failsafe" web UI and its derivatives, implement this with their own TCP stack and HTTP server.

An httpd on top of the legacy stack was proposed in 2024 [1]. Its TCP fixes were merged, the server was not; one reviewer suggested the httpd bundled with lwIP if a server is needed at all [2]. This series builds lib/lwip httpd.c; the command parses no HTTP itself and implements the lwIP POST and custom file callbacks.

Patch 1 adds httpd_deinit() to the bundled lwIP, as was done with httpc_abort() for wget: with the shared lwIP runtime a listener left behind would accept connections while another client polls. The series is based on next.

The command only stores the upload and sets $fileaddr, $filesize and $httpd_target. What to do with a target is left to the environment:

  => setenv httpd_targets "initramfs bl2"
  => setenv httpd_do_initramfs 'bootm $fileaddr'
  => httpd && run httpd_do_$httpd_target

It follows the structure and test of tftpsrv. The size cost is about 11 KiB on qemu_arm64_lwip_defconfig.

Tested on qemu_arm64_lwip with curl and headless Chrome: uploads of 3 and 20 MiB with CRC check, unknown targets, multipart bodies, concurrent uploads, uploads overlapping reserved memory, interrupted uploads, repeated runs and Ctrl-C. After the command returns, port 80 refuses connections while tftpsrv polls. test_net_httpd passes with a 5 MiB file.

A revision before the move to the shared runtime was also tested on an Airoha AN7583 board (Nokia XG-040G-MF), on v2026.07 with the OpenWrt patches for that board and the lwIP chained pbuf transmit fix: 20 MiB were uploaded in 1.4 s with a matching CRC, and an OpenWrt initramfs uploaded from a browser was booted by httpd_do_initramfs. The command adds 11 KiB to u-boot.bin there.

On QEMU's e1000, lwIP wget runs at about 3 KB/s and a 5 MiB httpd upload does not finish within 60 s. The cause is in the e1000 driver; a fix is posted separately [3].

[1] https://lore.kernel.org/u-boot/[email protected]/
[2] https://lore.kernel.org/u-boot/CALeDE9Ps9hua1+AhZDkA+WtxG0phB_0E7j8RJJa8kY5eqn24NA@mail.gmail.com/
[3] https://lore.kernel.org/u-boot/[email protected]/

Vitaliy Sochnev (4):
net: lwip: add an httpd stop operation
net: lwip: add httpd command
doc: usage: cmd: add httpd
test: py: net: add httpd test

 cmd/Kconfig                                 |  11 +
 cmd/lwip/Makefile                           |   1 +
 cmd/lwip/httpd.c                            |  12 +
 configs/qemu_arm64_lwip_defconfig           |   1 +
 configs/sandbox64_lwip_defconfig            |   1 +
 doc/usage/cmd/httpd.rst                     |  92 +++++
 include/net-lwip.h                          |   1 +
 lib/lwip/Makefile                           |   9 +
 lib/lwip/lwip/src/apps/http/httpd.c         |  51 ++-
 lib/lwip/lwip/src/include/lwip/apps/httpd.h |   1 +
 lib/lwip/u-boot/fsdata_uboot.h              |   8 +
 lib/lwip/u-boot/lwipopts.h                  |  14 +
 net/lwip/Makefile                           |   1 +
 net/lwip/httpd.c                            | 373 ++++++++++++++++++++
 test/py/tests/test_net.py                   |  95 +++++
 15 files changed, 669 insertions(+), 2 deletions(-)
 create mode 100644 cmd/lwip/httpd.c
 create mode 100644 doc/usage/cmd/httpd.rst
 create mode 100644 lib/lwip/u-boot/fsdata_uboot.h
 create mode 100644 net/lwip/httpd.c

base-commit: 2b8902913c19eb581fb0d567201c09b8fa46ac74

Signature · 1 line
2.55.0
#1 lore raw

RFC PATCH 1/4 net: lwip: add an httpd stop operation

The lwIP httpd has no way to stop: its listening PCB and callbacks outlive the caller. With the shared lwIP runtime the server would keep accepting connections while any other client polls the network.

Add httpd_deinit(), which aborts the open connections and closes the listening PCB. Open connections are only tracked with LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED.

With SO_REUSE, set SOF_REUSEADDR on the listening PCB: connections closed by the server stay in TIME-WAIT and would make the next bind fail.

---
 lib/lwip/lwip/src/apps/http/httpd.c         | 51 ++++++++++++++++++++-
 lib/lwip/lwip/src/include/lwip/apps/httpd.h |  1 +
 2 files changed, 50 insertions(+), 2 deletions(-)
lib/lwip/lwip/src/apps/http/httpd.c +49 -2
index 9477e855e..745477272 100644
@@ -98,6 +98,7 @@
 
 #include "lwip/altcp.h"
 #include "lwip/altcp_tcp.h"
+#include "lwip/tcp.h"
 #if HTTPD_ENABLE_HTTPS
 #include "lwip/altcp_tls.h"
 #endif
@@ -345,6 +346,9 @@ static char *http_cgi_params[LWIP_HTTPD_MAX_CGI_PARAMETERS]; /* Params extracted
 static char *http_cgi_param_vals[LWIP_HTTPD_MAX_CGI_PARAMETERS]; /* Values for each extracted param */
 #endif /* LWIP_HTTPD_CGI */
 
+/** listening PCB set up by httpd_init(), closed by httpd_deinit() */
+static struct altcp_pcb *httpd_listen_pcb;
+
 #if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED
 /** global list of active HTTP connections, use to kill the oldest when
     running out of memory */
@@ -2658,7 +2662,7 @@ http_accept(void *arg, struct altcp_pcb *pcb, err_t err)
   return ERR_OK;
 }
 
-static void
+static struct altcp_pcb *
 httpd_init_pcb(struct altcp_pcb *pcb, u16_t port)
 {
   err_t err;
@@ -2673,6 +2677,7 @@ httpd_init_pcb(struct altcp_pcb *pcb, u16_t port)
     LWIP_ASSERT("httpd_init: tcp_listen failed", pcb != NULL);
     altcp_accept(pcb, http_accept);
   }
+  return pcb;
 }
 
 /**
@@ -2694,9 +2699,51 @@ httpd_init(void)
 
   /* LWIP_ASSERT_CORE_LOCKED(); is checked by tcp_new() */
 
+#if SO_REUSE
+  {
+    /* rebind while connections of a previous run are in TIME-WAIT */
+    struct tcp_pcb *tpcb = tcp_new_ip_type(IPADDR_TYPE_ANY);
+    if (tpcb != NULL) {
+      ip_set_option(tpcb, SOF_REUSEADDR);
+#if LWIP_ALTCP
+      pcb = altcp_tcp_wrap(tpcb);
+      if (pcb == NULL) {
+        tcp_close(tpcb);
+      }
+#else /* LWIP_ALTCP */
+      pcb = tpcb;
+#endif /* LWIP_ALTCP */
+    } else {
+      pcb = NULL;
+    }
+  }
+#else /* SO_REUSE */
   pcb = altcp_tcp_new_ip_type(IPADDR_TYPE_ANY);
+#endif /* SO_REUSE */
   LWIP_ASSERT("httpd_init: tcp_new failed", pcb != NULL);
-  httpd_init_pcb(pcb, HTTPD_SERVER_PORT);
+  httpd_listen_pcb = httpd_init_pcb(pcb, HTTPD_SERVER_PORT);
+}
+
+/**
+ * @ingroup httpd
+ * Stop the httpd: close the listening PCB set up by httpd_init() and abort
+ * all open connections, so that no httpd callback runs afterwards.
+ * Open connections are only known with LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED.
+ */
+void
+httpd_deinit(void)
+{
+#if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED
+  /* this also unlinks the http_state from the list */
+  while (http_connections != NULL) {
+    http_close_or_abort_conn(http_connections->pcb, http_connections, 1);
+  }
+#endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */
+  if (httpd_listen_pcb != NULL) {
+    altcp_accept(httpd_listen_pcb, NULL);
+    altcp_close(httpd_listen_pcb);
+    httpd_listen_pcb = NULL;
+  }
 }
 
 #if HTTPD_ENABLE_HTTPS
lib/lwip/lwip/src/include/lwip/apps/httpd.h +1 -0
index 1ecdd743c..e6ddd023d 100644
@@ -243,6 +243,7 @@ void httpd_post_data_recved(void *connection, u16_t recved_len);
 #endif /* LWIP_HTTPD_SUPPORT_POST */
 
 void httpd_init(void);
+void httpd_deinit(void);
 
 #if HTTPD_ENABLE_HTTPS
 struct altcp_tls_config;
Signature · 1 line
2.55.0
#2 lore raw

Re: [RFC PATCH 1/4] net: lwip: add an httpd stop operation

Quoted 12 lines · Vitaliy Sochnev

The lwIP httpd has no way to stop: its listening PCB and callbacks outlive the caller. With the shared lwIP runtime the server would keep accepting connections while any other client polls the network.

Add httpd_deinit(), which aborts the open connections and closes the listening PCB. Open connections are only tracked with LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED.

With SO_REUSE, set SOF_REUSEADDR on the listening PCB: connections closed by the server stay in TIME-WAIT and would make the next bind fail.

Quoted 5 lines
---
 lib/lwip/lwip/src/apps/http/httpd.c         | 51 ++++++++++++++++++++-
 lib/lwip/lwip/src/include/lwip/apps/httpd.h |  1 +
 2 files changed, 50 insertions(+), 2 deletions(-)

I'm a little wary of adding code to upstream lwIP here. Have you submitted this there as well?

Signature · 1 line
Tom
#3 lore raw

Re: [RFC PATCH 1/4] net: lwip: add an httpd stop operation

Quoted 2 lines · Tom Rini

I'm a little wary of adding code to upstream lwIP here. Have you submitted this there as well?

Not before sending this series. I have now submitted it to the lwIP patch tracker:

https://savannah.nongnu.org/patch/?10636

It applies to lwIP master as is and builds there with the example_app warning flags, with and without SO_REUSE and LWIP_ALTCP.

#4 lore raw

Re: [RFC PATCH 1/4] net: lwip: add an httpd stop operation

Quoted 11 lines · Vitaliy Sochnev
Quoted 2 lines · Tom Rini

I'm a little wary of adding code to upstream lwIP here. Have you submitted this there as well?

Not before sending this series. I have now submitted it to the lwIP patch tracker:

https://savannah.nongnu.org/patch/?10636

It applies to lwIP master as is and builds there with the example_app warning flags, with and without SO_REUSE and LWIP_ALTCP.

OK, please wait for v2'ing this work here until it's merged with lwIP upstream. I think the comments on the U-Boot side will be fairly minor, and it's about making sure this part is upstreamed and not something we worry about long term. Thanks!

Signature · 1 line
Tom
#5 lore raw

RFC PATCH 2/4 net: lwip: add httpd command

In reply to Vitaliy Sochnev

Add a command which receives the first file uploaded with an HTTP POST into memory, so that a device can be recovered with only a web browser on the host.

It uses the httpd application bundled with lwIP. Pages are served through the lwIP custom file hooks, so no generated fsdata is needed. The lwIP fs_open() and fs_close() clash with the U-Boot file system layer and are renamed for the two lwIP objects.

GET / returns an upload page with one file input per target in $httpd_targets. A file is sent as the raw body of POST /upload/<target>. Unknown targets, multipart bodies, concurrent uploads and files which do not fit into free memory are refused. After an upload $fileaddr, $filesize and $httpd_target are set and the command returns, so boot scripts decide what to do with each target:

  httpd && run httpd_do_$httpd_target

The size cost is about 11 KiB on qemu_arm64_lwip_defconfig.

---
 cmd/Kconfig                       |  11 +
 cmd/lwip/Makefile                 |   1 +
 cmd/lwip/httpd.c                  |  12 +
 configs/qemu_arm64_lwip_defconfig |   1 +
 configs/sandbox64_lwip_defconfig  |   1 +
 include/net-lwip.h                |   1 +
 lib/lwip/Makefile                 |   9 +
 lib/lwip/u-boot/fsdata_uboot.h    |   8 +
 lib/lwip/u-boot/lwipopts.h        |  14 ++
 net/lwip/Makefile                 |   1 +
 net/lwip/httpd.c                  | 373 ++++++++++++++++++++++++++++++
 11 files changed, 432 insertions(+)
 create mode 100644 cmd/lwip/httpd.c
 create mode 100644 lib/lwip/u-boot/fsdata_uboot.h
 create mode 100644 net/lwip/httpd.c
cmd/Kconfig +11 -0
index 7124b961d..8c10e8c3c 100644
@@ -2288,6 +2288,17 @@ config CMD_TFTPBOOT
 	help
 	  tftpboot - load file via network using TFTP protocol
 
+config CMD_HTTPD
+	bool "httpd"
+	depends on NET_LWIP
+	select PROT_TCP_LWIP
+	help
+	  Act as a minimal HTTP server and receive the first file uploaded
+	  with a POST request, e.g. from the built-in web page. This allows
+	  recovering a device with nothing more than a web browser. The
+	  command returns successfully after the upload, so boot scripts can
+	  act on the received image.
+
 config CMD_TFTPSRV
 	bool "tftpsrv"
 	depends on CMD_TFTPBOOT
cmd/lwip/Makefile +1 -0
index 245683a96..84e8cb736 100644
@@ -1,5 +1,6 @@
 obj-$(CONFIG_CMD_DHCP) += dhcp.o
 obj-$(CONFIG_CMD_DNS) += dns.o
+obj-$(CONFIG_CMD_HTTPD) += httpd.o
 obj-$(CONFIG_CMD_NFS) += nfs.o
 obj-$(CONFIG_CMD_PING) += ping.o
 obj-$(CONFIG_CMD_SNTP) += sntp.o
cmd/lwip/httpd.c new file +12 -0
new file mode 100644
index 000000000..b86fc4d2d
@@ -0,0 +1,12 @@
+// SPDX-License-Identifier: GPL-2.0+
+
+#include <command.h>
+#include <net.h>
+
+U_BOOT_CMD(httpd, 2, 0, do_httpd,
+	   "act as an HTTP server and receive the first uploaded file",
+	   "[loadAddress]\n"
+	   "Serve an upload page and receive a file sent with\n"
+	   "'POST /upload/<target>' into memory. Valid targets are listed in\n"
+	   "$httpd_targets (default: file). On success $fileaddr, $filesize\n"
+	   "and $httpd_target are set. Press Ctrl-C to abort.");
configs/qemu_arm64_lwip_defconfig +1 -0
index 06ed5a131..0d937c5b4 100644
@@ -8,6 +8,7 @@ CONFIG_CMD_DNS=y
 CONFIG_CMD_NFS=y
 CONFIG_CMD_SNTP=y
 CONFIG_CMD_TFTPSRV=y
+CONFIG_CMD_HTTPD=y
 CONFIG_CMD_WGET=y
 CONFIG_EFI_HTTP_BOOT=y
 CONFIG_WGET_HTTPS=y
configs/sandbox64_lwip_defconfig +1 -0
index 0e9272853..3447d379f 100644
@@ -3,3 +3,4 @@
 CONFIG_SANDBOX=y
 
 CONFIG_NET_LWIP=y
+CONFIG_CMD_HTTPD=y
include/net-lwip.h +1 -0
index 7819f9823..709961251 100644
@@ -90,6 +90,7 @@ int net_lwip_dns_resolve(char *name_or_ip, ip_addr_t *ip);
  */
 bool wget_validate_uri(char *uri);
 
+int do_httpd(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[]);
 int do_dns(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[]);
 int do_nfs(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[]);
 int do_tftpsrv(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[]);
lib/lwip/Makefile +9 -0
index c3f0e916f..e9dea9eff 100644
@@ -55,5 +55,14 @@ obj-y += \
 	lwip/src/core/udp.o \
 	lwip/src/netif/ethernet.o
 
+obj-$(CONFIG_CMD_HTTPD) += lwip/src/apps/http/fs.o \
+	lwip/src/apps/http/httpd.o
+
+# Avoid clashes with the U-Boot file system layer
+httpd_fs_rename := -Dfs_open=lwip_fs_open -Dfs_close=lwip_fs_close \
+	-Dfs_bytes_left=lwip_fs_bytes_left
+CFLAGS_lwip/src/apps/http/fs.o += $(httpd_fs_rename)
+CFLAGS_lwip/src/apps/http/httpd.o += $(httpd_fs_rename)
+
 obj-$(CONFIG_$(PHASE_)MBEDTLS_LIB_TLS) += lwip/src/apps/altcp_tls/altcp_tls_mbedtls.o \
 	lwip/src/apps/altcp_tls/altcp_tls_mbedtls_mem.o
lib/lwip/u-boot/fsdata_uboot.h new file +8 -0
new file mode 100644
index 000000000..7fbf64273
@@ -0,0 +1,8 @@
+/* SPDX-License-Identifier: GPL-2.0+ */
+/*
+ * Empty read-only file system for the lwIP httpd. All pages are provided
+ * at run time by fs_open_custom().
+ */
+
+#define FS_ROOT		NULL
+#define FS_NUMFILES	0
lib/lwip/u-boot/lwipopts.h +14 -0
index 1c1adc57c..56ea259e0 100644
@@ -175,7 +175,12 @@
 #define LWIP_DISABLE_MEMP_SANITY_CHECKS 1
 
 #define LWIP_SOCKET                     0
+#if defined(CONFIG_CMD_HTTPD)
+/* httpd rebinds while connections of a previous run are in TIME-WAIT */
+#define SO_REUSE                        1
+#else
 #define SO_REUSE                        0
+#endif
 
 #define LWIP_STATS                      0
 
@@ -200,4 +205,13 @@
 #define LWIP_DHCP_GET_NTP_SRV 1
 #endif
 
+#if defined(CONFIG_CMD_HTTPD)
+#define LWIP_HTTPD_SUPPORT_POST         1
+#define LWIP_HTTPD_CUSTOM_FILES         1
+#define LWIP_HTTPD_DYNAMIC_HEADERS      1
+#define HTTPD_FSDATA_FILE               "fsdata_uboot.h"
+/* Track connections so that httpd_deinit() can abort them */
+#define LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED 1
+#endif
+
 #endif /* LWIP_UBOOT_LWIPOPTS_H */
net/lwip/Makefile +1 -0
index 5291cbb2a..cd13376a6 100644
@@ -3,6 +3,7 @@ ccflags-y += -I$(srctree)/lib/lwip/lwip/src/include -I$(srctree)/lib/lwip/u-boot
 obj-$(CONFIG_$(PHASE_)DM_ETH) += net-lwip.o
 obj-$(CONFIG_CMD_DHCP) += dhcp.o
 obj-$(CONFIG_DNS) += dns.o
+obj-$(CONFIG_CMD_HTTPD) += httpd.o
 obj-$(CONFIG_LWIP_ICMP_SHOW_UNREACH) += icmp_unreach.o
 obj-$(CONFIG_CMD_NFS) += nfs.o
 obj-$(CONFIG_CMD_TFTPBOOT) += tftp.o
net/lwip/httpd.c new file +373 -0

373 lines not on this page · raw message

Signature · 1 line
2.55.0
#6 lore raw

RFC PATCH 3/4 doc: usage: cmd: add httpd

In reply to Vitaliy Sochnev

Document the httpd command, the environment variables it uses and sets, and its security implications.

---
 doc/usage/cmd/httpd.rst | 92 +++++++++++++++++++++++++++++++++++++++++
 1 file changed, 92 insertions(+)
 create mode 100644 doc/usage/cmd/httpd.rst
doc/usage/cmd/httpd.rst new file +92 -0
new file mode 100644
index 000000000..4b765c8fc
@@ -0,0 +1,92 @@
+.. SPDX-License-Identifier: GPL-2.0+
+
+.. index::
+   single: httpd (command)
+
+httpd command
+=============
+
+Synopsis
+--------
+
+::
+
+    httpd [loadAddress]
+
+Description
+-----------
+
+The httpd command acts as a minimal HTTP server and receives the first file
+uploaded to it into memory. It lets a host load an image with only a web
+browser, e.g. to recover a device.
+
+loadAddress
+    memory address where the received file is stored. If not provided, the
+    address is taken from the *loadaddr* environment variable or the default
+    image load address.
+
+Requesting ``/`` returns an upload page with one file selector per upload
+target. The targets are listed, separated by spaces, in the *httpd_targets*
+environment variable. If the variable is not set, a single target named
+*file* is offered. Target names may only contain lower case letters, digits,
+``_`` and ``-``; other names are ignored.
+
+A file is uploaded by sending it as the raw body of a request
+``POST /upload/<target>``. Multipart form data is refused, as it would be
+stored verbatim. Uploads which do not fit into free memory are refused before
+any data is written. The lwIP httpd reads at most nine digits of the
+Content-Length header, so files of 1 GB or more cannot be uploaded.
+
+After a successful upload, the *fileaddr* and *filesize* environment variables
+describe the received file and *httpd_target* holds the target name. The
+command then returns successfully. It does not boot or write the file itself;
+boot scripts decide what to do with each target. An interrupted upload is
+discarded and the command keeps listening.
+
+The command runs until a file has been received or Ctrl-C is pressed.
+
+Security
+--------
+
+The server has no authentication and no encryption. Anybody who can reach the
+board while the command is running can upload a file, and a boot script may
+act on it. Only run the command on a trusted network, typically on explicit
+user request such as a button pressed at power-on.
+
+Example
+-------
+
+In the example the board offers two targets. A FIT image uploaded as
+*initramfs* is booted, a file uploaded as *bl2* would be written to flash by
+a board specific script.
+
+::
+
+    => setenv ipaddr 192.168.1.1
+    => setenv netmask 255.255.255.0
+    => setenv httpd_targets "initramfs bl2"
+    => setenv httpd_do_initramfs 'bootm $fileaddr'
+    => httpd && run httpd_do_$httpd_target
+    Using ethernet@1fb50000 device
+    Listening for HTTP uploads on http://192.168.1.1/
+    Load address: 0x81800000
+
+    Receiving 'initramfs' (9437184 bytes)
+    Loading: ##################################################
+    Bytes transferred = 9437184 (900000 hex)
+    ## Loading kernel (any) from FIT Image at 81800000 ...
+
+Open http://192.168.1.1/ in a browser on a host with an address in the same
+subnet, or send the file from the command line:
+
+::
+
+    $ curl --data-binary @image.itb \
+           -H 'Content-Type: application/octet-stream' \
+           http://192.168.1.1/upload/initramfs
+
+Configuration
+-------------
+
+The command is only available if CONFIG_CMD_HTTPD=y. It requires the lwIP
+network stack (CONFIG_NET_LWIP=y) and uses the lwIP httpd application.
Signature · 1 line
2.55.0
#7 lore raw

Re: [RFC PATCH 3/4] doc: usage: cmd: add httpd

Quoted 8 lines · Vitaliy Sochnev

Document the httpd command, the environment variables it uses and sets, and its security implications.

---
 doc/usage/cmd/httpd.rst | 92 +++++++++++++++++++++++++++++++++++++++++
 1 file changed, 92 insertions(+)
 create mode 100644 doc/usage/cmd/httpd.rst

I would prefer this folded with the patch that adds the command.

Signature · 1 line
Tom
#8 lore raw

Re: [RFC PATCH 3/4] doc: usage: cmd: add httpd

Quoted 1 line · Tom Rini

I would prefer this folded with the patch that adds the command.

OK, I will fold it into 2/4 in v2.

#9 lore raw

RFC PATCH 4/4 test: py: net: add httpd test

In reply to Vitaliy Sochnev

Upload a generated file with curl after checking that an unknown target is refused, then check its size and CRC32 in U-Boot. The test is skipped unless the board environment provides env__net_httpd_file.

---
 test/py/tests/test_net.py | 95 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 95 insertions(+)
test/py/tests/test_net.py +95 -0
index a2007c2fd..8c4c67f2d 100644
@@ -72,6 +72,17 @@ For example:
         'timeout': 50000,
     }
 
+    # Details regarding a file that may be written to U-Boot using the httpd
+    # command. This variable may be omitted or set to None if httpd testing is
+    # not possible or desired. The test uses host-side curl to upload a
+    # generated file to U-Boot. The optional httpd_url entry may be used when
+    # the host must use a forwarded address instead of U-Boot's ipaddr value.
+    env__net_httpd_file = {
+        'addr': 0x10000000,
+        'size': 4096,
+        'timeout': 50000,
+    }
+
     # Details regarding a file that may be read from a NFS server. This variable
     # may be omitted or set to None if NFS testing is not possible or desired.
     env__net_nfs_readable_file = {
@@ -554,3 +565,87 @@ def test_net_tftpsrv(ubman):
 
     output = ubman.run_command("crc32 $fileaddr $filesize")
     assert crc in output
+
[email protected]("cmd_crc32")
[email protected]("cmd_httpd")
[email protected]("curl")
+def test_net_httpd(ubman):
+    """Test the httpd command.
+
+    A file is generated on the host and uploaded to U-Boot using HTTP after
+    an upload to an unknown target has been refused. The file is then
+    validated in U-Boot using its size and CRC32.
+
+    The details of the file to upload are provided by the boardenv_* file;
+    see the comment at the beginning of this file.
+    """
+
+    if not net_set_up:
+        pytest.skip("Network not initialized")
+
+    f = ubman.config.env.get("env__net_httpd_file", None)
+    if not f:
+        pytest.skip("No httpd file to write")
+
+    addr = f.get("addr", None)
+    if not addr:
+        addr = utils.find_ram_base(ubman)
+
+    timeout = f.get("timeout", ubman.p.timeout)
+    timeout_secs = max(1, (timeout + 999) // 1000)
+    size = f.get("size", 4096)
+    url = f.get("httpd_url", None)
+    data = bytes([i % 251 for i in range(size)])
+    crc = "%08x" % (zlib.crc32(data) & 0xffffffff)
+
+    ip = ubman.run_command("echo $ipaddr").strip()
+    if not ip:
+        pytest.skip("No U-Boot IP address")
+    if not url:
+        url = "http://%s" % ip
+
+    def upload(target):
+        return utils.run_and_log(
+            ubman,
+            [
+                "curl",
+                "--silent",
+                "--max-time",
+                str(timeout_secs),
+                "--output",
+                "/dev/null",
+                "--write-out",
+                "%{http_code}",
+                "--header",
+                "Content-Type: application/octet-stream",
+                "--data-binary",
+                "@" + tmp.name,
+                "%s/upload/%s" % (url, target),
+            ],
+        ).strip()
+
+    ubman.run_command("setenv httpd_targets test")
+    with tempfile.NamedTemporaryFile() as tmp:
+        tmp.write(data)
+        tmp.flush()
+
+        done = False
+        with ubman.temporary_timeout(timeout):
+            try:
+                ubman.run_command("httpd %x" % addr, wait_for_prompt=False)
+                ubman.wait_for("Listening for HTTP uploads")
+                assert upload("unknown") == "400"
+                assert upload("test") == "200"
+                ubman.wait_for("Bytes transferred = %d" % size)
+                ubman.wait_for(ubman.prompt)
+                done = True
+            finally:
+                if not done:
+                    ubman.ctrlc()
+                    ubman.drain_console()
+
+    output = ubman.run_command("echo $httpd_target $filesize")
+    assert "test %x" % size in output
+
+    output = ubman.run_command("crc32 $fileaddr $filesize")
+    assert crc in output
Signature · 1 line
2.55.0