Okay, here is a minimal sample C code for an FTP server on ESP-IDF, focusing on memory footprint and using a VFS-mounted SD card.
Important Caveats:
- Extremely Minimal: This code is highly simplified. It supports only one concurrent client connection and implements a minimal set of FTP commands (
USER, PASS, SYST, FEAT, PWD, CWD, TYPE I, PASV, LIST, RETR, STOR, QUIT). Many standard FTP features and error conditions are not handled.
- Security: There is no security. Passwords are sent in plaintext. This is suitable only for trusted local networks or testing.
- Error Handling: Error handling is basic.
- Performance: Performance for transfers might not be optimal due to simple blocking I/O and buffer management.
- SD Card Mount: This example includes the SD card mounting code. You will need to configure the specific pins for your SD card interface (SPI or SDMMC).
- Wi-Fi: This example includes placeholder calls for Wi-Fi setup, but you need to replace them with your actual Wi-Fi connection code.
- Memory: While aiming for minimal footprint, socket buffers and task stacks still consume RAM. Further optimization would require detailed analysis and custom buffer management.
Conceptual Structure:
- A main server task listens for incoming control connections on port 21.
- When a connection is accepted, a new task is created to handle that specific client.
- The client task processes commands received over the control connection.
- For data transfers (
LIST, RETR, STOR), the server enters passive mode (PASV), opens a temporary listening socket, and the client connects to it for data transfer.
- File system operations are done using standard C library functions (
fopen, fread, fwrite, fclose, opendir, readdir, closedir, stat, chdir) which operate on the VFS mounted at /sdcard.
#include <string.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h> // For chdir, getcwd
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_log.h"
#include "esp_err.h"
#include "esp_netif.h"
#include "esp_vfs_fat.h"
#include "driver/sdmmc_host.h"
#include "sdmmc_cmd.h"
// --- Configuration ---
#define FTP_PORT 21
#define FTP_MAX_CONNECTIONS 1 // Limit to 1 for minimalism
#define FTP_BUFFER_SIZE 256 // Command buffer size
#define FILE_BUFFER_SIZE 512 // File transfer buffer size
#define FTP_TASK_STACK_SIZE 4096 // Stack size for client tasks
#define FTP_SERVER_TASK_STACK_SIZE 3072 // Stack size for server listener task
#define SD_MOUNT_POINT "/sdcard"
// Define your SD card pins here (example for SPI)
#define PIN_NUM_MISO GPIO_NUM_19
#define PIN_NUM_MOSI GPIO_NUM_23
#define PIN_NUM_CLK GPIO_NUM_18
#define PIN_NUM_CS GPIO_NUM_5
// Minimal user/pass - DO NOT USE IN PRODUCTION
#define FTP_USER "esp32"
#define FTP_PASS "esp32"
// --- Globals for the *current* client (limited to 1) ---
static int control_sock = -1;
static int data_sock = -1;
static int data_listen_sock = -1;
static char current_dir[256] = "/"; // Logical FTP path
static bool logged_in = false;
static const char *TAG = "minimal_ftp";
// --- Helper Functions ---
// Send an FTP response code and message
static void send_response(int sock, int code, const char *message) {
char response[FTP_BUFFER_SIZE];
snprintf(response, sizeof(response), "%d %s\r\n", code, message);
ESP_LOGI(TAG, "Sending: %s", response);
send(sock, response, strlen(response), 0);
}
// Resolve an FTP path to a VFS path relative to the SD_MOUNT_POINT
// Simple implementation: prefix SD_MOUNT_POINT, handle "/" specially
static char* resolve_vfs_path(const char* ftp_path, char* vfs_path_buf, size_t buf_size) {
if (ftp_path[0] == '/') {
// Absolute path
snprintf(vfs_path_buf, buf_size, "%s%s", SD_MOUNT_POINT, ftp_path);
} else {
// Relative path to current_dir
snprintf(vfs_path_buf, buf_size, "%s%s/%s", SD_MOUNT_POINT, current_dir, ftp_path);
}
// Simple normalization: remove trailing slash unless it's the root
size_t len = strlen(vfs_path_buf);
if (len > strlen(SD_MOUNT_POINT) + 1 && vfs_path_buf[len-1] == '/') {
vfs_path_buf[len-1] = '\0';
}
// Replace "//" with "/" if any
char *ptr = vfs_path_buf + strlen(SD_MOUNT_POINT) + 1; // Start after /sdcard/
while((ptr = strstr(ptr, "//")) != NULL) {
memmove(ptr, ptr + 1, strlen(ptr + 1) + 1);
}
ESP_LOGD(TAG, "Resolved '%s' (from current '%s') to VFS path '%s'", ftp_path, current_dir, vfs_path_buf);
return vfs_path_buf;
}
// Wait for a data connection in passive mode
static esp_err_t setup_passive(int sock) {
struct sockaddr_in data_addr;
socklen_t len = sizeof(data_addr);
int reuse = 1;
if (data_listen_sock != -1) {
close(data_listen_sock); // Close previous passive listener if any
data_listen_sock = -1;
}
if (data_sock != -1) {
close(data_sock); // Close previous data connection if any
data_sock = -1;
}
data_listen_sock = socket(AF_INET, SOCK_STREAM, 0);
if (data_listen_sock < 0) {
ESP_LOGE(TAG, "Cannot create data socket");
send_response(sock, 425, "Cannot create data socket.");
return ESP_FAIL;
}
setsockopt(data_listen_sock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
// Bind to port 0 to let the OS choose a free port
memset(&data_addr, 0, sizeof(data_addr));
data_addr.sin_family = AF_INET;
data_addr.sin_port = htons(0); // Auto-assign port
data_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(data_listen_sock, (struct sockaddr *)&data_addr, sizeof(data_addr)) < 0) {
ESP_LOGE(TAG, "Data socket bind failed");
close(data_listen_sock);
data_listen_sock = -1;
send_response(sock, 425, "Cannot bind data socket.");
return ESP_FAIL;
}
if (listen(data_listen_sock, 1) < 0) { // Listen for 1 connection
ESP_LOGE(TAG, "Data socket listen failed");
close(data_listen_sock);
data_listen_sock = -1;
send_response(sock, 425, "Cannot listen on data socket.");
return ESP_FAIL;
}
// Get the assigned port
getsockname(data_listen_sock, (struct sockaddr *)&data_addr, &len);
int port = ntohs(data_addr.sin_port);
// Get ESP32's IP address
esp_netif_ip_info_t ip_info;
esp_netif_t *netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF"); // Assumes STA mode
if (!netif || esp_netif_get_ip_info(netif, &ip_info) != ESP_OK) {
ESP_LOGE(TAG, "Failed to get IP address");
close(data_listen_sock);
data_listen_sock = -1;
send_response(sock, 425, "Cannot get device IP.");
return ESP_FAIL;
}
uint8_t *ip_bytes = (uint8_t *)&ip_info.ip.addr;
char pasv_response[64];
snprintf(pasv_response, sizeof(pasv_response),
"Entering Passive Mode (%d,%d,%d,%d,%d,%d)",
ip_bytes[0], ip_bytes[1], ip_bytes[2], ip_bytes[3], port / 256, port % 256);
send_response(sock, 227, pasv_response);
// Wait for the client to connect to the data port
struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
data_sock = accept(data_listen_sock, (struct sockaddr *)&client_addr, &client_len);
// Close the listening socket immediately after accepting the connection
close(data_listen_sock);
data_listen_sock = -1;
if (data_sock < 0) {
ESP_LOGE(TAG, "Data socket accept failed");
data_sock = -1;
return ESP_FAIL;
}
ESP_LOGI(TAG, "Data connection accepted");
return ESP_OK;
}
// Close data connection if open
static void close_data_connection() {
if (data_sock != -1) {
ESP_LOGI(TAG, "Closing data connection");
close(data_sock);
data_sock = -1;
}
if (data_listen_sock != -1) {
ESP_LOGI(TAG, "Closing data listen connection");
close(data_listen_sock);
data_listen_sock = -1;
}
}
// --- FTP Command Handlers ---
static void handle_user(int sock, const char *arg) {
if (arg && strcmp(arg, FTP_USER) == 0) {
send_response(sock, 331, "Password required.");
} else {
send_response(sock, 530, "Not logged in.");
}
}
static void handle_pass(int sock, const char *arg) {
// This is a naive check - should be more secure in real app
// Also, USER must precede PASS
if (arg && strcmp(arg, FTP_PASS) == 0) {
logged_in = true;
send_response(sock, 230, "Login successful.");
} else {
send_response(sock, 530, "Not logged in.");
}
}
static void handle_syst(int sock, const char *arg) {
send_response(sock, 215, "UNIX Type: L8"); // Pretend to be UNIX for compatibility
}
static void handle_feat(int sock, const char *arg) {
send_response(sock, 211, "Features:");
send(sock, " PASV\r\n", strlen(" PASV\r\n"), 0); // Support Passive mode
send_response(sock, 211, "End");
}
static void handle_pwd(int sock, const char *arg) {
char response[FTP_BUFFER_SIZE];
snprintf(response, sizeof(response), "\"%s\"", current_dir);
send_response(sock, 257, response);
}
static void handle_cwd(int sock, const char *arg) {
if (!arg) {
send_response(sock, 501, "Argument required.");
return;
}
char vfs_path[256];
resolve_vfs_path(arg, vfs_path, sizeof(vfs_path));
// Check if it's a directory
struct stat st;
if (stat(vfs_path, &st) != 0 || !S_ISDIR(st.st_mode)) {
send_response(sock, 550, "Failed to change directory. Not found or not a directory.");
return;
}
// Update current_dir (logical FTP path)
if (arg[0] == '/') {
strncpy(current_dir, arg, sizeof(current_dir) - 1);
current_dir[sizeof(current_dir)-1] = '\0';
} else {
// Append to current_dir, handle ..
char temp_dir[256];
snprintf(temp_dir, sizeof(temp_dir), "%s/%s", current_dir, arg);
// Simple .. handling (only for trailing /..)
char *ptr = temp_dir;
while ((ptr = strstr(ptr, "/..")) != NULL) {
// Find the segment before /..
char *prev_slash = ptr;
while (prev_slash > temp_dir && *prev_slash != '/') prev_slash--;
if (prev_slash > temp_dir) {
// Remove the segment and /..
*prev_slash = '\0';
strcat(prev_slash, ptr + 3); // Copy string after /..
ptr = prev_slash; // Continue searching from new position
} else {
// Handle /.. at root level (stay at root) or invalid path
// In this minimal example, just remove /.. if it's at start or after root
if (strcmp(temp_dir, "/..") == 0) {
strcpy(temp_dir, "/");
} else if (strncmp(temp_dir, "/../", 4) == 0) {
memmove(temp_dir, temp_dir + 3, strlen(temp_dir + 3) + 1);
} else {
// More complex cases like /a/../b/.. are not handled perfectly here
ptr++; // Move past the current //.. to avoid infinite loop if not replaced
}
}
}
// Ensure root is just "/"
if (strcmp(temp_dir, "") == 0) {
strcpy(temp_dir, "/");
}
strncpy(current_dir, temp_dir, sizeof(current_dir) - 1);
current_dir[sizeof(current_dir)-1] = '\0';
}
// Ensure current_dir ends with '/' unless it's just "/"
if (current_dir[0] != '/' || current_dir[1] != '\0') {
size_t len = strlen(current_dir);
if (len > 0 && current_dir[len-1] != '/') {
strcat(current_dir, "/");
}
}
ESP_LOGI(TAG, "Current directory set to: %s", current_dir);
send_response(sock, 250, "Directory successfully changed.");
}
static void handle_type(int sock, const char *arg) {
// We only support Binary mode
if (arg && (strcmp(arg, "I") == 0 || strcmp(arg, "L 8") == 0)) {
send_response(sock, 200, "Type set to I.");
} else {
send_response(sock, 504, "Type not supported.");
}
}
static void handle_pasv(int sock, const char *arg) {
setup_passive(sock); // This function handles the response
}
static void handle_list(int sock, const char *arg) {
if (data_sock == -1) {
send_response(sock, 425, "Use PASV first.");
return;
}
send_response(sock, 150, "Opening data connection for directory listing.");
char vfs_path[256];
// LIST can take a path argument, but minimal implementation lists current_dir
resolve_vfs_path(".", vfs_path, sizeof(vfs_path));
DIR *dir = opendir(vfs_path);
if (!dir) {
ESP_LOGE(TAG, "Failed to open directory %s", vfs_path);
send_response(sock, 550, "Failed to open directory.");
close_data_connection();
return;
}
struct dirent *entry;
char list_item[256]; // Buffer for one list item
while ((entry = readdir(dir)) != NULL) {
if (entry->d_name[0] == '.') continue; // Skip hidden files (., ..)
char full_path[256];
snprintf(full_path, sizeof(full_path), "%s/%s", vfs_path, entry->d_name);
struct stat st;
// Use fstatat if available and preferred, but stat is more portable C standard
if (stat(full_path, &st) == 0) {
// Minimalist ls -l like format: drwxr-xr-x 1 1 1 size Jan 01 1970 name
// Permissions, links, user, group, date are faked for simplicity
char type = S_ISDIR(st.st_mode) ? 'd' : '-';
snprintf(list_item, sizeof(list_item), "%c--------- 1 1 1 %10ld Jan 01 1970 %s\r\n",
type, (long)st.st_size, entry->d_name); // Use long for size
send(data_sock, list_item, strlen(list_item), 0);
} else {
// Fallback if stat fails
snprintf(list_item, sizeof(list_item), "- --------- 1 1 1 %10d Jan 01 1970 %s\r\n",
0, entry->d_name);
send(data_sock, list_item, strlen(list_item), 0);
}
}
closedir(dir);
send_response(sock, 226, "Directory send OK.");
close_data_connection();
}
static void handle_retr(int sock, const char *arg) {
if (!arg) {
send_response(sock, 501, "Argument required.");
return;
}
if (data_sock == -1) {
send_response(sock, 425, "Use PASV first.");
return;
}
char vfs_path[256];
resolve_vfs_path(arg, vfs_path, sizeof(vfs_path));
FILE *f = fopen(vfs_path, "rb");
if (!f) {
ESP_LOGE(TAG, "Failed to open file for RETR: %s", vfs_path);
send_response(sock, 550, "Failed to open file.");
close_data_connection();
return;
}
struct stat st;
if (stat(vfs_path, &st) == 0) {
char response[64];
snprintf(response, sizeof(response), "Opening BINARY mode data connection for %s (%ld bytes).", arg, (long)st.st_size);
send_response(sock, 150, response);
} else {
send_response(sock, 150, "Opening BINARY mode data connection.");
}
uint8_t file_buffer[FILE_BUFFER_SIZE];
size_t read_bytes;
while ((read_bytes = fread(file_buffer, 1, sizeof(file_buffer), f)) > 0) {
if (send(data_sock, file_buffer, read_bytes, 0) < 0) {
ESP_LOGE(TAG, "Error sending file data");
break; // Exit loop on send error
}
}
fclose(f);
if (read_bytes == 0 && ferror(f)) {
ESP_LOGE(TAG, "Error reading file");
send_response(sock, 551, "Error reading file.");
} else {
send_response(sock, 226, "Transfer complete.");
}
close_data_connection();
}
static void handle_stor(int sock, const char *arg) {
if (!arg) {
send_response(sock, 501, "Argument required.");
return;
}
if (data_sock == -1) {
send_response(sock, 425, "Use PASV first.");
return;
}
char vfs_path[256];
resolve_vfs_path(arg, vfs_path, sizeof(vfs_path));
send_response(sock, 150, "Ok to send data.");
FILE *f = fopen(vfs_path, "wb");
if (!f) {
ESP_LOGE(TAG, "Failed to open file for STOR: %s", vfs_path);
send_response(sock, 553, "Failed to open file for writing.");
close_data_connection();
return;
}
uint8_t file_buffer[FILE_BUFFER_SIZE];
ssize_t recv_bytes;
while ((recv_bytes = recv(data_sock, file_buffer, sizeof(file_buffer), 0)) > 0) {
if (fwrite(file_buffer, 1, recv_bytes, f) != recv_bytes) {
ESP_LOGE(TAG, "Error writing file data");
// Attempt to close file and indicate error
fclose(f);
f = NULL; // Mark file handle as invalid
break; // Exit loop on write error
}
}
if (f) fclose(f); // Close file if it wasn't closed by error
close_data_connection();
if (recv_bytes < 0) {
ESP_LOGE(TAG, "Error receiving file data");
send_response(sock, 426, "Connection closed; aborted transfer.");
} else { // recv_bytes == 0 means client closed connection normally
send_response(sock, 226, "Transfer complete.");
}
}
static void handle_quit(int sock, const char *arg) {
send_response(sock, 221, "Goodbye.");
close_data_connection();
close(sock);
control_sock = -1; // Mark as closed
}
static void handle_noop(int sock, const char *arg) {
send_response(sock, 200, "NOOP ok.");
}
// --- Client Task ---
static void ftp_client_task(void *pvParameters) {
int sock = (int)pvParameters;
control_sock = sock; // Store global handle (works only for 1 client)
logged_in = false; // Reset login state for new client
strcpy(current_dir, "/"); // Reset current directory
send_response(sock, 220, "ESP32 Minimal FTP Server");
char recv_buf[FTP_BUFFER_SIZE];
int len;
while (control_sock != -1 && (len = recv(sock, recv_buf, sizeof(recv_buf) - 1, 0)) > 0) {
recv_buf[len] = 0; // Null-terminate
// Process each line in the buffer (commands are \r\n terminated)
char *cmd_start = recv_buf;
char *cmd_end;
while ((cmd_end = strstr(cmd_start, "\r\n")) != NULL) {
*cmd_end = 0; // Null-terminate the command line
char *cmd = cmd_start;
char *arg = NULL;
// Find command and argument
char *space = strchr(cmd, ' ');
if (space) {
*space = 0; // Null-terminate command
arg = space + 1; // Argument starts after space
// Trim leading spaces from arg
while (*arg == ' ') arg++;
if (*arg == '\0') arg = NULL; // No argument if only spaces
}
ESP_LOGI(TAG, "Received command: %s (arg: %s)", cmd, arg ? arg : "(none)");
// --- Command Dispatch ---
// Basic string comparison - case-insensitive check is needed for full compliance
if (strcasecmp(cmd, "USER") == 0) {
handle_user(sock, arg);
} else if (strcasecmp(cmd, "PASS") == 0) {
handle_pass(sock, arg);
} else if (!logged_in) {
send_response(sock, 530, "Please login with USER and PASS.");
}
else if (strcasecmp(cmd, "SYST") == 0) {
handle_syst(sock, arg);
} else if (strcasecmp(cmd, "FEAT") == 0) {
handle_feat(sock, arg);
} else if (strcasecmp(cmd, "PWD") == 0 || strcasecmp(cmd, "XPWD") == 0) {
handle_pwd(sock, arg);
} else if (strcasecmp(cmd, "CWD") == 0 || strcasecmp(cmd, "XCWD") == 0) {
handle_cwd(sock, arg);
} else if (strcasecmp(cmd, "TYPE") == 0) {
handle_type(sock, arg);
} else if (strcasecmp(cmd, "PASV") == 0) {
handle_pasv(sock, arg);
} else if (strcasecmp(cmd, "LIST") == 0) {
handle_list(sock, arg);
} else if (strcasecmp(cmd, "RETR") == 0) {
handle_retr(sock, arg);
} else if (strcasecmp(cmd, "STOR") == 0) {
handle_stor(sock, arg);
} else if (strcasecmp(cmd, "QUIT") == 0) {
handle_quit(sock, arg);
goto end_task; // Exit task after handling QUIT
} else if (strcasecmp(cmd, "NOOP") == 0) {
handle_noop(sock, arg);
}
// Add more minimal commands here as needed (RNFR, RNTO, DELE, RMD, MKD etc.)
else {
ESP_LOGW(TAG, "Unknown command: %s", cmd);
send_response(sock, 502, "Command not implemented.");
}
cmd_start = cmd_end + 2; // Move to the next line
}
// Shift remaining data in buffer to the front
if (cmd_start != recv_buf) {
int remaining = len - (cmd_start - recv_buf);
if (remaining > 0) {
memmove(recv_buf, cmd_start, remaining);
len = remaining;
} else {
len = 0;
}
}
recv_buf[len] = 0; // Ensure null-termination of the remaining part
}
// recv returned 0 or error, or QUIT was handled
if (len <= 0 && control_sock != -1) {
ESP_LOGI(TAG, "Client disconnected");
close(control_sock);
}
end_task:
control_sock = -1; // Clear global handle
close_data_connection(); // Ensure data sockets are closed
vTaskDelete(NULL);
}
// --- SD Card Initialization ---
esp_err_t init_sd_card() {
ESP_LOGI(TAG, "Initializing SD card");
esp_err_t ret;
esp_vfs_fat_sdmmc_mount_config_t mount_config = {
.format_if_mount_failed = false, // Set to true to format if mount fails
.max_files = 5, // Set to 5 for minimal memory usage
.allocation_unit_size = 16 * 1024
};
sdmmc_card_t *card;
// Use SD_SPI_HOST for SPI mode, SDMMC_HOST for SDMMC mode
// For SPI mode:
sdmmc_host_t host = SDSPI_HOST_DEFAULT();
spi_bus_config_t bus_cfg = {
.miso_io_num = PIN_NUM_MISO,
.mosi_io_num = PIN_NUM_MOSI,
.sclk_io_num = PIN_NUM_CLK,
.quadwp_io_num = -1,
.quadhd_io_num = -1,
.max_transfer_sz = 4000, // Keep buffer small
};
ret = spi_bus_initialize(host.slot, &bus_cfg, SPI_DMA_CHAN_NONE); // No DMA for minimal
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to initialize SPI bus.");
return ret;
}
sdspi_device_config_t slot_config = SDSPI_DEVICE_CONFIG_DEFAULT();
slot_config.gpio_cs = PIN_NUM_CS;
slot_config.host_id = host.slot;
ret = esp_vfs_fat_sdspi_mount(SD_MOUNT_POINT, &host, &slot_config, &mount_config, &card);
// For SDMMC mode (alternate):
/*
sdmmc_host_t host = SDMMC_HOST_DEFAULT();
// Configure SDMMC pins here if not using default
// host.slot = HSPI_HOST; // Example: use HSPI host (SDMMC controller 1)
// sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT();
// slot_config.gpio_cd = ...; // Card detect
// slot_config.gpio_wp = ...; // Write protect
ret = esp_vfs_fat_sdmmc_mount(SD_MOUNT_POINT, &host, &mount_config, &card);
*/
if (ret != ESP_OK) {
if (ret == ESP_FAIL) {
ESP_LOGE(TAG, "Failed to mount filesystem. If you want to format, set format_if_mount_failed = true.");
} else {
ESP_LOGE(TAG, "Failed to initialize the card (%s).", esp_err_to_name(ret));
}
// For SPI, release bus on failure
if (host.slot == SDSPI_HOST_DEFAULT().slot) {
spi_bus_free(host.slot);
}
} else {
ESP_LOGI(TAG, "Filesystem mounted");
sdmmc_card_print_info(stdout, card);
}
return ret;
}
// --- Server Listener Task ---
static void ftp_server_task(void *pvParameters) {
char addr_str[128];
int addr_family = AF_INET;
int ip_protocol = IPPROTO_IP;
struct sockaddr_in listen_addr;
memset(&listen_addr, 0, sizeof(listen_addr));
listen_addr.sin_family = addr_family;
listen_addr.sin_port = htons(FTP_PORT);
listen_addr.sin_addr.s_addr = htonl(INADDR_ANY);
int listen_sock = socket(AF_INET, SOCK_STREAM, ip_protocol);
if (listen_sock < 0) {
ESP_LOGE(TAG, "Unable to create socket: errno %d", errno);
vTaskDelete(NULL);
return;
}
int reuse = 1;
setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
ESP_LOGI(TAG, "Socket created");
if (bind(listen_sock, (struct sockaddr *)&listen_addr, sizeof(listen_addr)) < 0) {
ESP_LOGE(TAG, "Socket unable to bind: errno %d", errno);
goto clean_up;
}
ESP_LOGI(TAG, "Socket bound to port %d", FTP_PORT);
if (listen(listen_sock, FTP_MAX_CONNECTIONS) < 0) {
ESP_LOGE(TAG, "Error listening on socket: errno %d", errno);
goto clean_up;
}
ESP_LOGI(TAG, "Socket listening");
while (1) {
ESP_LOGI(TAG, "Waiting for connection...");
struct sockaddr_in source_addr;
socklen_t addrlen = sizeof(source_addr);
int new_sock = accept(listen_sock, (struct sockaddr *)&source_addr, &addrlen);
if (new_sock < 0) {
ESP_LOGE(TAG, "Unable to accept connection: errno %d", errno);
continue;
}
inet_ntoa_r(((struct sockaddr_in *)&source_addr)->sin_addr.s_addr, addr_str, sizeof(addr_str) - 1);
ESP_LOGI(TAG, "Client connected: %s", addr_str);
// This minimal server only handles one client at a time.
// If control_sock is not -1, a client is already connected.
if (control_sock != -1) {
ESP_LOGW(TAG, "Another client already connected. Rejecting new connection.");
const char *busy_msg = "421 Server is busy.\r\n";
send(new_sock, busy_msg, strlen(busy_msg), 0);
close(new_sock);
} else {
// Create a task for the new client
if (xTaskCreate(ftp_client_task, "ftp_client", FTP_TASK_STACK_SIZE, (void *)new_sock, 5, NULL) != pdPASS) {
ESP_LOGE(TAG, "Failed to create client task");
const char *err_msg = "421 Server internal error.\r\n";
send(new_sock, err_msg, strlen(err_msg), 0);
close(new_sock);
control_sock = -1; // Ensure state is clear
} else {
ESP_LOGI(TAG, "Client task created");
// The ftp_client_task now manages the 'control_sock' state
}
}
}
clean_up:
close(listen_sock);
vTaskDelete(NULL);
}
// --- Main Application ---
// Placeholder for your Wi-Fi setup
extern esp_err_t example_connect(void);
extern esp_err_t example_disconnect(void);
void app_main(void) {
ESP_LOGI(TAG, "Starting Minimal FTP Server");
// Initialize TCP/IP stack
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
// Create default Wi-Fi station
esp_netif_create_default_wifi_sta();
// Connect to Wi-Fi (replace with your actual Wi-Fi connect code)
// This assumes example_connect() blocks until connected or fails
ESP_LOGI(TAG, "Connecting to Wi-Fi...");
ESP_ERROR_CHECK(example_connect()); // !! REPLACE THIS WITH YOUR WIFI CONNECT CODE !!
ESP_LOGI(TAG, "Wi-Fi connected");
// Initialize and mount SD card VFS
ESP_ERROR_CHECK(init_sd_card());
// Create the main FTP server task
xTaskCreate(ftp_server_task, "ftp_server", FTP_SERVER_TASK_STACK_SIZE, NULL, 5, NULL);
ESP_LOGI(TAG, "FTP Server started");
// Your main task can do other things or simply yield/sleep
while(1) {
vTaskDelay(pdMS_TO_TICKS(1000));
}
// Note: SD card unmount and Wi-Fi disconnect are not included in this minimal example's main loop
// as the server task runs indefinitely. Proper shutdown would require signaling tasks to stop.
// esp_vfs_fat_sdmmc_unmount();
// spi_bus_free(SDSPI_HOST); // Or SDMMC_HOST depending on your config
// example_disconnect();
}
To Use This Code:
- Integrate: Add this
.c file to your ESP-IDF project's main component.
- Wi-Fi: Replace the
example_connect() and example_disconnect() calls with your actual Wi-Fi connection logic. You need to ensure the device connects to your network and gets an IP address before the FTP server task starts listening. A common pattern is to wait for the IP_EVENT_STA_GOT_IP event.
- SD Card Pins: Configure the
PIN_NUM_MISO, PIN_NUM_MOSI, PIN_NUM_CLK, and PIN_NUM_CS defines to match your specific hardware and how the SD card is wired (SPI interface shown). If using the SDMMC interface, you'll need to adjust the init_sd_card function accordingly.
- VFS Path: The server mounts the SD card at
/sdcard. The FTP root / corresponds to /sdcard in the VFS.
- Build and Flash: Build the project using
idf.py build and flash using idf.py flash.
- Test: Find the ESP32's IP address (via logs or your Wi-Fi connection status). Use an FTP client (like FileZilla, WinSCP, or the command-line
ftp tool) to connect to that IP address on port 21. Use the configured FTP_USER and FTP_PASS.
This provides a functional, albeit limited, FTP server demonstrating the necessary components (sockets, VFS, tasks) in an ESP-IDF environment with a focus on keeping the code size and immediate resource usage down.