Skip to content

Commit

Permalink
wifi optis, refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
indexds committed Jan 11, 2025
1 parent f46096f commit 4142ee9
Show file tree
Hide file tree
Showing 9 changed files with 73 additions and 69 deletions.
70 changes: 43 additions & 27 deletions sdkconfig
Original file line number Diff line number Diff line change
Expand Up @@ -843,7 +843,7 @@ CONFIG_ESP_NETIF_TCPIP_LWIP=y
CONFIG_ESP_NETIF_USES_TCPIP_WITH_BSD_API=y
CONFIG_ESP_NETIF_RECEIVE_REPORT_ERRORS=y
# CONFIG_ESP_NETIF_L2_TAP is not set
CONFIG_ESP_NETIF_BRIDGE_EN=y
# CONFIG_ESP_NETIF_BRIDGE_EN is not set
# end of ESP NETIF Adapter

#
Expand Down Expand Up @@ -1010,9 +1010,9 @@ CONFIG_ESP_WIFI_RX_BA_WIN=6
CONFIG_ESP_WIFI_TASK_PINNED_TO_CORE_1=y
CONFIG_ESP_WIFI_SOFTAP_BEACON_MAX_LEN=752
CONFIG_ESP_WIFI_MGMT_SBUF_NUM=16
# CONFIG_ESP_WIFI_IRAM_OPT is not set
# CONFIG_ESP_WIFI_EXTRA_IRAM_OPT is not set
# CONFIG_ESP_WIFI_RX_IRAM_OPT is not set
CONFIG_ESP_WIFI_IRAM_OPT=y
CONFIG_ESP_WIFI_EXTRA_IRAM_OPT=y
CONFIG_ESP_WIFI_RX_IRAM_OPT=y
# CONFIG_ESP_WIFI_ENABLE_WPA3_SAE is not set
# CONFIG_ESP_WIFI_ENABLE_WPA3_OWE_STA is not set
# CONFIG_ESP_WIFI_SLP_IRAM_OPT is not set
Expand Down Expand Up @@ -1057,7 +1057,7 @@ CONFIG_ESP_COREDUMP_ENABLE_TO_NONE=y
#
# FAT Filesystem support
#
CONFIG_FATFS_VOLUME_COUNT=2
CONFIG_FATFS_VOLUME_COUNT=1
CONFIG_FATFS_LFN_NONE=y
# CONFIG_FATFS_LFN_HEAP is not set
# CONFIG_FATFS_LFN_STACK is not set
Expand Down Expand Up @@ -1088,12 +1088,12 @@ CONFIG_FATFS_CODEPAGE_437=y
CONFIG_FATFS_CODEPAGE=437
CONFIG_FATFS_FS_LOCK=0
CONFIG_FATFS_TIMEOUT_MS=10000
CONFIG_FATFS_PER_FILE_CACHE=y
# CONFIG_FATFS_PER_FILE_CACHE is not set
# CONFIG_FATFS_USE_FASTSEEK is not set
CONFIG_FATFS_VFS_FSTAT_BLKSIZE=0
# CONFIG_FATFS_IMMEDIATE_FSYNC is not set
# CONFIG_FATFS_USE_LABEL is not set
CONFIG_FATFS_LINK_LOCK=y
# CONFIG_FATFS_LINK_LOCK is not set
# end of FAT Filesystem support

#
Expand Down Expand Up @@ -1231,8 +1231,7 @@ CONFIG_LWIP_IP4_FRAG=y
CONFIG_LWIP_IP4_REASSEMBLY=y
CONFIG_LWIP_IP_REASS_MAX_PBUFS=10
CONFIG_LWIP_IP_FORWARD=y
CONFIG_LWIP_IPV4_NAPT=y
CONFIG_LWIP_IPV4_NAPT_PORTMAP=y
# CONFIG_LWIP_IPV4_NAPT is not set
# CONFIG_LWIP_STATS is not set
# CONFIG_LWIP_ESP_GRATUITOUS_ARP is not set
CONFIG_LWIP_TCPIP_RECVMBOX_SIZE=32
Expand Down Expand Up @@ -1340,7 +1339,7 @@ CONFIG_LWIP_DNS_MAX_SERVERS=4
# CONFIG_LWIP_FALLBACK_DNS_SERVER_SUPPORT is not set
# end of DNS

CONFIG_LWIP_BRIDGEIF_MAX_PORTS=7
CONFIG_LWIP_BRIDGEIF_MAX_PORTS=5
CONFIG_LWIP_ESP_LWIP_ASSERT=y

#
Expand All @@ -1354,7 +1353,26 @@ CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_NONE=y
# CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_CUSTOM is not set
# end of Hooks

# CONFIG_LWIP_DEBUG is not set
CONFIG_LWIP_DEBUG=y
CONFIG_LWIP_DEBUG_ESP_LOG=y
# CONFIG_LWIP_NETIF_DEBUG is not set
# CONFIG_LWIP_PBUF_DEBUG is not set
# CONFIG_LWIP_ETHARP_DEBUG is not set
# CONFIG_LWIP_API_LIB_DEBUG is not set
# CONFIG_LWIP_SOCKETS_DEBUG is not set
CONFIG_LWIP_IP_DEBUG=y
# CONFIG_LWIP_ICMP_DEBUG is not set
# CONFIG_LWIP_DHCP_STATE_DEBUG is not set
# CONFIG_LWIP_DHCP_DEBUG is not set
# CONFIG_LWIP_IP6_DEBUG is not set
# CONFIG_LWIP_ICMP6_DEBUG is not set
# CONFIG_LWIP_TCP_DEBUG is not set
# CONFIG_LWIP_UDP_DEBUG is not set
# CONFIG_LWIP_SNTP_DEBUG is not set
# CONFIG_LWIP_DNS_DEBUG is not set
# CONFIG_LWIP_BRIDGEIF_DEBUG is not set
# CONFIG_LWIP_BRIDGEIF_FDB_DEBUG is not set
# CONFIG_LWIP_BRIDGEIF_FW_DEBUG is not set
# end of LWIP

#
Expand All @@ -1373,7 +1391,6 @@ CONFIG_MBEDTLS_SSL_MAX_CONTENT_LEN=512
#
# CONFIG_MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH is not set
# CONFIG_MBEDTLS_X509_TRUSTED_CERT_CALLBACK is not set
# CONFIG_MBEDTLS_SSL_CONTEXT_SERIALIZATION is not set
# CONFIG_MBEDTLS_SSL_KEEP_PEER_CERTIFICATE is not set
# end of mbedTLS v3.x related

Expand Down Expand Up @@ -1439,13 +1456,12 @@ CONFIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED=y
# CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED is not set
# CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED is not set
# CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED is not set
CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED=y
CONFIG_MBEDTLS_ECP_NIST_OPTIM=y
# CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED is not set
# CONFIG_MBEDTLS_ECP_NIST_OPTIM is not set
# CONFIG_MBEDTLS_ECP_FIXED_POINT_OPTIM is not set
CONFIG_MBEDTLS_POLY1305_C=y
CONFIG_MBEDTLS_CHACHA20_C=y
CONFIG_MBEDTLS_CHACHAPOLY_C=y
CONFIG_MBEDTLS_HKDF_C=y
# CONFIG_MBEDTLS_POLY1305_C is not set
# CONFIG_MBEDTLS_CHACHA20_C is not set
# CONFIG_MBEDTLS_HKDF_C is not set
# CONFIG_MBEDTLS_THREADING_C is not set
# CONFIG_MBEDTLS_ERROR_STRINGS is not set
# end of mbedTLS
Expand Down Expand Up @@ -1526,8 +1542,8 @@ CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_0=y
# PThreads
#
CONFIG_PTHREAD_TASK_PRIO_DEFAULT=5
CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT=3072
CONFIG_PTHREAD_STACK_MIN=768
CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT=4096
CONFIG_PTHREAD_STACK_MIN=1024
CONFIG_PTHREAD_DEFAULT_CORE_NO_AFFINITY=y
# CONFIG_PTHREAD_DEFAULT_CORE_0 is not set
# CONFIG_PTHREAD_DEFAULT_CORE_1 is not set
Expand Down Expand Up @@ -1622,7 +1638,7 @@ CONFIG_SPIFFS_OBJ_NAME_LEN=32
# CONFIG_SPIFFS_FOLLOW_SYMLINKS is not set
# CONFIG_SPIFFS_USE_MAGIC is not set
CONFIG_SPIFFS_META_LENGTH=4
CONFIG_SPIFFS_USE_MTIME=y
# CONFIG_SPIFFS_USE_MTIME is not set

#
# Debug Configuration
Expand Down Expand Up @@ -1686,8 +1702,8 @@ CONFIG_WL_SECTOR_SIZE=4096
#
# Wi-Fi Provisioning Manager
#
CONFIG_WIFI_PROV_SCAN_MAX_ENTRIES=12
CONFIG_WIFI_PROV_AUTOSTOP_TIMEOUT=30
CONFIG_WIFI_PROV_SCAN_MAX_ENTRIES=10
CONFIG_WIFI_PROV_AUTOSTOP_TIMEOUT=20
# CONFIG_WIFI_PROV_BLE_FORCE_ENCRYPTION is not set
CONFIG_WIFI_PROV_STA_ALL_CHANNEL_SCAN=y
# CONFIG_WIFI_PROV_STA_FAST_SCAN is not set
Expand Down Expand Up @@ -1822,8 +1838,8 @@ CONFIG_ESP32_WIFI_RX_BA_WIN=6
CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_1=y
CONFIG_ESP32_WIFI_SOFTAP_BEACON_MAX_LEN=752
CONFIG_ESP32_WIFI_MGMT_SBUF_NUM=16
# CONFIG_ESP32_WIFI_IRAM_OPT is not set
# CONFIG_ESP32_WIFI_RX_IRAM_OPT is not set
CONFIG_ESP32_WIFI_IRAM_OPT=y
CONFIG_ESP32_WIFI_RX_IRAM_OPT=y
# CONFIG_ESP32_WIFI_ENABLE_WPA3_SAE is not set
# CONFIG_ESP32_WIFI_ENABLE_WPA3_OWE_STA is not set
CONFIG_WPA_MBEDTLS_CRYPTO=y
Expand Down Expand Up @@ -1872,8 +1888,8 @@ CONFIG_ESP32_TIME_SYSCALL_USE_RTC_FRC1=y
# CONFIG_ESP32_TIME_SYSCALL_USE_FRC1 is not set
# CONFIG_ESP32_TIME_SYSCALL_USE_NONE is not set
CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT=5
CONFIG_ESP32_PTHREAD_TASK_STACK_SIZE_DEFAULT=3072
CONFIG_ESP32_PTHREAD_STACK_MIN=768
CONFIG_ESP32_PTHREAD_TASK_STACK_SIZE_DEFAULT=4096
CONFIG_ESP32_PTHREAD_STACK_MIN=1024
CONFIG_ESP32_DEFAULT_PTHREAD_CORE_NO_AFFINITY=y
# CONFIG_ESP32_DEFAULT_PTHREAD_CORE_0 is not set
# CONFIG_ESP32_DEFAULT_PTHREAD_CORE_1 is not set
Expand Down
10 changes: 5 additions & 5 deletions src/http/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,18 @@ mod wg_routes;
/// Handles wifi related routes.
mod wifi_routes;

/// This IP will be the only one allowed to access the http server once it is
/// up. By default, this is set to the DHCP address allocated to the computer
/// connecting to the esp32.
const ALLOWED_IP: Ipv4Addr = Ipv4Addr::new(10, 10, 10, 2);
use super::net::ETH_GATEWAY;

/// Checks that the source ip of the request is [`ALLOWED_IP`]. This function
/// should be called at the beginning of every call to `fn_handler` to prevent
/// security vulnerabilities.
fn check_ip(request: &mut Request<&mut EspHttpConnection>) -> anyhow::Result<()> {
let source_ip = request.connection().raw_connection()?.source_ipv4()?;

if source_ip != ALLOWED_IP {
// This IP will be the only one allowed to access the http server once it is
// up. By default, this is set to the DHCP address allocated to the computer
// connecting to the esp32.
if source_ip != Ipv4Addr::from(u32::from(ETH_GATEWAY) + 1) {
log::warn!("Forbidden ip [{}] tried to connect! Returned 403.", source_ip);
return Err(Error::msg("Forbidden"));
}
Expand Down
8 changes: 4 additions & 4 deletions src/http/wifi_routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use esp_idf_svc::http::server::{EspHttpServer, Method};
use esp_idf_svc::nvs::{EspNvs, NvsDefault};
use esp_idf_svc::wifi::{AuthMethod, EspWifi};

use crate::network::wifi;
use crate::net;
use crate::utils::nvs::WifiConfig;

/// Sets the WiFi related routes for the http server.
Expand All @@ -22,7 +22,7 @@ pub fn set_routes(
move |mut request| {
super::check_ip(&mut request)?;

wifi::disconnect(Arc::clone(&wifi))?;
net::wifi_disconnect(Arc::clone(&wifi))?;

let connection = request.connection();

Expand Down Expand Up @@ -58,8 +58,8 @@ pub fn set_routes(
let wifi = Arc::clone(&wifi);

thread::spawn(move || {
_ = wifi::set_configuration(Arc::clone(&nvs_thread), Arc::clone(&wifi));
_ = wifi::connect(Arc::clone(&wifi));
_ = net::wifi_set_config(Arc::clone(&nvs_thread), Arc::clone(&wifi));
_ = net::wifi_connect(Arc::clone(&wifi));
});

let connection = request.connection();
Expand Down
7 changes: 3 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,11 @@ use esp_idf_svc::eventloop::EspSystemEventLoop;
use esp_idf_svc::hal::prelude::Peripherals;
use esp_idf_svc::log::EspLogger;
use esp_idf_svc::nvs::{EspDefaultNvsPartition, EspNvs};
use network::{eth, wifi};

/// Handles the http server and its capabilities.
mod http;
/// Handles wifi and ethernet capabilities.
mod network;
mod net;
/// Handles over-the-air updates.
mod ota;
/// Handles non-volatile storage.
Expand All @@ -29,8 +28,8 @@ fn main() -> anyhow::Result<()> {

let nvs_config = Arc::new(Mutex::new(EspNvs::new(nvs.clone(), "config", true)?));

let eth_netif = eth::start(peripherals.pins, peripherals.mac, sysloop.clone())?;
let wifi_netif = wifi::init(peripherals.modem, sysloop.clone(), nvs.clone())?;
let eth_netif = net::eth_start(peripherals.pins, peripherals.mac, sysloop.clone())?;
let wifi_netif = net::wifi_init(peripherals.modem, sysloop.clone(), nvs.clone())?;

let http_server = http::start(Arc::clone(&nvs_config), Arc::clone(&wifi_netif))?;

Expand Down
10 changes: 5 additions & 5 deletions src/network/eth.rs → src/net/eth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@ use esp_idf_svc::hal::mac::MAC;
use esp_idf_svc::ipv4::{Configuration, Ipv4Addr, Mask, RouterConfiguration, Subnet};
use esp_idf_svc::netif::{EspNetif, NetifConfiguration, NetifStack};

/// Ethernet gateway to access the web configuration page. Care should be taken not to set this ip in a way that would clash with other subnet configurations on the local network. Whatever this ip is, the DHCP allocated ip the device will receive will be ip+1
pub const ETH_GATEWAY: Ipv4Addr = Ipv4Addr::new(192, 168, 100, 1);

/// Initializes the Ethernet driver and network interface, then starts it.
pub fn start(
pub fn eth_start(
pins: Pins,
mac: MAC,
sysloop: EspSystemEventLoop,
Expand Down Expand Up @@ -45,7 +48,7 @@ pub fn start(
route_priority: 10,
ip_configuration: Some(Configuration::Router(RouterConfiguration {
subnet: Subnet {
gateway: Ipv4Addr::new(10, 10, 10, 1),
gateway: ETH_GATEWAY,
mask: Mask(30),
},
dhcp_enabled: true, // adds dhcp_server flag
Expand All @@ -59,9 +62,6 @@ pub fn start(
})?,
)?;

log::info!("Enabling napt..");
eth_netif.netif_mut().enable_napt(true)?;

log::info!("Starting ethernet netif..");
eth_netif.start()?;

Expand Down
7 changes: 5 additions & 2 deletions src/network/mod.rs → src/net/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
/// Handles ethernet related capabilities.
pub mod eth;
mod eth;
/// Handles wifi related capbabilities.
pub mod wifi;
mod wifi;

pub use eth::*;
pub use wifi::*;
8 changes: 4 additions & 4 deletions src/network/wifi.rs → src/net/wifi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use crate::utils::nvs::WifiConfig;
/// Initializes the WiFi driver and network interface, but does not start it
/// yet. This will be done when the user calls a scan using the web interface
/// provided by the http server.
pub fn init(
pub fn wifi_init(
modem: Modem,
sysloop: EspSystemEventLoop,
nvs: EspDefaultNvsPartition,
Expand Down Expand Up @@ -44,7 +44,7 @@ pub fn init(
}

/// Stores the given configuration in nvs and sets it.
pub fn set_configuration(
pub fn wifi_set_config(
nvs: Arc<Mutex<EspNvs<NvsDefault>>>,
wifi: Arc<Mutex<EspWifi<'static>>>,
) -> anyhow::Result<()> {
Expand All @@ -71,7 +71,7 @@ pub fn set_configuration(
/// Connects the WiFi network interface to the configured access point.
/// Care should be taken to always call [`set_configuration`] before this
/// function.
pub fn connect(wifi: Arc<Mutex<EspWifi<'static>>>) -> anyhow::Result<()> {
pub fn wifi_connect(wifi: Arc<Mutex<EspWifi<'static>>>) -> anyhow::Result<()> {
log::info!("Connecting to access point..");

let mut wifi = wifi.lock().unwrap();
Expand All @@ -93,7 +93,7 @@ pub fn connect(wifi: Arc<Mutex<EspWifi<'static>>>) -> anyhow::Result<()> {

/// Disconnects the WiFi network interface from the access point it is connected
/// to.
pub fn disconnect(wifi: Arc<Mutex<EspWifi<'static>>>) -> anyhow::Result<()> {
pub fn wifi_disconnect(wifi: Arc<Mutex<EspWifi<'static>>>) -> anyhow::Result<()> {
log::info!("Disconnecting from access point..");

let mut wifi = wifi.lock().unwrap();
Expand Down
4 changes: 2 additions & 2 deletions src/wireguard/esp_wireguard/esp_wireguard/src/esp_wireguard.c
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ static esp_err_t esp_wireguard_peer_init(const wireguard_config_t *config, struc
}

/* resolve peer name or IP address */
ESP_LOGI(TAG, "resolving ip address (dns)..");
ESP_LOGI(TAG, "resolving ip address..");
{
ip_addr_t endpoint_ip;
memset(&endpoint_ip, 0, sizeof(endpoint_ip));
Expand Down Expand Up @@ -188,7 +188,7 @@ static esp_err_t esp_wireguard_netif_create(const wireguard_config_t *config)
ip_2_ip4(&netmask),
ip_2_ip4(&gateway),
&wg, &wireguardif_init,
&ip4_input);
&ip_input);
if (wg_netif == NULL) {
ESP_LOGE(TAG, "netif_add: failed");
err = ESP_FAIL;
Expand Down
18 changes: 2 additions & 16 deletions src/wireguard/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use std::ffi::CString;
use std::net::Ipv4Addr;
use std::sync::{Arc, Mutex};
use std::time::Duration;

Expand Down Expand Up @@ -71,8 +70,8 @@ fn create_ctx_conf(
fw_mark: 0,
public_key: CString::new(nvs_conf.server_public_key.as_str())?.into_raw(),
preshared_key: ptr::null_mut(),
allowed_ip: CString::new("0.0.0.0")?.into_raw(),
allowed_ip_mask: CString::new("0.0.0.0")?.into_raw(),
allowed_ip: CString::new("192.168.200.1")?.into_raw(),
allowed_ip_mask: CString::new("255.255.255.0")?.into_raw(),
endpoint: CString::new(nvs_conf.address.as_str())?.into_raw(),
port: nvs_conf.port.as_str().parse()?,
persistent_keepalive: 20,
Expand Down Expand Up @@ -206,16 +205,3 @@ pub fn end_tunnel() -> anyhow::Result<()> {
Ok(())
}

#[allow(dead_code)]
pub fn netif_ip() -> anyhow::Result<Ipv4Addr> {
let guard = WG_CTX.lock().unwrap();

if !guard.is_set() {
log::error!("Attempted to get ip without prior connection!");
return Err(anyhow::anyhow!("No netif to get ip from."));
}

let raw_ip = unsafe { (*(*guard.0).netif).ip_addr.addr };

Ok(Ipv4Addr::from(raw_ip.to_be_bytes()))
}

0 comments on commit 4142ee9

Please sign in to comment.