Unverified Commit cb434811 authored by Johny Mattsson's avatar Johny Mattsson Committed by GitHub
Browse files

IDF web server module (#3502)

* Added httpd module.

Lua-interface to the standard esp_http_server component.

* Added eromfs module.
parent e5892a72
...@@ -7,10 +7,12 @@ set(module_srcs ...@@ -7,10 +7,12 @@ set(module_srcs
"crypto.c" "crypto.c"
"dht.c" "dht.c"
"encoder.c" "encoder.c"
"eromfs.c"
"file.c" "file.c"
"gpio.c" "gpio.c"
"heaptrace.c" "heaptrace.c"
"http.c" "http.c"
"httpd.c"
"i2c.c" "i2c.c"
"i2c_hw_master.c" "i2c_hw_master.c"
"i2c_hw_slave.c" "i2c_hw_slave.c"
...@@ -74,6 +76,7 @@ idf_component_register( ...@@ -74,6 +76,7 @@ idf_component_register(
"driver_can" "driver_can"
"esp_http_client" "esp_http_client"
"fatfs" "fatfs"
"esp_http_server"
"libsodium" "libsodium"
"lua" "lua"
"mbedtls" "mbedtls"
...@@ -138,3 +141,17 @@ set_property( ...@@ -138,3 +141,17 @@ set_property(
DIRECTORY "${COMPONENT_DIR}" APPEND DIRECTORY "${COMPONENT_DIR}" APPEND
PROPERTY ADDITIONAL_MAKE_CLEAN_FILES ucg_config.h u8g2_fonts.h u8g2_displays.h PROPERTY ADDITIONAL_MAKE_CLEAN_FILES ucg_config.h u8g2_fonts.h u8g2_displays.h
) )
# eromfs generation
add_custom_command(
OUTPUT eromfs.bin
COMMAND ${COMPONENT_DIR}/eromfs.py ${CONFIG_NODEMCU_CMODULE_EROMFS_VOLUMES}
DEPENDS ${SDKCONFIG_HEADER}
)
add_custom_target(eromfs_bin DEPENDS eromfs.bin)
target_add_binary_data(${COMPONENT_LIB} "${CMAKE_CURRENT_BINARY_DIR}/eromfs.bin" BINARY DEPENDS eromfs_bin)
set_property(
DIRECTORY "${COMPONENT_DIR}" APPEND
PROPERTY ADDITIONAL_MAKE_CLEAN_FILES eromfs.bin
)
...@@ -54,6 +54,34 @@ menu "NodeMCU modules" ...@@ -54,6 +54,34 @@ menu "NodeMCU modules"
Includes the encoder module. This provides hex and base64 encoding Includes the encoder module. This provides hex and base64 encoding
and decoding functionality. and decoding functionality.
config NODEMCU_CMODULE_EROMFS
bool "Eromfs module (embedded read-only mountable file sets)"
select VFS_SUPPORT_IO
default "n"
help
Includes the eromfs module, giving access to the embedded mountable
file sets (volumes) configured here. Useful for bundling file sets
within the main firmware image, such as website contents.
config NODEMCU_CMODULE_EROMFS_VOLUMES
depends on NODEMCU_CMODULE_EROMFS
string "File sets to embed"
default "volume_name=/path/to/volume_root;myvol2=../relpath"
help
List one or more volume definitions in the form of
VolumeName=/path/to/files where the VolumeName is the identifier
by which the eromfs module will refer to the volume. The path
may be given as either a relative or absolute path. If relative,
it is relative to the top-level nodemcu-firmware directory.
All files and directories within the specified volume root will
be included. Symlinks are not supported and will result in
failure if encountered. Multiple volumes may be declared by
separating the entries with a semicolon.
Note that eromfs does not support directories per se, but will
store the directory path as part of the filename just as SPIFFS
does.
config NODEMCU_CMODULE_ETH config NODEMCU_CMODULE_ETH
depends on IDF_TARGET_ESP32 depends on IDF_TARGET_ESP32
select ETH_USE_ESP32_EMAC select ETH_USE_ESP32_EMAC
...@@ -91,6 +119,32 @@ menu "NodeMCU modules" ...@@ -91,6 +119,32 @@ menu "NodeMCU modules"
help help
Includes the HTTP module (recommended). Includes the HTTP module (recommended).
config NODEMCU_CMODULE_HTTPD
bool "Httpd (web server) module"
default "n"
help
Includes the HTTPD module. This module uses the regular IDF
http server component internally.
config NODEMCU_CMODULE_HTTPD_MAX_RESPONSE_HEADERS
int "Max response header fields" if NODEMCU_CMODULE_HTTPD
default 5
help
Determines how much space to allocate for header fields in the
HTTP response. This value does not include header fields the
http server itself generates internally, but only headers
explicitly returned in a dynamic route handler. Typically only
Content-Type is needed, so for most applications the default
value here will suffice.
config NODEMCU_CMODULE_HTTPD_RECV_BODY_CHUNK_SIZE
int "Receive body chunk size" if NODEMCU_CMODULE_HTTPD
default 1024
help
When receiving a body payload, receive at most this many
bytes at a time. Higher values means reduced overhead at
the cost of higher memory load.
config NODEMCU_CMODULE_I2C config NODEMCU_CMODULE_I2C
bool "I2C module" bool "I2C module"
default "y" default "y"
......
#include "module.h"
#include "lauxlib.h"
#include "esp_vfs.h"
#include <errno.h>
#include <dirent.h>
#include <stdint.h>
#include <string.h>
/**
* The logical layout of the embedded volumes is
* [ volume record ]
* [ volume record ]
* ...
* [ index record in vol1 ]
* [ index record in vol1 ]
* ...
* [ file contents in vol1 ]
* [ file contents in vol1 ]
* ...
* [ index record in vol2 ]
* [ index record in vol2 ]
* ...
* [ file contents in vol2 ]
* [ file contents in vol2 ]
*
* Both the volume records and index records are variable length so as to not
* waste space in their name fields. Finding the start of the index records
* for a volume is by reading the offs(et) field in the volume record and
* jumping that many bytes forward from the start of the eromfs.bin data.
* Similarly, finding the file contents is by reading the index record's
* offs(et) field and basing that off the start of the volume index.
* Naturally, the start of the volume index is the same as the end of the
* volume header, and the start of the file contents is the same as the
* end of the volume index, and either of those can be worked out by
* reading the offs(et) field in the first record.
*/
#pragma pack(push, 1)
typedef struct {
uint8_t rec_len;
uint16_t offs; // index_offs
char name[];
} volume_record_t;
typedef struct {
uint8_t rec_len;
uint32_t offs; // based off index_offs
uint32_t len; // file_len
char name[];
} index_record_t;
#pragma pack(pop)
typedef struct {
const index_record_t *meta;
const char *data; // start of data
off_t pos;
} file_descriptor_t;
typedef struct {
DIR opaque;
const index_record_t *index;
const index_record_t *pos;
} eromfs_DIR_t;
extern const char eromfs_bin_start[] asm("_binary_eromfs_bin_start");
// Both the volume header and the file set indices end where the next
// type of data block commences (file set index, file contents).
#define end_of(type, start) ((const type *)(((char *)start) + start->offs))
#define eromfs_header_start ((const volume_record_t *)eromfs_bin_start)
#define eromfs_header_end end_of(volume_record_t, eromfs_header_start)
/* The logic for finding a volume record by name is the same as finding a
* file record by name, only the data structure type varies. Hence we
* hide the casting and variable length record stepping behind a convenience
* macro here.
*/
#define find_entry_by_name(out, xname, start_void_p, record_t) \
do { \
const record_t *entry_ = (const record_t *)(start_void_p); \
const record_t *end_ = end_of(record_t, entry_); \
unsigned xname_len = strlen(xname); \
for (; entry_ < end_; \
entry_ = (const record_t *)(((char *)entry_) + entry_->rec_len)) \
{ \
uint8_t name_len = entry_->rec_len - sizeof(record_t); \
if (xname_len == name_len && \
strncmp(xname, entry_->name, name_len) == 0) \
{ \
out = entry_; \
break; \
} \
} \
} while(0);
static int mounted_volumes = LUA_NOREF;
static SemaphoreHandle_t fd_mutex;
static file_descriptor_t fds[CONFIG_NODEMCU_MAX_OPEN_FILES];
// --- VFS interface -----------------------------------------------------
#define get_index() const index_record_t *index = (const index_record_t *)ctx
static const index_record_t *path2entry(void *ctx, const char *path)
{
while (*path == '/')
++path;
get_index();
const index_record_t *entry = NULL;
find_entry_by_name(entry, path, index, index_record_t);
return entry;
}
static int eromfs_fstat(void *ctx, int fd, struct stat *st)
{
memset(st, 0, sizeof(struct stat));
st->st_size = fds[fd].meta->len;
st->st_blocks = (fds[fd].meta->len + 511)/512;
return 0;
}
#ifdef CONFIG_VFS_SUPPORT_DIR
static int eromfs_stat(void *ctx, const char *path, struct stat *st)
{
const index_record_t *entry = path2entry(ctx, path);
if (!entry)
return -ENOENT;
memset(st, 0, sizeof(struct stat));
st->st_size = entry->len;
st->st_blocks = (entry->len + 511)/512;
return 0;
}
static DIR *eromfs_opendir(void *ctx, const char *path)
{
if (strcmp(path, "/") != 0)
return NULL;
get_index();
eromfs_DIR_t *dir = calloc(1, sizeof(eromfs_DIR_t));
dir->index = index;
dir->pos = index;
return (DIR *)dir;
}
static struct dirent *eromfs_readdir(void *ctx, DIR *pdir)
{
UNUSED(ctx);
eromfs_DIR_t *dir = (eromfs_DIR_t *)pdir;
const index_record_t *end = end_of(index_record_t, dir->index);
if (dir->pos >= end)
return NULL;
static struct dirent de = {
.d_ino = 0,
.d_type = DT_REG,
};
size_t max_len = sizeof(de.d_name);
size_t len = dir->pos->rec_len - sizeof(index_record_t);
if (len > max_len -1)
len = max_len - 1;
strncpy(de.d_name, dir->pos->name, len);
de.d_name[len] = 0;
dir->pos = (const index_record_t *)((char *)dir->pos + dir->pos->rec_len);
return &de;
}
static int eromfs_closedir(void *ctx, DIR *dir)
{
UNUSED(ctx);
free(dir);
return 0;
}
#endif
static int eromfs_open(void *ctx, const char *path, int flags, int mode)
{
UNUSED(flags);
UNUSED(mode);
const index_record_t *entry = path2entry(ctx, path);
if (!entry)
return -ENOENT;
xSemaphoreTake(fd_mutex, portMAX_DELAY);
int fd = -ENFILE;
// max open files is guaranteed to be small; linear search is fine
for (unsigned i = 0; i < CONFIG_NODEMCU_MAX_OPEN_FILES; ++i)
{
if (fds[i].meta == NULL)
{
fds[i].meta = entry;
fds[i].data = (const char *)ctx + entry->offs;
fds[i].pos = 0;
fd = (int)i;
}
}
xSemaphoreGive(fd_mutex);
return fd;
}
static ssize_t eromfs_read(void *ctx, int fd, void *dst, size_t size)
{
UNUSED(ctx);
size_t avail = fds[fd].meta->len - fds[fd].pos;
if (size > avail)
size = avail;
const char *src = fds[fd].data + fds[fd].pos;
memcpy(dst, src, size);
fds[fd].pos += size;
return size;
}
static off_t eromfs_lseek(void *ctx, int fd, off_t size, int mode)
{
UNUSED(ctx);
off_t pos = fds[fd].pos;
switch(mode)
{
case SEEK_SET: pos = size; break;
case SEEK_CUR: pos += size; break;
case SEEK_END: pos = fds[fd].meta->len + size; break;
default:
return -EINVAL;
}
if (pos < 0 || pos > fds[fd].meta->len)
return -EINVAL;
fds[fd].pos = pos;
return pos;
}
static int eromfs_close(void *ctx, int fd)
{
UNUSED(ctx);
xSemaphoreTake(fd_mutex, portMAX_DELAY);
fds[fd].meta = NULL;
fds[fd].data = NULL;
fds[fd].pos = 0;
xSemaphoreGive(fd_mutex);
return 0;
}
// --- Lua interface -----------------------------------------------------
static int leromfs_list(lua_State *L)
{
lua_newtable(L);
int t = lua_gettop(L);
// If this logic looks similar to the find_entry_by_name() macro, it's
// because it is :) Except we're capturing all the volume names, so no
// easy reuse.
const volume_record_t *vol = eromfs_header_start;
const volume_record_t *end = eromfs_header_end;
for (; vol < end; vol = (const volume_record_t *)((char *)vol + vol->rec_len))
{
uint8_t volume_name_len = vol->rec_len - sizeof(volume_record_t);
lua_pushlstring(L, vol->name, volume_name_len);
lua_rawseti(L, t, lua_objlen(L, t) + 1);
}
return 1;
}
static int leromfs_mount(lua_State *L)
{
const char *name = luaL_checkstring(L, 1);
const char *mountpt = luaL_checkstring(L, 2);
lua_settop(L, 2);
const volume_record_t *vol = NULL;
find_entry_by_name(vol, name, eromfs_bin_start, volume_record_t);
if (!vol)
return luaL_error(L, "volume %s not found", name);
const index_record_t *index_start =
(const index_record_t *)(eromfs_bin_start + vol->offs);
esp_vfs_t eromfs = {
.flags = ESP_VFS_FLAG_CONTEXT_PTR,
.open_p = eromfs_open,
.fstat_p = eromfs_fstat,
.read_p = eromfs_read,
.lseek_p = eromfs_lseek,
.close_p = eromfs_close,
#ifdef CONFIG_VFS_SUPPORT_DIR
.stat_p = eromfs_stat,
.opendir_p = eromfs_opendir,
.readdir_p = eromfs_readdir,
.closedir_p = eromfs_closedir,
#endif
};
esp_err_t err = esp_vfs_register(mountpt, &eromfs, (void *)index_start);
if (err != ESP_OK)
return luaL_error(L, "failed to mount eromfs; code %d", err);
lua_rawgeti(L, LUA_REGISTRYINDEX, mounted_volumes);
lua_pushvalue(L, 2);
lua_pushvalue(L, 1);
lua_rawset(L, -3); // mounted_volumes[mountpt] = name
return 0;
}
static int leromfs_unmount(lua_State *L)
{
const char *name = luaL_checkstring(L, 1);
const char *mountpt = luaL_checkstring(L, 2);
lua_settop(L, 2);
lua_rawgeti(L, LUA_REGISTRYINDEX, mounted_volumes);
lua_pushvalue(L, 2);
lua_rawget(L, -2);
if (lua_isstring(L, -1))
{
const char *mounted_name = lua_tostring(L, -1);
if (strcmp(name, mounted_name) == 0)
{
esp_err_t err = esp_vfs_unregister(mountpt);
if (err != ESP_OK)
return luaL_error(L, "unmounting failed; code %d", err);
lua_pop(L, 1);
lua_pushvalue(L, 2);
lua_pushnil(L);
lua_rawset(L, -3); // mounted_volumes[mountpt] = nil
return 0;
}
else
return luaL_error(L,
"can't umount %s from %s; volume %s is mounted there",
name, mountpt, mounted_name);
}
else
return 0; // already unmounted, not an error
}
static int leromfs_init(lua_State *L)
{
fd_mutex = xSemaphoreCreateMutex();
lua_newtable(L);
mounted_volumes = luaL_ref(L, LUA_REGISTRYINDEX);
return 0;
}
LROT_BEGIN(eromfs, NULL, 0)
LROT_FUNCENTRY( list, leromfs_list )
LROT_FUNCENTRY( mount, leromfs_mount )
LROT_FUNCENTRY( unmount, leromfs_unmount )
LROT_END(eromfs, NULL, 0)
NODEMCU_MODULE(EROMFS, "eromfs", eromfs, leromfs_init);
#!/usr/bin/env python3
import sys
import os
import struct
# [volume records]
# reclen, index_offs, name
# reclen, index_offs2, name2
# [file index]
# reclen, offs, file_len, name # offs base index_offs
# reclen, offs, file_len, name2 # offs base index_offs2
# [file contents]
# rawdata
# rawdata
vol_names = [] # one entry per volume
volume_indexes = [] # one entry per volume
volume_file_contents = [] # one entry per volume
for voldef in sys.argv[1:]:
[ name, basedir ] = voldef.split('=')
print(f'==> Packing volume "{name}" from {basedir}')
vol_names.append(name)
# Make relative paths relative to the top nodemcu-firmware dir; this
# script gets executed with build/esp-idf/modules as the current dir
if not os.path.isabs(basedir):
basedir = os.path.join(*['..', '..', '..', basedir])
if not os.path.isdir(basedir):
raise FileNotFoundError(f'source directory {basedir} not found')
basedir_len = len(basedir) +1
file_index = b''
file_data = b''
offs = 0
entries = []
index_size = 0
for root, subdirs, files in os.walk(basedir):
prefix = ('' if root == basedir else root[basedir_len:] + '/')
for filename in files:
hostrelpath = os.path.join(root, filename)
relpath = prefix + filename
size = os.path.getsize(hostrelpath)
rec_len = 1 + 4 + 4 + len(relpath) # reclen + offs + filelen + name
if rec_len > 255:
raise ValueError(f'excessive path length for {relpath}')
entries.append([ rec_len, offs, size, relpath ])
offs += size
index_size += rec_len
with open(hostrelpath, mode='rb') as f:
file_data += f.read()
for entry in entries:
[ rec_len, offs, size, relpath ] = entry
print('[', rec_len, index_size + offs, size, relpath, ']')
file_index += \
struct.pack('<BII', rec_len, index_size + offs, size) + \
relpath.encode('utf-8')
volume_indexes.append(file_index)
volume_file_contents.append(file_data)
volume_records_len = len(vol_names) * (1 + 2) + len(''.join(vol_names))
print(f'==> Generating volumes index ({volume_records_len} bytes)')
with open('eromfs.bin', 'wb') as f:
index_offs = volume_records_len
for idx, name in enumerate(vol_names):
rec_len = 1 + 2 + len(name)
index_len = len(volume_indexes[idx])
data_len = len(volume_file_contents[idx])
if rec_len > 255:
raise ValueError(f'volume name too long for {name}')
if index_offs > 65535:
raise ValueError('volumes index overflowed; too many volumes')
f.write(
struct.pack('<BH', rec_len, index_offs) + name.encode('utf-8') \
)
print(f'- {name} (index {index_len} bytes; content {data_len} bytes)')
index_offs += index_len + data_len
for idx, index in enumerate(volume_indexes):
f.write(index)
f.write(volume_file_contents[idx])
This diff is collapsed.
# EROMFS Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2021-11-13 | [Johny Mattsson](https://github.com/jmattsson) |[Johny Mattsson](https://github.com/jmattsson) | [heaptrace.c](../../components/modules/eromfs.c)|
EROMFS (Embedded Read-Only Mountable File Sets) provides a convenient mechanism
for bundling file sets into the firmware image itself. The main use cases
envisaged for this is static web site content and default "skeleton" files
that may be used to populate SPIFFS on first boot.
When enabling the `eromfs` module one or more file sets ("volumes") must be
declared. Each such volume is identified by name, and may be mounted anywhere
supported by the [Virtual File System](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/storage/vfs.html). Once mounted, the included
files are available on a read-only basis to any thread wanting to access them.
Note that EROMFS does not support directories per se, but will store the
directory path as part of the filename just as SPIFFS does. As such it is
only possible to list the root of the volume, not subdirectories (since
they don't exist).
## eromfs.list
Returns a list of the bundled file sets (volumes).
#### Syntax
```lua
eromfs.list()
```
#### Parameters
None.
#### Returns
An array with the names of the bundled volumes.
#### Example
```lua
for _, volname in ipairs(eromfs.list()) do print(volname) end
```
## eromfs.mount
Mounts a volume at a specified point in the virtual file system.
Note that it is technically possible to mount a volume multiple times on
different mount points. The benefit of doing so however is questionable.
#### Syntax
```lua
eromfs.mount(volname, mountpt)
```
#### Parameters
- `volname` the name of the volume to mount, e.g. `myvol`.
- `mountpt` where to mount said volume. Must start with '/', e.g. `/myvol`.
#### Returns
`nil` on success. Raises an error if the named volume cannot be found, or
cannot be mounted.
#### Example
```lua
-- Assumes the volume named "myvol" exists
eromfs.mount('myvol', '/somewhere')
for name,size in pairs(file.list('/somewhere')) do print(name, size) end
```
## eromfs.unmount
Unmounts the specified EROMFS volume from the given mount point.
#### Syntax
```lua
eromfs.unmount(volname, mountpt)
```
#### Parameters
- `volname` the name of the volume to mount.
- `mountpt` the current mount point of the volume.
#### Returns
`nil` if:
- the volume was successfully unmounted; or
- the volume was not currently mounted at the given mount point
Raises an error if:
- the unmounting fails for some reason; or
- a different EROMFS volume is mounted on the given mount point
#### Example
```lua
eromfs.unmount('myvol', '/somewhere')
```
# LEDC Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2021-11-07 | [Johny Mattsson](https://github.com/jmattsson) | [Johny Mattsson](https://github.com/jmattsson) | [httpd.c](../../components/modules/httpd.c)|
This module provides an interface to Espressif's [web server component](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/protocols/esp_http_server.html).
# HTTPD Overview
The httpd module implements support for both static file serving and dynamic
content generation. For static files, all files need to reside under a
common prefix (the "webroot") in the (virtual) filesystem. The module does
not care whether the underlying file system supports directories or not,
so files may be served from SPIFFS, FAT filesystems, or whatever else
may be mounted. If you wish to include the static website contents within
the firmware image itself, considering using the [EROMFS](eromfs.md) module.
Unlike the default behaviour of the Espressif web server, this module serves
static files based on file extensions primarily. Static routes are typically
defined as a file extension (e.g. \*.html) and the `Content-Type` such files
should be served as. A number of file extensions are included by default
and should cover the basic needs:
- \*.html (text/html)
- \*.css (text/css)
- \*.js (text/javascript)
- \*.json (application/json)
- \*.gif (image/gif)
- \*.jpg (image/jpeg)
- \*.jpeg (image/jpeg)
- \*.png (image/png)
- \*.svg (image/svg+xml)
- \*.ttf (font/ttf)
The native Espressif approach may also be used if you prefer, but is harder
to work with. Both schemes can coexist in most cases without issues. When
using the native approach, URI wildcard matching is supported.
Dynamic routes may be registered, which when accessed by a client will result
in a Lua function being invoked. This function may then generate whatever
content is applicable, for example obtaining a sensor value and returning it.
Note that if you are writing sensor data to files and serving those files
statically you will be susceptible to race conditions where the file contents
may not be available from the outside. This is due to the web server running
in its own FreeRTOS thread and serving files directly from that thread
concurrently with the Lua VM running as usual. It is therefore safer to
instead serve such content on a dynamic route, even if all that route does
is reads the file and serves that.
An example of such a setup:
```lua
function handler(req)
local f = io.open('/path/to/mysensordata.csv', 'r')
return {
status = "200 OK",
type = "text/plain",
getbody = function()
local data = f:read(512) -- pick a suiteable chunk size here
if not data then f:close() end
return data
end,
}
end
httpd.dynamic(httpd.GET, "/mysensordata", handler)
```
## httpd.start()
Starts the web server. The server has to be started before routes can be
configured.
#### Syntax
```lua
httpd.start({
webroot = "<static file prefix>",
max_handlers = 20,
auto_index = httpd.INDEX_NONE || httpd.INDEX_ROOT || httpd.INDEX_ALL,
})
```
#### Parameters
A single configuration table is provided, with the following possible fields:
- `webroot` (mandatory) This sets the prefix used when serving static files.
For example, with `webroot` set to "web", a HTTP request for "/index.html"
will result in the httpd module trying to serve the file "web/index.html"
from the file system. Do NOT set this to the empty string, as that would
provide remote access to your entire virtual file system, including special
files such as virtual device files (e.g. "/dev/uart1") which would likely
present a serious security issue.
- `max_handlers` (optional) Configures the maximum number of route handlers
the server will support. Default value is 20, which includes both the
standard static file extension handlers and any user-provided handlers.
Raising this will result in a bit of additional memory being used. Adjust
if and when necessary.
- `auto_index` Sets the indexer mode to be used. Most web servers
automatically go looking for an "index.html" file when a directory is
requested. For example, when pointing your web browser to a web site
for the first time, e.g. http://www.example.com/ the actual request will
come through for "/", which in turn commonly gets translated to "/index.html"
on the server. This behaviour can be enabled in this module as well. There
are three modes provided:
- `httpd.INDEX_NONE` No automatic translation to "index.html" is provided.
- `httpd.INDEX_ROOT` Only the root ("/") is translated to "/index.html".
- `httpd.INDEX_ALL` Any path ending with a "/" has "index.html" appended.
For example, a request for "subdir/" would become "subdir/index.html",
which in turn might result in the file "web/subdir/index.html" being
served (if the `webroot` was set to "web").
The default value is `httpd.INDEX_ROOT`.
#### Returns
`nil`
#### Example
```lua
httpd.start({ webroot = "web", auto_index = httpd.INDEX_ALL })
```
## httpd.stop()
Stops the web server. All registered route handlers are removed.
#### Syntax
```lua
httpd.stop()
```
#### Parameters
None.
#### Returns
`nil`
## httpd.static()
Registers a static route handler.
#### Syntax
```
httpd.static(route, content_type)
```
#### Parameters
- `route` The route prefix. Typically in the form of \*.ext to serve all files
with the ".ext" extension statically. Refer to the Espressif [documentation](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/protocols/esp_http_server.html)
if you wish to use the native Espressif style of static routes instead.
- `content_type` The value to send in the `Content-Type` header for this file
type.
#### Returns
An error code on failure, or `nil` on success. The error code is the value
returned from the `httpd_register_uri_handler()` function.
#### Example
```lua
httpd.start({ webroot = "web" })
httpd.static("*.csv", "text/csv") -- Serve CSV files under web/
```
## httpd.dynamic()
Registers a dynamic route handler.
#### Syntax
```lua
httpd.dynamic(method, route, handler)
```
#### Parameters
- `method` The HTTP method this route applies to. One of:
- `httpd.GET`
- `httpd.HEAD`
- `httpd.PUT`
- `httpd.POST`
- `httpd.DELETE`
- `route` The route prefix. Be mindful of any trailing "/" as that may interact
with the `auto_index` functionality.
- `handler` The route handler function - `handler(req)`. The provided request
object `req` has the following fields/functions:
- `method` The request method. Same as the `method` parameter above. If the
same function is registered for several methods, this field can be used to
determine the method the request used.
- `uri` The requested URI. Includes both path and query string (if
applicable).
- `query` The query string on its own. Not decoded.
- `headers` A table-like object in which request headers may be looked up.
Note that due to the Espressif API not providing a way to iterate over all
headers this table will appear empty if fed to `pairs()`.
- `getbody()` A function which may be called to read in the request body
incrementally. The size of each chunk is set via the Kconfig option
"Receive body chunk size". When this function returns `nil` the end of
the body has been reached. May raise an error if reading the body fails
for some reason (e.g. timeout, network error).
Note that the provided `req` object is _only valid_ within the scope of this
single invocation of the handler. Attempts to store away the request and use
it later _will_ fail.
#### Returns
A table with the response data to send to the requesting client:
```lua
{
status = "200 OK",
type = "text/plain",
headers = {
['X-Extra'] = "My custom header value"
},
body = "Hello, Lua!",
getbody = dynamic_content_generator_func,
}
```
Supported fields:
- `status` The status code and string to send. If not included "200 OK" is used.
Other common strings would be "404 Not Found", "400 Bad Request" and everybody's
favourite "500 Internal Server Error".
- `type` The value for the `Content-Type` header. The Espressif web server
component handles this header specially, which is why it's provided here and
not within the `headers` table.
- `body` The full content body to send.
- `getbody` A function to source the body content from, similar to the way
the request body is read in. This function will be called repeatedly and the
returned string from each invocation will be sent as a chunk to the client.
Once this function returns `nil` the body is deemed to be complete and no
further calls to the function will be made. It is guaranteed that the
function will be called until it returns `nil` even if the sending of the
content encounters an error. This ensures that any resource cleanup
necessary will still take place in such circumstances (e.g. file closing).
Only one of `body` and `getbody` should be specified.
#### Example
```lua
httpd.start({ webroot = "web" })
function put_foo(req)
local body_len = tonumber(req.headers['content-length']) or 0
if body_len < 4096
then
local f = io.open("/upload/foo.txt", "w")
local body = req.getbody()
while body
do
f:write(body)
body = req.getbody()
end
f:close()
return { status = "201 Created" }
else
return { status = "400 Bad Request" }
end
end
httpd.dynamic(httpd.PUT, "/foo", put_foo)
```
## httpd.unregister()
Unregisters a previously registered handler. The default handlers may be
unregistered.
#### Syntax
```lua
httpd.unregister(method, route)
```
#### Parameters
- `method` The method the route was registered for. One of:
- `httpd.GET`
- `httpd.HEAD`
- `httpd.PUT`
- `httpd.POST`
- `httpd.DELETE`
- `route` The route prefix.
#### Returns
`1` on success, `nil` on failure (including if the route was not registered).
#### Example
Unregistering one of the default static handlers:
```lua
httpd.start({ webroot = "web" })
httpd.unregister(httpd.GET, "*.jpeg")
```
...@@ -53,6 +53,7 @@ pages: ...@@ -53,6 +53,7 @@ pages:
- 'gpio': 'modules/gpio.md' - 'gpio': 'modules/gpio.md'
- 'heaptrace': 'modules/heaptrace.md' - 'heaptrace': 'modules/heaptrace.md'
- 'http': 'modules/http.md' - 'http': 'modules/http.md'
- 'httpd': 'modules/httpd.md'
- 'i2c': 'modules/i2c.md' - 'i2c': 'modules/i2c.md'
- 'i2s': 'modules/i2s.md' - 'i2s': 'modules/i2s.md'
- 'ledc': 'modules/ledc.md' - 'ledc': 'modules/ledc.md'
......
...@@ -27,7 +27,7 @@ CONFIG_LWIP_SO_REUSE=y ...@@ -27,7 +27,7 @@ CONFIG_LWIP_SO_REUSE=y
# Decrease the duration of sockets in TIME_WAIT # Decrease the duration of sockets in TIME_WAIT
# see https://github.com/nodemcu/nodemcu-firmware/issues/1836 # see https://github.com/nodemcu/nodemcu-firmware/issues/1836
CONFIG_TCP_MSL=5000 CONFIG_LWIP_TCP_MSL=5000
# Disable esp-idf's bluetooth component by default. # Disable esp-idf's bluetooth component by default.
# The bthci module is also disabled and will enable bt when selected # The bthci module is also disabled and will enable bt when selected
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment