entry.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. # SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD
  2. # SPDX-License-Identifier: Apache-2.0
  3. from typing import List, Optional, Union
  4. from construct import Const, Int8ul, Int16ul, Int32ul, PaddedString, Struct
  5. from .exceptions import LowerCaseException, TooLongNameException
  6. from .fatfs_state import FATFSState
  7. from .utils import (DATETIME, EMPTY_BYTE, FATFS_INCEPTION, MAX_EXT_SIZE, MAX_NAME_SIZE, SHORT_NAMES_ENCODING,
  8. FATDefaults, build_date_entry, build_time_entry, is_valid_fatfs_name, pad_string)
  9. class Entry:
  10. """
  11. The class Entry represents entry of the directory.
  12. """
  13. ATTR_READ_ONLY: int = 0x01
  14. ATTR_HIDDEN: int = 0x02
  15. ATTR_SYSTEM: int = 0x04
  16. ATTR_VOLUME_ID: int = 0x08
  17. ATTR_DIRECTORY: int = 0x10 # directory
  18. ATTR_ARCHIVE: int = 0x20 # file
  19. ATTR_LONG_NAME: int = ATTR_READ_ONLY | ATTR_HIDDEN | ATTR_SYSTEM | ATTR_VOLUME_ID
  20. # indexes in the entry structure and sizes in bytes, not in characters (encoded using 2 bytes for lfn)
  21. LDIR_Name1_IDX: int = 1
  22. LDIR_Name1_SIZE: int = 5
  23. LDIR_Name2_IDX: int = 14
  24. LDIR_Name2_SIZE: int = 6
  25. LDIR_Name3_IDX: int = 28
  26. LDIR_Name3_SIZE: int = 2
  27. # short entry in long file names
  28. LDIR_DIR_NTRES: int = 0x18
  29. # one entry can hold 13 characters with size 2 bytes distributed in three regions of the 32 bytes entry
  30. CHARS_PER_ENTRY: int = LDIR_Name1_SIZE + LDIR_Name2_SIZE + LDIR_Name3_SIZE
  31. # the last 16 bytes record in the LFN entry has first byte masked with the following value
  32. LAST_RECORD_LFN_ENTRY: int = 0x40
  33. SHORT_ENTRY: int = -1
  34. # this value is used for short-like entry but with accepted lower case
  35. SHORT_ENTRY_LN: int = 0
  36. # The 1st January 1980 00:00:00
  37. DEFAULT_DATE: DATETIME = (FATFS_INCEPTION.year, FATFS_INCEPTION.month, FATFS_INCEPTION.day)
  38. DEFAULT_TIME: DATETIME = (FATFS_INCEPTION.hour, FATFS_INCEPTION.minute, FATFS_INCEPTION.second)
  39. ENTRY_FORMAT_SHORT_NAME = Struct(
  40. 'DIR_Name' / PaddedString(MAX_NAME_SIZE, SHORT_NAMES_ENCODING),
  41. 'DIR_Name_ext' / PaddedString(MAX_EXT_SIZE, SHORT_NAMES_ENCODING),
  42. 'DIR_Attr' / Int8ul,
  43. 'DIR_NTRes' / Int8ul, # this tagged for lfn (0x00 for short entry in lfn, 0x18 for short name)
  44. 'DIR_CrtTimeTenth' / Const(EMPTY_BYTE), # ignored by esp-idf fatfs library
  45. 'DIR_CrtTime' / Int16ul, # ignored by esp-idf fatfs library
  46. 'DIR_CrtDate' / Int16ul, # ignored by esp-idf fatfs library
  47. 'DIR_LstAccDate' / Int16ul, # must be same as DIR_WrtDate
  48. 'DIR_FstClusHI' / Const(2 * EMPTY_BYTE),
  49. 'DIR_WrtTime' / Int16ul,
  50. 'DIR_WrtDate' / Int16ul,
  51. 'DIR_FstClusLO' / Int16ul,
  52. 'DIR_FileSize' / Int32ul,
  53. )
  54. def __init__(self,
  55. entry_id: int,
  56. parent_dir_entries_address: int,
  57. fatfs_state: FATFSState) -> None:
  58. self.fatfs_state: FATFSState = fatfs_state
  59. self.id: int = entry_id
  60. self.entry_address: int = parent_dir_entries_address + self.id * FATDefaults.ENTRY_SIZE
  61. self._is_alias: bool = False
  62. self._is_empty: bool = True
  63. @staticmethod
  64. def get_cluster_id(obj_: dict) -> int:
  65. cluster_id_: int = obj_['DIR_FstClusLO']
  66. return cluster_id_
  67. @property
  68. def is_empty(self) -> bool:
  69. return self._is_empty
  70. @staticmethod
  71. def _parse_entry(entry_bytearray: Union[bytearray, bytes]) -> dict:
  72. entry_: dict = Entry.ENTRY_FORMAT_SHORT_NAME.parse(entry_bytearray)
  73. return entry_
  74. @staticmethod
  75. def _build_entry(**kwargs) -> bytes: # type: ignore
  76. entry_: bytes = Entry.ENTRY_FORMAT_SHORT_NAME.build(dict(**kwargs))
  77. return entry_
  78. @staticmethod
  79. def _build_entry_long(names: List[bytes], checksum: int, order: int, is_last: bool) -> bytes:
  80. """
  81. Long entry starts with 1 bytes of the order, if the entry is the last in the chain it is or-masked with 0x40,
  82. otherwise is without change (or masked with 0x00). The following example shows 3 entries:
  83. first two (0x2000-0x2040) are long in the reverse order and the last one (0x2040-0x2060) is short.
  84. The entries define file name "thisisverylongfilenama.txt".
  85. 00002000: 42 67 00 66 00 69 00 6C 00 65 00 0F 00 43 6E 00 Bg.f.i.l.e...Cn.
  86. 00002010: 61 00 6D 00 61 00 2E 00 74 00 00 00 78 00 74 00 a.m.a...t...x.t.
  87. 00002020: 01 74 00 68 00 69 00 73 00 69 00 0F 00 43 73 00 .t.h.i.s.i...Cs.
  88. 00002030: 76 00 65 00 72 00 79 00 6C 00 00 00 6F 00 6E 00 v.e.r.y.l...o.n.
  89. 00002040: 54 48 49 53 49 53 7E 31 54 58 54 20 00 00 00 00 THISIS~1TXT.....
  90. 00002050: 21 00 00 00 00 00 00 00 21 00 02 00 15 00 00 00 !.......!.......
  91. """
  92. order |= (Entry.LAST_RECORD_LFN_ENTRY if is_last else 0x00)
  93. long_entry: bytes = (Int8ul.build(order) + # order of the long name entry (possibly masked with 0x40)
  94. names[0] + # first 5 characters (10 bytes) of the name part
  95. Int8ul.build(Entry.ATTR_LONG_NAME) + # one byte entity type ATTR_LONG_NAME
  96. Int8ul.build(0) + # one byte of zeros
  97. Int8ul.build(checksum) + # lfn_checksum defined in utils.py
  98. names[1] + # next 6 characters (12 bytes) of the name part
  99. Int16ul.build(0) + # 2 bytes of zeros
  100. names[2]) # last 2 characters (4 bytes) of the name part
  101. return long_entry
  102. @staticmethod
  103. def parse_entry_long(entry_bytes_: bytes, my_check: int) -> dict:
  104. order_ = Int8ul.parse(entry_bytes_[0:1])
  105. names0 = entry_bytes_[1:11]
  106. if Int8ul.parse(entry_bytes_[12:13]) != 0 or Int16ul.parse(entry_bytes_[26:28]) != 0 or Int8ul.parse(entry_bytes_[11:12]) != 15:
  107. return {}
  108. if Int8ul.parse(entry_bytes_[13:14]) != my_check:
  109. return {}
  110. names1 = entry_bytes_[14:26]
  111. names2 = entry_bytes_[28:32]
  112. return {
  113. 'order': order_,
  114. 'name1': names0,
  115. 'name2': names1,
  116. 'name3': names2,
  117. 'is_last': bool(order_ & Entry.LAST_RECORD_LFN_ENTRY == Entry.LAST_RECORD_LFN_ENTRY)
  118. }
  119. @property
  120. def entry_bytes(self) -> bytes:
  121. """
  122. :returns: Bytes defining the entry belonging to the given instance.
  123. """
  124. start_: int = self.entry_address
  125. entry_: bytes = self.fatfs_state.binary_image[start_: start_ + FATDefaults.ENTRY_SIZE]
  126. return entry_
  127. @entry_bytes.setter
  128. def entry_bytes(self, value: bytes) -> None:
  129. """
  130. :param value: new content of the entry
  131. :returns: None
  132. The setter sets the content of the entry in bytes.
  133. """
  134. self.fatfs_state.binary_image[self.entry_address: self.entry_address + FATDefaults.ENTRY_SIZE] = value
  135. def _clean_entry(self) -> None:
  136. self.entry_bytes: bytes = FATDefaults.ENTRY_SIZE * EMPTY_BYTE
  137. def allocate_entry(self,
  138. first_cluster_id: int,
  139. entity_name: str,
  140. entity_type: int,
  141. entity_extension: str = '',
  142. size: int = 0,
  143. date: DATETIME = DEFAULT_DATE,
  144. time: DATETIME = DEFAULT_TIME,
  145. lfn_order: int = SHORT_ENTRY,
  146. lfn_names: Optional[List[bytes]] = None,
  147. lfn_checksum_: int = 0,
  148. fits_short: bool = False,
  149. lfn_is_last: bool = False) -> None:
  150. """
  151. :param first_cluster_id: id of the first data cluster for given entry
  152. :param entity_name: name recorded in the entry
  153. :param entity_extension: extension recorded in the entry
  154. :param size: size of the content of the file
  155. :param date: denotes year (actual year minus 1980), month number day of the month (minimal valid is (0, 1, 1))
  156. :param time: denotes hour, minute and second with granularity 2 seconds (sec // 2)
  157. :param entity_type: type of the entity (file [0x20] or directory [0x10])
  158. :param lfn_order: if long names support is enabled, defines order in long names entries sequence (-1 for short)
  159. :param lfn_names: if the entry is dedicated for long names the lfn_names contains
  160. LDIR_Name1, LDIR_Name2 and LDIR_Name3 in this order
  161. :param lfn_checksum_: use only for long file names, checksum calculated lfn_checksum function
  162. :param fits_short: determines if the name fits in 8.3 filename
  163. :param lfn_is_last: determines if the long file name entry is holds last part of the name,
  164. thus its address is first in the physical order
  165. :returns: None
  166. :raises LowerCaseException: In case when long_names_enabled is set to False and filename exceeds 8 chars
  167. for name or 3 chars for extension the exception is raised
  168. :raises TooLongNameException: When long_names_enabled is set to False and name doesn't fit to 8.3 filename
  169. an exception is raised
  170. """
  171. valid_full_name: bool = is_valid_fatfs_name(entity_name) and is_valid_fatfs_name(entity_extension)
  172. if not (valid_full_name or lfn_order >= 0):
  173. raise LowerCaseException('Lower case is not supported in short name entry, use upper case.')
  174. if self.fatfs_state.use_default_datetime:
  175. date = self.DEFAULT_DATE
  176. time = self.DEFAULT_TIME
  177. # clean entry before allocation
  178. self._clean_entry()
  179. self._is_empty = False
  180. object_name = entity_name.upper() if not self.fatfs_state.long_names_enabled else entity_name
  181. object_extension = entity_extension.upper() if not self.fatfs_state.long_names_enabled else entity_extension
  182. exceeds_short_name: bool = len(object_name) > MAX_NAME_SIZE or len(object_extension) > MAX_EXT_SIZE
  183. if not self.fatfs_state.long_names_enabled and exceeds_short_name:
  184. raise TooLongNameException(
  185. 'Maximal length of the object name is {} characters and {} characters for extension!'.format(
  186. MAX_NAME_SIZE, MAX_EXT_SIZE
  187. )
  188. )
  189. start_address = self.entry_address
  190. end_address = start_address + FATDefaults.ENTRY_SIZE
  191. if lfn_order in (self.SHORT_ENTRY, self.SHORT_ENTRY_LN):
  192. date_entry_: int = build_date_entry(*date)
  193. time_entry: int = build_time_entry(*time)
  194. self.fatfs_state.binary_image[start_address: end_address] = self._build_entry(
  195. DIR_Name=pad_string(object_name, size=MAX_NAME_SIZE),
  196. DIR_Name_ext=pad_string(object_extension, size=MAX_EXT_SIZE),
  197. DIR_Attr=entity_type,
  198. DIR_NTRes=0x00 if (not self.fatfs_state.long_names_enabled) or (not fits_short) else 0x18,
  199. DIR_FstClusLO=first_cluster_id,
  200. DIR_FileSize=size,
  201. DIR_CrtDate=date_entry_, # ignored by esp-idf fatfs library
  202. DIR_LstAccDate=date_entry_, # must be same as DIR_WrtDate
  203. DIR_WrtDate=date_entry_,
  204. DIR_CrtTime=time_entry, # ignored by esp-idf fatfs library
  205. DIR_WrtTime=time_entry
  206. )
  207. else:
  208. assert lfn_names is not None
  209. self.fatfs_state.binary_image[start_address: end_address] = self._build_entry_long(lfn_names,
  210. lfn_checksum_,
  211. lfn_order,
  212. lfn_is_last)
  213. def update_content_size(self, content_size: int) -> None:
  214. """
  215. :param content_size: the new size of the file content in bytes
  216. :returns: None
  217. This method parses the binary entry to the construct structure, updates the content size of the file
  218. and builds new binary entry.
  219. """
  220. parsed_entry = self._parse_entry(self.entry_bytes)
  221. parsed_entry.DIR_FileSize = content_size # type: ignore
  222. self.entry_bytes = Entry.ENTRY_FORMAT_SHORT_NAME.build(parsed_entry)