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 "lib/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
50STATIC 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
65STATIC 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
91STATIC 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}
97STATIC MP_DEFINE_CONST_FUN_OBJ_1(fat_vfs_del_obj, fat_vfs_del);
98#endif
99
100STATIC 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}
116STATIC MP_DEFINE_CONST_FUN_OBJ_1(fat_vfs_mkfs_fun_obj, fat_vfs_mkfs);
117STATIC MP_DEFINE_CONST_STATICMETHOD_OBJ(fat_vfs_mkfs_obj, MP_ROM_PTR(&fat_vfs_mkfs_fun_obj));
118
119typedef 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
126STATIC 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
166STATIC 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}
191STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(fat_vfs_ilistdir_obj, 1, 2, fat_vfs_ilistdir_func);
192
193STATIC 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
217STATIC 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}
220STATIC MP_DEFINE_CONST_FUN_OBJ_2(fat_vfs_remove_obj, fat_vfs_remove);
221
222STATIC 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}
225STATIC MP_DEFINE_CONST_FUN_OBJ_2(fat_vfs_rmdir_obj, fat_vfs_rmdir);
226
227STATIC 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}
245STATIC MP_DEFINE_CONST_FUN_OBJ_3(fat_vfs_rename_obj, fat_vfs_rename);
246
247STATIC 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}
257STATIC MP_DEFINE_CONST_FUN_OBJ_2(fat_vfs_mkdir_obj, fat_vfs_mkdir);
258
259/// Change current directory.
260STATIC 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}
273STATIC MP_DEFINE_CONST_FUN_OBJ_2(fat_vfs_chdir_obj, fat_vfs_chdir);
274
275/// Get the current directory.
276STATIC 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}
285STATIC MP_DEFINE_CONST_FUN_OBJ_1(fat_vfs_getcwd_obj, fat_vfs_getcwd);
286
287/// \function stat(path)
288/// Get the status of a file or directory.
289STATIC mp_obj_t fat_vfs_stat(mp_obj_t vfs_in, mp_obj_t path_in) {
290 mp_obj_fat_vfs_t *self = MP_OBJ_TO_PTR(vfs_in);
291 const char *path = mp_obj_str_get_str(path_in);
292
293 FILINFO fno;
294 if (path[0] == 0 || (path[0] == '/' && path[1] == 0)) {
295 // stat root directory
296 fno.fsize = 0;
297 fno.fdate = 0x2821; // Jan 1, 2000
298 fno.ftime = 0;
299 fno.fattrib = AM_DIR;
300 } else {
301 FRESULT res = f_stat(&self->fatfs, path, &fno);
302 if (res != FR_OK) {
303 mp_raise_OSError(fresult_to_errno_table[res]);
304 }
305 }
306
307 mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(10, NULL));
308 mp_int_t mode = 0;
309 if (fno.fattrib & AM_DIR) {
310 mode |= MP_S_IFDIR;
311 } else {
312 mode |= MP_S_IFREG;
313 }
314 mp_int_t seconds = timeutils_seconds_since_epoch(
315 1980 + ((fno.fdate >> 9) & 0x7f),
316 (fno.fdate >> 5) & 0x0f,
317 fno.fdate & 0x1f,
318 (fno.ftime >> 11) & 0x1f,
319 (fno.ftime >> 5) & 0x3f,
320 2 * (fno.ftime & 0x1f)
321 );
322 t->items[0] = MP_OBJ_NEW_SMALL_INT(mode); // st_mode
323 t->items[1] = MP_OBJ_NEW_SMALL_INT(0); // st_ino
324 t->items[2] = MP_OBJ_NEW_SMALL_INT(0); // st_dev
325 t->items[3] = MP_OBJ_NEW_SMALL_INT(0); // st_nlink
326 t->items[4] = MP_OBJ_NEW_SMALL_INT(0); // st_uid
327 t->items[5] = MP_OBJ_NEW_SMALL_INT(0); // st_gid
328 t->items[6] = mp_obj_new_int_from_uint(fno.fsize); // st_size
329 t->items[7] = mp_obj_new_int_from_uint(seconds); // st_atime
330 t->items[8] = mp_obj_new_int_from_uint(seconds); // st_mtime
331 t->items[9] = mp_obj_new_int_from_uint(seconds); // st_ctime
332
333 return MP_OBJ_FROM_PTR(t);
334}
335STATIC MP_DEFINE_CONST_FUN_OBJ_2(fat_vfs_stat_obj, fat_vfs_stat);
336
337// Get the status of a VFS.
338STATIC mp_obj_t fat_vfs_statvfs(mp_obj_t vfs_in, mp_obj_t path_in) {
339 mp_obj_fat_vfs_t *self = MP_OBJ_TO_PTR(vfs_in);
340 (void)path_in;
341
342 DWORD nclst;
343 FATFS *fatfs = &self->fatfs;
344 FRESULT res = f_getfree(fatfs, &nclst);
345 if (FR_OK != res) {
346 mp_raise_OSError(fresult_to_errno_table[res]);
347 }
348
349 mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(10, NULL));
350
351 t->items[0] = MP_OBJ_NEW_SMALL_INT(fatfs->csize * SECSIZE(fatfs)); // f_bsize
352 t->items[1] = t->items[0]; // f_frsize
353 t->items[2] = MP_OBJ_NEW_SMALL_INT((fatfs->n_fatent - 2)); // f_blocks
354 t->items[3] = MP_OBJ_NEW_SMALL_INT(nclst); // f_bfree
355 t->items[4] = t->items[3]; // f_bavail
356 t->items[5] = MP_OBJ_NEW_SMALL_INT(0); // f_files
357 t->items[6] = MP_OBJ_NEW_SMALL_INT(0); // f_ffree
358 t->items[7] = MP_OBJ_NEW_SMALL_INT(0); // f_favail
359 t->items[8] = MP_OBJ_NEW_SMALL_INT(0); // f_flags
360 t->items[9] = MP_OBJ_NEW_SMALL_INT(FF_MAX_LFN); // f_namemax
361
362 return MP_OBJ_FROM_PTR(t);
363}
364STATIC MP_DEFINE_CONST_FUN_OBJ_2(fat_vfs_statvfs_obj, fat_vfs_statvfs);
365
366STATIC mp_obj_t vfs_fat_mount(mp_obj_t self_in, mp_obj_t readonly, mp_obj_t mkfs) {
367 fs_user_mount_t *self = MP_OBJ_TO_PTR(self_in);
368
369 // Read-only device indicated by writeblocks[0] == MP_OBJ_NULL.
370 // User can specify read-only device by:
371 // 1. readonly=True keyword argument
372 // 2. nonexistent writeblocks method (then writeblocks[0] == MP_OBJ_NULL already)
373 if (mp_obj_is_true(readonly)) {
374 self->blockdev.writeblocks[0] = MP_OBJ_NULL;
375 }
376
377 // check if we need to make the filesystem
378 FRESULT res = (self->blockdev.flags & MP_BLOCKDEV_FLAG_NO_FILESYSTEM) ? FR_NO_FILESYSTEM : FR_OK;
379 if (res == FR_NO_FILESYSTEM && mp_obj_is_true(mkfs)) {
380 uint8_t working_buf[FF_MAX_SS];
381 res = f_mkfs(&self->fatfs, FM_FAT | FM_SFD, 0, working_buf, sizeof(working_buf));
382 }
383 if (res != FR_OK) {
384 mp_raise_OSError(fresult_to_errno_table[res]);
385 }
386 self->blockdev.flags &= ~MP_BLOCKDEV_FLAG_NO_FILESYSTEM;
387
388 return mp_const_none;
389}
390STATIC MP_DEFINE_CONST_FUN_OBJ_3(vfs_fat_mount_obj, vfs_fat_mount);
391
392STATIC mp_obj_t vfs_fat_umount(mp_obj_t self_in) {
393 (void)self_in;
394 // keep the FAT filesystem mounted internally so the VFS methods can still be used
395 return mp_const_none;
396}
397STATIC MP_DEFINE_CONST_FUN_OBJ_1(fat_vfs_umount_obj, vfs_fat_umount);
398
399STATIC const mp_rom_map_elem_t fat_vfs_locals_dict_table[] = {
400 #if _FS_REENTRANT
401 { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&fat_vfs_del_obj) },
402 #endif
403 { MP_ROM_QSTR(MP_QSTR_mkfs), MP_ROM_PTR(&fat_vfs_mkfs_obj) },
404 { MP_ROM_QSTR(MP_QSTR_open), MP_ROM_PTR(&fat_vfs_open_obj) },
405 { MP_ROM_QSTR(MP_QSTR_ilistdir), MP_ROM_PTR(&fat_vfs_ilistdir_obj) },
406 { MP_ROM_QSTR(MP_QSTR_mkdir), MP_ROM_PTR(&fat_vfs_mkdir_obj) },
407 { MP_ROM_QSTR(MP_QSTR_rmdir), MP_ROM_PTR(&fat_vfs_rmdir_obj) },
408 { MP_ROM_QSTR(MP_QSTR_chdir), MP_ROM_PTR(&fat_vfs_chdir_obj) },
409 { MP_ROM_QSTR(MP_QSTR_getcwd), MP_ROM_PTR(&fat_vfs_getcwd_obj) },
410 { MP_ROM_QSTR(MP_QSTR_remove), MP_ROM_PTR(&fat_vfs_remove_obj) },
411 { MP_ROM_QSTR(MP_QSTR_rename), MP_ROM_PTR(&fat_vfs_rename_obj) },
412 { MP_ROM_QSTR(MP_QSTR_stat), MP_ROM_PTR(&fat_vfs_stat_obj) },
413 { MP_ROM_QSTR(MP_QSTR_statvfs), MP_ROM_PTR(&fat_vfs_statvfs_obj) },
414 { MP_ROM_QSTR(MP_QSTR_mount), MP_ROM_PTR(&vfs_fat_mount_obj) },
415 { MP_ROM_QSTR(MP_QSTR_umount), MP_ROM_PTR(&fat_vfs_umount_obj) },
416};
417STATIC MP_DEFINE_CONST_DICT(fat_vfs_locals_dict, fat_vfs_locals_dict_table);
418
419STATIC const mp_vfs_proto_t fat_vfs_proto = {
420 .import_stat = fat_vfs_import_stat,
421};
422
423const mp_obj_type_t mp_fat_vfs_type = {
424 { &mp_type_type },
425 .name = MP_QSTR_VfsFat,
426 .make_new = fat_vfs_make_new,
427 .protocol = &fat_vfs_proto,
428 .locals_dict = (mp_obj_dict_t *)&fat_vfs_locals_dict,
429
430};
431
432#endif // MICROPY_VFS_FAT
433