1 /*
2  * This file is part of the MicroPython project, http://micropython.org/
3  *
4  * The MIT License (MIT)
5  *
6  * Copyright (c) 2014 Damien P. George
7  * Copyright (c) 2016 Paul Sokolovsky
8  *
9  * Permission is hereby granted, free of charge, to any person obtaining a copy
10  * of this software and associated documentation files (the "Software"), to deal
11  * in the Software without restriction, including without limitation the rights
12  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13  * copies of the Software, and to permit persons to whom the Software is
14  * furnished to do so, subject to the following conditions:
15  *
16  * The above copyright notice and this permission notice shall be included in
17  * all copies or substantial portions of the Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25  * THE SOFTWARE.
26  */
27 
28 #include "py/mpconfig.h"
29 #if MICROPY_VFS_FAT
30 
31 #if !MICROPY_VFS
32 #error "with MICROPY_VFS_FAT enabled, must also enable MICROPY_VFS"
33 #endif
34 
35 #include <string.h>
36 #include "py/runtime.h"
37 #include "py/mperrno.h"
38 #include "lib/oofatfs/ff.h"
39 #include "extmod/vfs_fat.h"
40 #include "shared/timeutils/timeutils.h"
41 
42 #if FF_MAX_SS == FF_MIN_SS
43 #define SECSIZE(fs) (FF_MIN_SS)
44 #else
45 #define SECSIZE(fs) ((fs)->ssize)
46 #endif
47 
48 #define mp_obj_fat_vfs_t fs_user_mount_t
49 
fat_vfs_import_stat(void * vfs_in,const char * path)50 STATIC mp_import_stat_t fat_vfs_import_stat(void *vfs_in, const char *path) {
51     fs_user_mount_t *vfs = vfs_in;
52     FILINFO fno;
53     assert(vfs != NULL);
54     FRESULT res = f_stat(&vfs->fatfs, path, &fno);
55     if (res == FR_OK) {
56         if ((fno.fattrib & AM_DIR) != 0) {
57             return MP_IMPORT_STAT_DIR;
58         } else {
59             return MP_IMPORT_STAT_FILE;
60         }
61     }
62     return MP_IMPORT_STAT_NO_EXIST;
63 }
64 
fat_vfs_make_new(const mp_obj_type_t * type,size_t n_args,size_t n_kw,const mp_obj_t * args)65 STATIC mp_obj_t fat_vfs_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
66     mp_arg_check_num(n_args, n_kw, 1, 1, false);
67 
68     // create new object
69     fs_user_mount_t *vfs = m_new_obj(fs_user_mount_t);
70     vfs->base.type = type;
71     vfs->fatfs.drv = vfs;
72 
73     // Initialise underlying block device
74     vfs->blockdev.flags = MP_BLOCKDEV_FLAG_FREE_OBJ;
75     vfs->blockdev.block_size = FF_MIN_SS; // default, will be populated by call to MP_BLOCKDEV_IOCTL_BLOCK_SIZE
76     mp_vfs_blockdev_init(&vfs->blockdev, args[0]);
77 
78     // mount the block device so the VFS methods can be used
79     FRESULT res = f_mount(&vfs->fatfs);
80     if (res == FR_NO_FILESYSTEM) {
81         // don't error out if no filesystem, to let mkfs()/mount() create one if wanted
82         vfs->blockdev.flags |= MP_BLOCKDEV_FLAG_NO_FILESYSTEM;
83     } else if (res != FR_OK) {
84         mp_raise_OSError(fresult_to_errno_table[res]);
85     }
86 
87     return MP_OBJ_FROM_PTR(vfs);
88 }
89 
90 #if _FS_REENTRANT
fat_vfs_del(mp_obj_t self_in)91 STATIC mp_obj_t fat_vfs_del(mp_obj_t self_in) {
92     mp_obj_fat_vfs_t *self = MP_OBJ_TO_PTR(self_in);
93     // f_umount only needs to be called to release the sync object
94     f_umount(&self->fatfs);
95     return mp_const_none;
96 }
97 STATIC MP_DEFINE_CONST_FUN_OBJ_1(fat_vfs_del_obj, fat_vfs_del);
98 #endif
99 
fat_vfs_mkfs(mp_obj_t bdev_in)100 STATIC mp_obj_t fat_vfs_mkfs(mp_obj_t bdev_in) {
101     // create new object
102     fs_user_mount_t *vfs = MP_OBJ_TO_PTR(fat_vfs_make_new(&mp_fat_vfs_type, 1, 0, &bdev_in));
103 
104     // make the filesystem
105     uint8_t working_buf[FF_MAX_SS];
106     FRESULT res = f_mkfs(&vfs->fatfs, FM_FAT | FM_SFD, 0, working_buf, sizeof(working_buf));
107     if (res == FR_MKFS_ABORTED) { // Probably doesn't support FAT16
108         res = f_mkfs(&vfs->fatfs, FM_FAT32, 0, working_buf, sizeof(working_buf));
109     }
110     if (res != FR_OK) {
111         mp_raise_OSError(fresult_to_errno_table[res]);
112     }
113 
114     return mp_const_none;
115 }
116 STATIC MP_DEFINE_CONST_FUN_OBJ_1(fat_vfs_mkfs_fun_obj, fat_vfs_mkfs);
117 STATIC MP_DEFINE_CONST_STATICMETHOD_OBJ(fat_vfs_mkfs_obj, MP_ROM_PTR(&fat_vfs_mkfs_fun_obj));
118 
119 typedef struct _mp_vfs_fat_ilistdir_it_t {
120     mp_obj_base_t base;
121     mp_fun_1_t iternext;
122     bool is_str;
123     FF_DIR dir;
124 } mp_vfs_fat_ilistdir_it_t;
125 
mp_vfs_fat_ilistdir_it_iternext(mp_obj_t self_in)126 STATIC mp_obj_t mp_vfs_fat_ilistdir_it_iternext(mp_obj_t self_in) {
127     mp_vfs_fat_ilistdir_it_t *self = MP_OBJ_TO_PTR(self_in);
128 
129     for (;;) {
130         FILINFO fno;
131         FRESULT res = f_readdir(&self->dir, &fno);
132         char *fn = fno.fname;
133         if (res != FR_OK || fn[0] == 0) {
134             // stop on error or end of dir
135             break;
136         }
137 
138         // Note that FatFS already filters . and .., so we don't need to
139 
140         // make 4-tuple with info about this entry
141         mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(4, NULL));
142         if (self->is_str) {
143             t->items[0] = mp_obj_new_str(fn, strlen(fn));
144         } else {
145             t->items[0] = mp_obj_new_bytes((const byte *)fn, strlen(fn));
146         }
147         if (fno.fattrib & AM_DIR) {
148             // dir
149             t->items[1] = MP_OBJ_NEW_SMALL_INT(MP_S_IFDIR);
150         } else {
151             // file
152             t->items[1] = MP_OBJ_NEW_SMALL_INT(MP_S_IFREG);
153         }
154         t->items[2] = MP_OBJ_NEW_SMALL_INT(0); // no inode number
155         t->items[3] = mp_obj_new_int_from_uint(fno.fsize);
156 
157         return MP_OBJ_FROM_PTR(t);
158     }
159 
160     // ignore error because we may be closing a second time
161     f_closedir(&self->dir);
162 
163     return MP_OBJ_STOP_ITERATION;
164 }
165 
fat_vfs_ilistdir_func(size_t n_args,const mp_obj_t * args)166 STATIC mp_obj_t fat_vfs_ilistdir_func(size_t n_args, const mp_obj_t *args) {
167     mp_obj_fat_vfs_t *self = MP_OBJ_TO_PTR(args[0]);
168     bool is_str_type = true;
169     const char *path;
170     if (n_args == 2) {
171         if (mp_obj_get_type(args[1]) == &mp_type_bytes) {
172             is_str_type = false;
173         }
174         path = mp_obj_str_get_str(args[1]);
175     } else {
176         path = "";
177     }
178 
179     // Create a new iterator object to list the dir
180     mp_vfs_fat_ilistdir_it_t *iter = m_new_obj(mp_vfs_fat_ilistdir_it_t);
181     iter->base.type = &mp_type_polymorph_iter;
182     iter->iternext = mp_vfs_fat_ilistdir_it_iternext;
183     iter->is_str = is_str_type;
184     FRESULT res = f_opendir(&self->fatfs, &iter->dir, path);
185     if (res != FR_OK) {
186         mp_raise_OSError(fresult_to_errno_table[res]);
187     }
188 
189     return MP_OBJ_FROM_PTR(iter);
190 }
191 STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(fat_vfs_ilistdir_obj, 1, 2, fat_vfs_ilistdir_func);
192 
fat_vfs_remove_internal(mp_obj_t vfs_in,mp_obj_t path_in,mp_int_t attr)193 STATIC mp_obj_t fat_vfs_remove_internal(mp_obj_t vfs_in, mp_obj_t path_in, mp_int_t attr) {
194     mp_obj_fat_vfs_t *self = MP_OBJ_TO_PTR(vfs_in);
195     const char *path = mp_obj_str_get_str(path_in);
196 
197     FILINFO fno;
198     FRESULT res = f_stat(&self->fatfs, path, &fno);
199 
200     if (res != FR_OK) {
201         mp_raise_OSError(fresult_to_errno_table[res]);
202     }
203 
204     // check if path is a file or directory
205     if ((fno.fattrib & AM_DIR) == attr) {
206         res = f_unlink(&self->fatfs, path);
207 
208         if (res != FR_OK) {
209             mp_raise_OSError(fresult_to_errno_table[res]);
210         }
211         return mp_const_none;
212     } else {
213         mp_raise_OSError(attr ? MP_ENOTDIR : MP_EISDIR);
214     }
215 }
216 
fat_vfs_remove(mp_obj_t vfs_in,mp_obj_t path_in)217 STATIC mp_obj_t fat_vfs_remove(mp_obj_t vfs_in, mp_obj_t path_in) {
218     return fat_vfs_remove_internal(vfs_in, path_in, 0); // 0 == file attribute
219 }
220 STATIC MP_DEFINE_CONST_FUN_OBJ_2(fat_vfs_remove_obj, fat_vfs_remove);
221 
fat_vfs_rmdir(mp_obj_t vfs_in,mp_obj_t path_in)222 STATIC mp_obj_t fat_vfs_rmdir(mp_obj_t vfs_in, mp_obj_t path_in) {
223     return fat_vfs_remove_internal(vfs_in, path_in, AM_DIR);
224 }
225 STATIC MP_DEFINE_CONST_FUN_OBJ_2(fat_vfs_rmdir_obj, fat_vfs_rmdir);
226 
fat_vfs_rename(mp_obj_t vfs_in,mp_obj_t path_in,mp_obj_t path_out)227 STATIC mp_obj_t fat_vfs_rename(mp_obj_t vfs_in, mp_obj_t path_in, mp_obj_t path_out) {
228     mp_obj_fat_vfs_t *self = MP_OBJ_TO_PTR(vfs_in);
229     const char *old_path = mp_obj_str_get_str(path_in);
230     const char *new_path = mp_obj_str_get_str(path_out);
231     FRESULT res = f_rename(&self->fatfs, old_path, new_path);
232     if (res == FR_EXIST) {
233         // if new_path exists then try removing it (but only if it's a file)
234         fat_vfs_remove_internal(vfs_in, path_out, 0); // 0 == file attribute
235         // try to rename again
236         res = f_rename(&self->fatfs, old_path, new_path);
237     }
238     if (res == FR_OK) {
239         return mp_const_none;
240     } else {
241         mp_raise_OSError(fresult_to_errno_table[res]);
242     }
243 
244 }
245 STATIC MP_DEFINE_CONST_FUN_OBJ_3(fat_vfs_rename_obj, fat_vfs_rename);
246 
fat_vfs_mkdir(mp_obj_t vfs_in,mp_obj_t path_o)247 STATIC mp_obj_t fat_vfs_mkdir(mp_obj_t vfs_in, mp_obj_t path_o) {
248     mp_obj_fat_vfs_t *self = MP_OBJ_TO_PTR(vfs_in);
249     const char *path = mp_obj_str_get_str(path_o);
250     FRESULT res = f_mkdir(&self->fatfs, path);
251     if (res == FR_OK) {
252         return mp_const_none;
253     } else {
254         mp_raise_OSError(fresult_to_errno_table[res]);
255     }
256 }
257 STATIC MP_DEFINE_CONST_FUN_OBJ_2(fat_vfs_mkdir_obj, fat_vfs_mkdir);
258 
259 // Change current directory.
fat_vfs_chdir(mp_obj_t vfs_in,mp_obj_t path_in)260 STATIC mp_obj_t fat_vfs_chdir(mp_obj_t vfs_in, mp_obj_t path_in) {
261     mp_obj_fat_vfs_t *self = MP_OBJ_TO_PTR(vfs_in);
262     const char *path;
263     path = mp_obj_str_get_str(path_in);
264 
265     FRESULT res = f_chdir(&self->fatfs, path);
266 
267     if (res != FR_OK) {
268         mp_raise_OSError(fresult_to_errno_table[res]);
269     }
270 
271     return mp_const_none;
272 }
273 STATIC MP_DEFINE_CONST_FUN_OBJ_2(fat_vfs_chdir_obj, fat_vfs_chdir);
274 
275 // Get the current directory.
fat_vfs_getcwd(mp_obj_t vfs_in)276 STATIC mp_obj_t fat_vfs_getcwd(mp_obj_t vfs_in) {
277     mp_obj_fat_vfs_t *self = MP_OBJ_TO_PTR(vfs_in);
278     char buf[MICROPY_ALLOC_PATH_MAX + 1];
279     FRESULT res = f_getcwd(&self->fatfs, buf, sizeof(buf));
280     if (res != FR_OK) {
281         mp_raise_OSError(fresult_to_errno_table[res]);
282     }
283     return mp_obj_new_str(buf, strlen(buf));
284 }
285 STATIC MP_DEFINE_CONST_FUN_OBJ_1(fat_vfs_getcwd_obj, fat_vfs_getcwd);
286 
287 // Get the status of a file or directory.
fat_vfs_stat(mp_obj_t vfs_in,mp_obj_t path_in)288 STATIC mp_obj_t fat_vfs_stat(mp_obj_t vfs_in, mp_obj_t path_in) {
289     mp_obj_fat_vfs_t *self = MP_OBJ_TO_PTR(vfs_in);
290     const char *path = mp_obj_str_get_str(path_in);
291 
292     FILINFO fno;
293     if (path[0] == 0 || (path[0] == '/' && path[1] == 0)) {
294         // stat root directory
295         fno.fsize = 0;
296         fno.fdate = 0x2821; // Jan 1, 2000
297         fno.ftime = 0;
298         fno.fattrib = AM_DIR;
299     } else {
300         FRESULT res = f_stat(&self->fatfs, path, &fno);
301         if (res != FR_OK) {
302             mp_raise_OSError(fresult_to_errno_table[res]);
303         }
304     }
305 
306     mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(10, NULL));
307     mp_int_t mode = 0;
308     if (fno.fattrib & AM_DIR) {
309         mode |= MP_S_IFDIR;
310     } else {
311         mode |= MP_S_IFREG;
312     }
313     mp_int_t seconds = timeutils_seconds_since_epoch(
314         1980 + ((fno.fdate >> 9) & 0x7f),
315         (fno.fdate >> 5) & 0x0f,
316         fno.fdate & 0x1f,
317         (fno.ftime >> 11) & 0x1f,
318         (fno.ftime >> 5) & 0x3f,
319         2 * (fno.ftime & 0x1f)
320         );
321     t->items[0] = MP_OBJ_NEW_SMALL_INT(mode); // st_mode
322     t->items[1] = MP_OBJ_NEW_SMALL_INT(0); // st_ino
323     t->items[2] = MP_OBJ_NEW_SMALL_INT(0); // st_dev
324     t->items[3] = MP_OBJ_NEW_SMALL_INT(0); // st_nlink
325     t->items[4] = MP_OBJ_NEW_SMALL_INT(0); // st_uid
326     t->items[5] = MP_OBJ_NEW_SMALL_INT(0); // st_gid
327     t->items[6] = mp_obj_new_int_from_uint(fno.fsize); // st_size
328     t->items[7] = mp_obj_new_int_from_uint(seconds); // st_atime
329     t->items[8] = mp_obj_new_int_from_uint(seconds); // st_mtime
330     t->items[9] = mp_obj_new_int_from_uint(seconds); // st_ctime
331 
332     return MP_OBJ_FROM_PTR(t);
333 }
334 STATIC MP_DEFINE_CONST_FUN_OBJ_2(fat_vfs_stat_obj, fat_vfs_stat);
335 
336 // Get the status of a VFS.
fat_vfs_statvfs(mp_obj_t vfs_in,mp_obj_t path_in)337 STATIC mp_obj_t fat_vfs_statvfs(mp_obj_t vfs_in, mp_obj_t path_in) {
338     mp_obj_fat_vfs_t *self = MP_OBJ_TO_PTR(vfs_in);
339     (void)path_in;
340 
341     DWORD nclst;
342     FATFS *fatfs = &self->fatfs;
343     FRESULT res = f_getfree(fatfs, &nclst);
344     if (FR_OK != res) {
345         mp_raise_OSError(fresult_to_errno_table[res]);
346     }
347 
348     mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(10, NULL));
349 
350     t->items[0] = MP_OBJ_NEW_SMALL_INT(fatfs->csize * SECSIZE(fatfs)); // f_bsize
351     t->items[1] = t->items[0]; // f_frsize
352     t->items[2] = MP_OBJ_NEW_SMALL_INT((fatfs->n_fatent - 2)); // f_blocks
353     t->items[3] = MP_OBJ_NEW_SMALL_INT(nclst); // f_bfree
354     t->items[4] = t->items[3]; // f_bavail
355     t->items[5] = MP_OBJ_NEW_SMALL_INT(0); // f_files
356     t->items[6] = MP_OBJ_NEW_SMALL_INT(0); // f_ffree
357     t->items[7] = MP_OBJ_NEW_SMALL_INT(0); // f_favail
358     t->items[8] = MP_OBJ_NEW_SMALL_INT(0); // f_flags
359     t->items[9] = MP_OBJ_NEW_SMALL_INT(FF_MAX_LFN); // f_namemax
360 
361     return MP_OBJ_FROM_PTR(t);
362 }
363 STATIC MP_DEFINE_CONST_FUN_OBJ_2(fat_vfs_statvfs_obj, fat_vfs_statvfs);
364 
vfs_fat_mount(mp_obj_t self_in,mp_obj_t readonly,mp_obj_t mkfs)365 STATIC mp_obj_t vfs_fat_mount(mp_obj_t self_in, mp_obj_t readonly, mp_obj_t mkfs) {
366     fs_user_mount_t *self = MP_OBJ_TO_PTR(self_in);
367 
368     // Read-only device indicated by writeblocks[0] == MP_OBJ_NULL.
369     // User can specify read-only device by:
370     //  1. readonly=True keyword argument
371     //  2. nonexistent writeblocks method (then writeblocks[0] == MP_OBJ_NULL already)
372     if (mp_obj_is_true(readonly)) {
373         self->blockdev.writeblocks[0] = MP_OBJ_NULL;
374     }
375 
376     // check if we need to make the filesystem
377     FRESULT res = (self->blockdev.flags & MP_BLOCKDEV_FLAG_NO_FILESYSTEM) ? FR_NO_FILESYSTEM : FR_OK;
378     if (res == FR_NO_FILESYSTEM && mp_obj_is_true(mkfs)) {
379         uint8_t working_buf[FF_MAX_SS];
380         res = f_mkfs(&self->fatfs, FM_FAT | FM_SFD, 0, working_buf, sizeof(working_buf));
381     }
382     if (res != FR_OK) {
383         mp_raise_OSError(fresult_to_errno_table[res]);
384     }
385     self->blockdev.flags &= ~MP_BLOCKDEV_FLAG_NO_FILESYSTEM;
386 
387     return mp_const_none;
388 }
389 STATIC MP_DEFINE_CONST_FUN_OBJ_3(vfs_fat_mount_obj, vfs_fat_mount);
390 
vfs_fat_umount(mp_obj_t self_in)391 STATIC mp_obj_t vfs_fat_umount(mp_obj_t self_in) {
392     (void)self_in;
393     // keep the FAT filesystem mounted internally so the VFS methods can still be used
394     return mp_const_none;
395 }
396 STATIC MP_DEFINE_CONST_FUN_OBJ_1(fat_vfs_umount_obj, vfs_fat_umount);
397 
398 STATIC const mp_rom_map_elem_t fat_vfs_locals_dict_table[] = {
399     #if _FS_REENTRANT
400     { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&fat_vfs_del_obj) },
401     #endif
402     { MP_ROM_QSTR(MP_QSTR_mkfs), MP_ROM_PTR(&fat_vfs_mkfs_obj) },
403     { MP_ROM_QSTR(MP_QSTR_open), MP_ROM_PTR(&fat_vfs_open_obj) },
404     { MP_ROM_QSTR(MP_QSTR_ilistdir), MP_ROM_PTR(&fat_vfs_ilistdir_obj) },
405     { MP_ROM_QSTR(MP_QSTR_mkdir), MP_ROM_PTR(&fat_vfs_mkdir_obj) },
406     { MP_ROM_QSTR(MP_QSTR_rmdir), MP_ROM_PTR(&fat_vfs_rmdir_obj) },
407     { MP_ROM_QSTR(MP_QSTR_chdir), MP_ROM_PTR(&fat_vfs_chdir_obj) },
408     { MP_ROM_QSTR(MP_QSTR_getcwd), MP_ROM_PTR(&fat_vfs_getcwd_obj) },
409     { MP_ROM_QSTR(MP_QSTR_remove), MP_ROM_PTR(&fat_vfs_remove_obj) },
410     { MP_ROM_QSTR(MP_QSTR_rename), MP_ROM_PTR(&fat_vfs_rename_obj) },
411     { MP_ROM_QSTR(MP_QSTR_stat), MP_ROM_PTR(&fat_vfs_stat_obj) },
412     { MP_ROM_QSTR(MP_QSTR_statvfs), MP_ROM_PTR(&fat_vfs_statvfs_obj) },
413     { MP_ROM_QSTR(MP_QSTR_mount), MP_ROM_PTR(&vfs_fat_mount_obj) },
414     { MP_ROM_QSTR(MP_QSTR_umount), MP_ROM_PTR(&fat_vfs_umount_obj) },
415 };
416 STATIC MP_DEFINE_CONST_DICT(fat_vfs_locals_dict, fat_vfs_locals_dict_table);
417 
418 STATIC const mp_vfs_proto_t fat_vfs_proto = {
419     .import_stat = fat_vfs_import_stat,
420 };
421 
422 const mp_obj_type_t mp_fat_vfs_type = {
423     { &mp_type_type },
424     .name = MP_QSTR_VfsFat,
425     .make_new = fat_vfs_make_new,
426     .protocol = &fat_vfs_proto,
427     .locals_dict = (mp_obj_dict_t *)&fat_vfs_locals_dict,
428 
429 };
430 
431 #endif // MICROPY_VFS_FAT
432