1 /*
2  * SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #ifndef __ESP_VFS_H__
8 #define __ESP_VFS_H__
9 
10 #include <stdint.h>
11 #include <stddef.h>
12 #include <stdarg.h>
13 #include <unistd.h>
14 #include <utime.h>
15 #include "freertos/FreeRTOS.h"
16 #include "freertos/semphr.h"
17 #include "esp_err.h"
18 #include <sys/types.h>
19 #include <sys/reent.h>
20 #include <sys/stat.h>
21 #include <sys/time.h>
22 #include <sys/termios.h>
23 #include <sys/poll.h>
24 #include <sys/dirent.h>
25 #include <string.h>
26 #include "sdkconfig.h"
27 
28 #ifdef __cplusplus
29 extern "C" {
30 #endif
31 
32 #ifndef _SYS_TYPES_FD_SET
33 #error "VFS should be used with FD_SETSIZE and FD_SET from sys/types.h"
34 #endif
35 
36 /**
37  * Maximum number of (global) file descriptors.
38  */
39 #define MAX_FDS         FD_SETSIZE /* for compatibility with fd_set and select() */
40 
41 /**
42  * Maximum length of path prefix (not including zero terminator)
43  */
44 #define ESP_VFS_PATH_MAX 15
45 
46 /**
47  * Default value of flags member in esp_vfs_t structure.
48  */
49 #define ESP_VFS_FLAG_DEFAULT        0
50 
51 /**
52  * Flag which indicates that FS needs extra context pointer in syscalls.
53  */
54 #define ESP_VFS_FLAG_CONTEXT_PTR    1
55 
56 /*
57  * @brief VFS identificator used for esp_vfs_register_with_id()
58  */
59 typedef int esp_vfs_id_t;
60 
61 /**
62  * @brief VFS semaphore type for select()
63  *
64  */
65 typedef struct
66 {
67     bool is_sem_local;      /*!< type of "sem" is SemaphoreHandle_t when true, defined by socket driver otherwise */
68     void *sem;              /*!< semaphore instance */
69 } esp_vfs_select_sem_t;
70 
71 /**
72  * @brief VFS definition structure
73  *
74  * This structure should be filled with pointers to corresponding
75  * FS driver functions.
76  *
77  * VFS component will translate all FDs so that the filesystem implementation
78  * sees them starting at zero. The caller sees a global FD which is prefixed
79  * with an pre-filesystem-implementation.
80  *
81  * Some FS implementations expect some state (e.g. pointer to some structure)
82  * to be passed in as a first argument. For these implementations,
83  * populate the members of this structure which have _p suffix, set
84  * flags member to ESP_VFS_FLAG_CONTEXT_PTR and provide the context pointer
85  * to esp_vfs_register function.
86  * If the implementation doesn't use this extra argument, populate the
87  * members without _p suffix and set flags member to ESP_VFS_FLAG_DEFAULT.
88  *
89  * If the FS driver doesn't provide some of the functions, set corresponding
90  * members to NULL.
91  */
92 typedef struct
93 {
94     int flags;      /*!< ESP_VFS_FLAG_CONTEXT_PTR or ESP_VFS_FLAG_DEFAULT */
95     union {
96         ssize_t (*write_p)(void* p, int fd, const void * data, size_t size);                         /*!< Write with context pointer */
97         ssize_t (*write)(int fd, const void * data, size_t size);                                    /*!< Write without context pointer */
98     };
99     union {
100         off_t (*lseek_p)(void* p, int fd, off_t size, int mode);                                     /*!< Seek with context pointer */
101         off_t (*lseek)(int fd, off_t size, int mode);                                                /*!< Seek without context pointer */
102     };
103     union {
104         ssize_t (*read_p)(void* ctx, int fd, void * dst, size_t size);                               /*!< Read with context pointer */
105         ssize_t (*read)(int fd, void * dst, size_t size);                                            /*!< Read without context pointer */
106     };
107     union {
108         ssize_t (*pread_p)(void *ctx, int fd, void * dst, size_t size, off_t offset);                /*!< pread with context pointer */
109         ssize_t (*pread)(int fd, void * dst, size_t size, off_t offset);                             /*!< pread without context pointer */
110     };
111     union {
112         ssize_t (*pwrite_p)(void *ctx, int fd, const void *src, size_t size, off_t offset);          /*!< pwrite with context pointer */
113         ssize_t (*pwrite)(int fd, const void *src, size_t size, off_t offset);                       /*!< pwrite without context pointer */
114     };
115     union {
116         int (*open_p)(void* ctx, const char * path, int flags, int mode);                            /*!< open with context pointer */
117         int (*open)(const char * path, int flags, int mode);                                         /*!< open without context pointer */
118     };
119     union {
120         int (*close_p)(void* ctx, int fd);                                                           /*!< close with context pointer */
121         int (*close)(int fd);                                                                        /*!< close without context pointer */
122     };
123     union {
124         int (*fstat_p)(void* ctx, int fd, struct stat * st);                                         /*!< fstat with context pointer */
125         int (*fstat)(int fd, struct stat * st);                                                      /*!< fstat without context pointer */
126     };
127 #ifdef CONFIG_VFS_SUPPORT_DIR
128     union {
129         int (*stat_p)(void* ctx, const char * path, struct stat * st);                               /*!< stat with context pointer */
130         int (*stat)(const char * path, struct stat * st);                                            /*!< stat without context pointer */
131     };
132     union {
133         int (*link_p)(void* ctx, const char* n1, const char* n2);                                    /*!< link with context pointer */
134         int (*link)(const char* n1, const char* n2);                                                 /*!< link without context pointer */
135     };
136     union {
137         int (*unlink_p)(void* ctx, const char *path);                                                /*!< unlink with context pointer */
138         int (*unlink)(const char *path);                                                             /*!< unlink without context pointer */
139     };
140     union {
141         int (*rename_p)(void* ctx, const char *src, const char *dst);                               /*!< rename with context pointer */
142         int (*rename)(const char *src, const char *dst);                                            /*!< rename without context pointer */
143     };
144     union {
145         DIR* (*opendir_p)(void* ctx, const char* name);                                             /*!< opendir with context pointer */
146         DIR* (*opendir)(const char* name);                                                          /*!< opendir without context pointer */
147     };
148     union {
149         struct dirent* (*readdir_p)(void* ctx, DIR* pdir);                                          /*!< readdir with context pointer */
150         struct dirent* (*readdir)(DIR* pdir);                                                       /*!< readdir without context pointer */
151     };
152     union {
153         int (*readdir_r_p)(void* ctx, DIR* pdir, struct dirent* entry, struct dirent** out_dirent); /*!< readdir_r with context pointer */
154         int (*readdir_r)(DIR* pdir, struct dirent* entry, struct dirent** out_dirent);              /*!< readdir_r without context pointer */
155     };
156     union {
157         long (*telldir_p)(void* ctx, DIR* pdir);                                                    /*!< telldir with context pointer */
158         long (*telldir)(DIR* pdir);                                                                 /*!< telldir without context pointer */
159     };
160     union {
161         void (*seekdir_p)(void* ctx, DIR* pdir, long offset);                                       /*!< seekdir with context pointer */
162         void (*seekdir)(DIR* pdir, long offset);                                                    /*!< seekdir without context pointer */
163     };
164     union {
165         int (*closedir_p)(void* ctx, DIR* pdir);                                                    /*!< closedir with context pointer */
166         int (*closedir)(DIR* pdir);                                                                 /*!< closedir without context pointer */
167     };
168     union {
169         int (*mkdir_p)(void* ctx, const char* name, mode_t mode);                                   /*!< mkdir with context pointer */
170         int (*mkdir)(const char* name, mode_t mode);                                                /*!< mkdir without context pointer */
171     };
172     union {
173         int (*rmdir_p)(void* ctx, const char* name);                                                /*!< rmdir with context pointer */
174         int (*rmdir)(const char* name);                                                             /*!< rmdir without context pointer */
175     };
176 #endif // CONFIG_VFS_SUPPORT_DIR
177     union {
178         int (*fcntl_p)(void* ctx, int fd, int cmd, int arg);                                        /*!< fcntl with context pointer */
179         int (*fcntl)(int fd, int cmd, int arg);                                                     /*!< fcntl without context pointer */
180     };
181     union {
182         int (*ioctl_p)(void* ctx, int fd, int cmd, va_list args);                                   /*!< ioctl with context pointer */
183         int (*ioctl)(int fd, int cmd, va_list args);                                                /*!< ioctl without context pointer */
184     };
185     union {
186         int (*fsync_p)(void* ctx, int fd);                                                          /*!< fsync with context pointer */
187         int (*fsync)(int fd);                                                                       /*!< fsync without context pointer */
188     };
189 #ifdef CONFIG_VFS_SUPPORT_DIR
190     union {
191         int (*access_p)(void* ctx, const char *path, int amode);                                    /*!< access with context pointer */
192         int (*access)(const char *path, int amode);                                                 /*!< access without context pointer */
193     };
194     union {
195         int (*truncate_p)(void* ctx, const char *path, off_t length);                               /*!< truncate with context pointer */
196         int (*truncate)(const char *path, off_t length);                                            /*!< truncate without context pointer */
197     };
198     union {
199         int (*utime_p)(void* ctx, const char *path, const struct utimbuf *times);                   /*!< utime with context pointer */
200         int (*utime)(const char *path, const struct utimbuf *times);                                /*!< utime without context pointer */
201     };
202 #endif // CONFIG_VFS_SUPPORT_DIR
203 #ifdef CONFIG_VFS_SUPPORT_TERMIOS
204     union {
205         int (*tcsetattr_p)(void *ctx, int fd, int optional_actions, const struct termios *p);       /*!< tcsetattr with context pointer */
206         int (*tcsetattr)(int fd, int optional_actions, const struct termios *p);                    /*!< tcsetattr without context pointer */
207     };
208     union {
209         int (*tcgetattr_p)(void *ctx, int fd, struct termios *p);                                   /*!< tcgetattr with context pointer */
210         int (*tcgetattr)(int fd, struct termios *p);                                                /*!< tcgetattr without context pointer */
211     };
212     union {
213         int (*tcdrain_p)(void *ctx, int fd);                                                        /*!< tcdrain with context pointer */
214         int (*tcdrain)(int fd);                                                                     /*!< tcdrain without context pointer */
215     };
216     union {
217         int (*tcflush_p)(void *ctx, int fd, int select);                                            /*!< tcflush with context pointer */
218         int (*tcflush)(int fd, int select);                                                         /*!< tcflush without context pointer */
219     };
220     union {
221         int (*tcflow_p)(void *ctx, int fd, int action);                                             /*!< tcflow with context pointer */
222         int (*tcflow)(int fd, int action);                                                          /*!< tcflow without context pointer */
223     };
224     union {
225         pid_t (*tcgetsid_p)(void *ctx, int fd);                                                     /*!< tcgetsid with context pointer */
226         pid_t (*tcgetsid)(int fd);                                                                  /*!< tcgetsid without context pointer */
227     };
228     union {
229         int (*tcsendbreak_p)(void *ctx, int fd, int duration);                                      /*!< tcsendbreak with context pointer */
230         int (*tcsendbreak)(int fd, int duration);                                                   /*!< tcsendbreak without context pointer */
231     };
232 #endif // CONFIG_VFS_SUPPORT_TERMIOS
233 #ifdef CONFIG_VFS_SUPPORT_SELECT
234     /** start_select is called for setting up synchronous I/O multiplexing of the desired file descriptors in the given VFS */
235     esp_err_t (*start_select)(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, esp_vfs_select_sem_t sem, void **end_select_args);
236     /** socket select function for socket FDs with the functionality of POSIX select(); this should be set only for the socket VFS */
237     int (*socket_select)(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval *timeout);
238     /** called by VFS to interrupt the socket_select call when select is activated from a non-socket VFS driver; set only for the socket driver */
239     void (*stop_socket_select)(void *sem);
240     /** stop_socket_select which can be called from ISR; set only for the socket driver */
241     void (*stop_socket_select_isr)(void *sem, BaseType_t *woken);
242     /** end_select is called to stop the I/O multiplexing and deinitialize the environment created by start_select for the given VFS */
243     void* (*get_socket_select_semaphore)(void);
244     /** get_socket_select_semaphore returns semaphore allocated in the socket driver; set only for the socket driver */
245     esp_err_t (*end_select)(void *end_select_args);
246 #endif // CONFIG_VFS_SUPPORT_SELECT
247 } esp_vfs_t;
248 
249 /**
250  * Register a virtual filesystem for given path prefix.
251  *
252  * @param base_path  file path prefix associated with the filesystem.
253  *                   Must be a zero-terminated C string, may be empty.
254  *                   If not empty, must be up to ESP_VFS_PATH_MAX
255  *                   characters long, and at least 2 characters long.
256  *                   Name must start with a "/" and must not end with "/".
257  *                   For example, "/data" or "/dev/spi" are valid.
258  *                   These VFSes would then be called to handle file paths such as
259  *                   "/data/myfile.txt" or "/dev/spi/0".
260  *                   In the special case of an empty base_path, a "fallback"
261  *                   VFS is registered. Such VFS will handle paths which are not
262  *                   matched by any other registered VFS.
263  * @param vfs  Pointer to esp_vfs_t, a structure which maps syscalls to
264  *             the filesystem driver functions. VFS component doesn't
265  *             assume ownership of this pointer.
266  * @param ctx  If vfs->flags has ESP_VFS_FLAG_CONTEXT_PTR set, a pointer
267  *             which should be passed to VFS functions. Otherwise, NULL.
268  *
269  * @return  ESP_OK if successful, ESP_ERR_NO_MEM if too many VFSes are
270  *          registered.
271  */
272 esp_err_t esp_vfs_register(const char* base_path, const esp_vfs_t* vfs, void* ctx);
273 
274 
275 /**
276  * Special case function for registering a VFS that uses a method other than
277  * open() to open new file descriptors from the interval <min_fd; max_fd).
278  *
279  * This is a special-purpose function intended for registering LWIP sockets to VFS.
280  *
281  * @param vfs Pointer to esp_vfs_t. Meaning is the same as for esp_vfs_register().
282  * @param ctx Pointer to context structure. Meaning is the same as for esp_vfs_register().
283  * @param min_fd The smallest file descriptor this VFS will use.
284  * @param max_fd Upper boundary for file descriptors this VFS will use (the biggest file descriptor plus one).
285  *
286  * @return  ESP_OK if successful, ESP_ERR_NO_MEM if too many VFSes are
287  *          registered, ESP_ERR_INVALID_ARG if the file descriptor boundaries
288  *          are incorrect.
289  */
290 esp_err_t esp_vfs_register_fd_range(const esp_vfs_t *vfs, void *ctx, int min_fd, int max_fd);
291 
292 /**
293  * Special case function for registering a VFS that uses a method other than
294  * open() to open new file descriptors. In comparison with
295  * esp_vfs_register_fd_range, this function doesn't pre-registers an interval
296  * of file descriptors. File descriptors can be registered later, by using
297  * esp_vfs_register_fd.
298  *
299  * @param vfs Pointer to esp_vfs_t. Meaning is the same as for esp_vfs_register().
300  * @param ctx Pointer to context structure. Meaning is the same as for esp_vfs_register().
301  * @param vfs_id Here will be written the VFS ID which can be passed to
302  *               esp_vfs_register_fd for registering file descriptors.
303  *
304  * @return  ESP_OK if successful, ESP_ERR_NO_MEM if too many VFSes are
305  *          registered, ESP_ERR_INVALID_ARG if the file descriptor boundaries
306  *          are incorrect.
307  */
308 esp_err_t esp_vfs_register_with_id(const esp_vfs_t *vfs, void *ctx, esp_vfs_id_t *vfs_id);
309 
310 /**
311  * Unregister a virtual filesystem for given path prefix
312  *
313  * @param base_path  file prefix previously used in esp_vfs_register call
314  * @return ESP_OK if successful, ESP_ERR_INVALID_STATE if VFS for given prefix
315  *         hasn't been registered
316  */
317 esp_err_t esp_vfs_unregister(const char* base_path);
318 
319 /**
320  * Unregister a virtual filesystem with the given index
321  *
322  * @param vfs_id  The VFS ID returned by esp_vfs_register_with_id
323  * @return ESP_OK if successful, ESP_ERR_INVALID_STATE if VFS for the given index
324  *         hasn't been registered
325  */
326 esp_err_t esp_vfs_unregister_with_id(esp_vfs_id_t vfs_id);
327 
328 /**
329  * Special function for registering another file descriptor for a VFS registered
330  * by esp_vfs_register_with_id.
331  *
332  * @param vfs_id VFS identificator returned by esp_vfs_register_with_id.
333  * @param fd The registered file descriptor will be written to this address.
334  *
335  * @return  ESP_OK if the registration is successful,
336  *          ESP_ERR_NO_MEM if too many file descriptors are registered,
337  *          ESP_ERR_INVALID_ARG if the arguments are incorrect.
338  */
339 esp_err_t esp_vfs_register_fd(esp_vfs_id_t vfs_id, int *fd);
340 
341 /**
342  * Special function for registering another file descriptor with given local_fd
343  * for a VFS registered by esp_vfs_register_with_id.
344  *
345  * @param vfs_id VFS identificator returned by esp_vfs_register_with_id.
346  * @param local_fd The fd in the local vfs. Passing -1 will set the local fd as the (*fd) value.
347  * @param permanent Whether the fd should be treated as permannet (not removed after close())
348  * @param fd The registered file descriptor will be written to this address.
349  *
350  * @return  ESP_OK if the registration is successful,
351  *          ESP_ERR_NO_MEM if too many file descriptors are registered,
352  *          ESP_ERR_INVALID_ARG if the arguments are incorrect.
353  */
354 esp_err_t esp_vfs_register_fd_with_local_fd(esp_vfs_id_t vfs_id, int local_fd, bool permanent, int *fd);
355 
356 /**
357  * Special function for unregistering a file descriptor belonging to a VFS
358  * registered by esp_vfs_register_with_id.
359  *
360  * @param vfs_id VFS identificator returned by esp_vfs_register_with_id.
361  * @param fd File descriptor which should be unregistered.
362  *
363  * @return  ESP_OK if the registration is successful,
364  *          ESP_ERR_INVALID_ARG if the arguments are incorrect.
365  */
366 esp_err_t esp_vfs_unregister_fd(esp_vfs_id_t vfs_id, int fd);
367 
368 /**
369  * These functions are to be used in newlib syscall table. They will be called by
370  * newlib when it needs to use any of the syscalls.
371  */
372 /**@{*/
373 ssize_t esp_vfs_write(struct _reent *r, int fd, const void * data, size_t size);
374 off_t esp_vfs_lseek(struct _reent *r, int fd, off_t size, int mode);
375 ssize_t esp_vfs_read(struct _reent *r, int fd, void * dst, size_t size);
376 int esp_vfs_open(struct _reent *r, const char * path, int flags, int mode);
377 int esp_vfs_close(struct _reent *r, int fd);
378 int esp_vfs_fstat(struct _reent *r, int fd, struct stat * st);
379 int esp_vfs_stat(struct _reent *r, const char * path, struct stat * st);
380 int esp_vfs_link(struct _reent *r, const char* n1, const char* n2);
381 int esp_vfs_unlink(struct _reent *r, const char *path);
382 int esp_vfs_rename(struct _reent *r, const char *src, const char *dst);
383 int esp_vfs_utime(const char *path, const struct utimbuf *times);
384 /**@}*/
385 
386 /**
387  * @brief Synchronous I/O multiplexing which implements the functionality of POSIX select() for VFS
388  * @param nfds      Specifies the range of descriptors which should be checked.
389  *                  The first nfds descriptors will be checked in each set.
390  * @param readfds   If not NULL, then points to a descriptor set that on input
391  *                  specifies which descriptors should be checked for being
392  *                  ready to read, and on output indicates which descriptors
393  *                  are ready to read.
394  * @param writefds  If not NULL, then points to a descriptor set that on input
395  *                  specifies which descriptors should be checked for being
396  *                  ready to write, and on output indicates which descriptors
397  *                  are ready to write.
398  * @param errorfds  If not NULL, then points to a descriptor set that on input
399  *                  specifies which descriptors should be checked for error
400  *                  conditions, and on output indicates which descriptors
401  *                  have error conditions.
402  * @param timeout   If not NULL, then points to timeval structure which
403  *                  specifies the time period after which the functions should
404  *                  time-out and return. If it is NULL, then the function will
405  *                  not time-out. Note that the timeout period is rounded up to
406  *                  the system tick and incremented by one.
407  *
408  * @return      The number of descriptors set in the descriptor sets, or -1
409  *              when an error (specified by errno) have occurred.
410  */
411 int esp_vfs_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval *timeout);
412 
413 /**
414  * @brief Notification from a VFS driver about a read/write/error condition
415  *
416  * This function is called when the VFS driver detects a read/write/error
417  * condition as it was requested by the previous call to start_select.
418  *
419  * @param sem semaphore structure which was passed to the driver by the start_select call
420  */
421 void esp_vfs_select_triggered(esp_vfs_select_sem_t sem);
422 
423 /**
424  * @brief Notification from a VFS driver about a read/write/error condition (ISR version)
425  *
426  * This function is called when the VFS driver detects a read/write/error
427  * condition as it was requested by the previous call to start_select.
428  *
429  * @param sem semaphore structure which was passed to the driver by the start_select call
430  * @param woken is set to pdTRUE if the function wakes up a task with higher priority
431  */
432 void esp_vfs_select_triggered_isr(esp_vfs_select_sem_t sem, BaseType_t *woken);
433 
434 /**
435  *
436  * @brief Implements the VFS layer of POSIX pread()
437  *
438  * @param fd         File descriptor used for read
439  * @param dst        Pointer to the buffer where the output will be written
440  * @param size       Number of bytes to be read
441  * @param offset     Starting offset of the read
442  *
443  * @return           A positive return value indicates the number of bytes read. -1 is return on failure and errno is
444  *                   set accordingly.
445  */
446 ssize_t esp_vfs_pread(int fd, void *dst, size_t size, off_t offset);
447 
448 /**
449  *
450  * @brief Implements the VFS layer of POSIX pwrite()
451  *
452  * @param fd         File descriptor used for write
453  * @param src        Pointer to the buffer from where the output will be read
454  * @param size       Number of bytes to write
455  * @param offset     Starting offset of the write
456  *
457  * @return           A positive return value indicates the number of bytes written. -1 is return on failure and errno is
458  *                   set accordingly.
459  */
460 ssize_t esp_vfs_pwrite(int fd, const void *src, size_t size, off_t offset);
461 
462 #ifdef __cplusplus
463 } // extern "C"
464 #endif
465 
466 #endif //__ESP_VFS_H__
467