Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pypdf/generic/_files.py: 27%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

271 statements  

1from __future__ import annotations 

2 

3import bisect 

4from functools import cached_property 

5from typing import TYPE_CHECKING, cast 

6 

7from pypdf._configuration import get_configuration 

8from pypdf._utils import format_iso8824_date, logger_warning, parse_iso8824_date 

9from pypdf.constants import AFRelationship, CatalogAttributes, FileSpecificationDictionaryEntries, PageAttributes 

10from pypdf.errors import LimitReachedError, PdfReadError, PyPdfError 

11from pypdf.generic import ( 

12 ArrayObject, 

13 ByteStringObject, 

14 DecodedStreamObject, 

15 DictionaryObject, 

16 NameObject, 

17 NullObject, 

18 NumberObject, 

19 StreamObject, 

20 TextStringObject, 

21 is_null_or_none, 

22) 

23from pypdf.generic._data_structures import _flatten_name_tree, _iter_name_tree 

24 

25if TYPE_CHECKING: 

26 import datetime 

27 from collections.abc import Iterator 

28 

29 from pypdf._utils import _TraversalState 

30 from pypdf._writer import PdfWriter 

31 

32 

33class EmbeddedFile: 

34 """ 

35 Container holding the information on an embedded file. 

36 

37 Attributes are evaluated lazily if possible. 

38 

39 Further information on embedded files can be found in section 7.11 of the PDF 2.0 specification. 

40 """ 

41 def __init__(self, name: str, pdf_object: DictionaryObject, parent: ArrayObject | None = None) -> None: 

42 """ 

43 Args: 

44 name: The (primary) name as provided in the name tree. 

45 pdf_object: The corresponding PDF object to allow retrieving further data. 

46 parent: The parent list. 

47 """ 

48 self._name = name 

49 self.pdf_object = pdf_object 

50 self._parent = parent 

51 

52 @property 

53 def name(self) -> str: 

54 """ 

55 The (primary) name of the embedded file as provided in the name tree. 

56 

57 .. warning:: 

58 

59 This value can contain arbitrary characters. Please make sure to sanitize it before 

60 using it to write the file content to the disk for example. 

61 """ 

62 return self._name 

63 

64 @classmethod 

65 def _create_new(cls, writer: PdfWriter, name: str, content: str | bytes) -> EmbeddedFile: 

66 """ 

67 Create a new embedded file and add it to the PdfWriter. 

68 

69 Args: 

70 writer: The PdfWriter instance to add the embedded file to. 

71 name: The filename to display. 

72 content: The data in the file. 

73 

74 Returns: 

75 EmbeddedFile instance for the newly created embedded file. 

76 """ 

77 # Convert string content to bytes if needed 

78 if isinstance(content, str): 

79 content = content.encode("latin-1") 

80 

81 # Create the file entry (the actual embedded file stream) 

82 file_entry = DecodedStreamObject() 

83 file_entry.set_data(content) 

84 file_entry.update({NameObject(PageAttributes.TYPE): NameObject("/EmbeddedFile")}) 

85 

86 # Create the /EF entry 

87 ef_entry = DictionaryObject() 

88 ef_entry.update({NameObject(FileSpecificationDictionaryEntries.F): writer._add_object(file_entry)}) 

89 

90 # Create the filespec dictionary 

91 from pypdf.generic import create_string_object # noqa: PLC0415 

92 filespec = DictionaryObject() 

93 filespec_reference = writer._add_object(filespec) 

94 name_object = cast(TextStringObject, create_string_object(name)) 

95 filespec.update( 

96 { 

97 NameObject(PageAttributes.TYPE): NameObject("/Filespec"), 

98 NameObject(FileSpecificationDictionaryEntries.F): name_object, 

99 NameObject(FileSpecificationDictionaryEntries.EF): ef_entry, 

100 } 

101 ) 

102 

103 # Add the name and filespec to the names array. 

104 # We use the inverse order for insertion, as this allows us to re-use the 

105 # same index. 

106 names_array = cls._get_names_array(writer) 

107 insertion_index = cls._get_insertion_index(names_array, name_object) 

108 names_array.insert(insertion_index, filespec_reference) 

109 names_array.insert(insertion_index, name_object) 

110 

111 # Return an EmbeddedFile instance 

112 return cls(name=name, pdf_object=filespec, parent=names_array) 

113 

114 @classmethod 

115 def _get_names_array(cls, writer: PdfWriter) -> ArrayObject: 

116 """Get the names array for embedded files, possibly creating and flattening it.""" 

117 if CatalogAttributes.NAMES not in writer.root_object: 

118 # Add the /Names entry to the catalog. 

119 writer.root_object[NameObject(CatalogAttributes.NAMES)] = writer._add_object(DictionaryObject()) 

120 

121 names_dict = cast(DictionaryObject, writer.root_object[CatalogAttributes.NAMES]) 

122 if "/EmbeddedFiles" not in names_dict: 

123 # We do not yet have an entry for embedded files. Create and return it. 

124 names = ArrayObject() 

125 embedded_files_names_dictionary = DictionaryObject( 

126 {NameObject(CatalogAttributes.NAMES): names} 

127 ) 

128 names_dict[NameObject("/EmbeddedFiles")] = writer._add_object(embedded_files_names_dictionary) 

129 return names 

130 

131 # We have an existing embedded files entry. 

132 configuration = get_configuration() 

133 embedded_files_names_tree = cast(DictionaryObject, names_dict["/EmbeddedFiles"]) 

134 if "/Names" in embedded_files_names_tree: 

135 # Simple case: We already have a flat list. 

136 names_tree = cast(ArrayObject, embedded_files_names_tree[NameObject(CatalogAttributes.NAMES)]) 

137 if len(names_tree) // 2 > configuration.embedded_files_maximum_count: 

138 raise LimitReachedError("Maximum embedded file entry limit reached.") 

139 return names_tree 

140 if "/Kids" not in embedded_files_names_tree: 

141 # Invalid case: This is no name tree. 

142 raise PdfReadError("Got neither Names nor Kids in embedded files tree.") 

143 

144 return _flatten_name_tree( 

145 embedded_files_names_tree, 

146 maximum_entries=configuration.embedded_files_maximum_count 

147 ) 

148 

149 @classmethod 

150 def _get_insertion_index(cls, names_array: ArrayObject, name: str) -> int: 

151 keys = [names_array[i].encode("utf-8") for i in range(0, len(names_array), 2)] 

152 name_bytes = name.encode("utf-8") 

153 

154 start = bisect.bisect_left(keys, name_bytes) 

155 end = bisect.bisect_right(keys, name_bytes) 

156 

157 if start != end: 

158 return end * 2 

159 if start == 0: 

160 return 0 

161 if start == (key_count := len(keys)): 

162 return key_count * 2 

163 return end * 2 

164 

165 @property 

166 def alternative_name(self) -> str | None: 

167 """ 

168 Retrieve the alternative name (as per the file specification dictionary). 

169 

170 .. warning:: 

171 

172 This value can contain arbitrary characters. Please make sure to sanitize it before 

173 using it to write the file content to the disk for example. 

174 """ 

175 for key in [FileSpecificationDictionaryEntries.UF, FileSpecificationDictionaryEntries.F]: 

176 # PDF 2.0 reference, table 43: 

177 # > A PDF reader shall use the value of the UF key, when present, instead of the F key. 

178 if key in self.pdf_object: 

179 value = self.pdf_object[key].get_object() 

180 if not is_null_or_none(value): 

181 return cast(str, value) 

182 return None 

183 

184 @alternative_name.setter 

185 def alternative_name(self, value: TextStringObject | None) -> None: 

186 """Set the alternative name (as per the file specification dictionary).""" 

187 if value is None: 

188 if FileSpecificationDictionaryEntries.UF in self.pdf_object: 

189 self.pdf_object[NameObject(FileSpecificationDictionaryEntries.UF)] = NullObject() 

190 if FileSpecificationDictionaryEntries.F in self.pdf_object: 

191 self.pdf_object[NameObject(FileSpecificationDictionaryEntries.F)] = NullObject() 

192 else: 

193 self.pdf_object[NameObject(FileSpecificationDictionaryEntries.UF)] = value 

194 self.pdf_object[NameObject(FileSpecificationDictionaryEntries.F)] = value 

195 

196 @property 

197 def description(self) -> str | None: 

198 """Retrieve the description.""" 

199 value = self.pdf_object.get(FileSpecificationDictionaryEntries.DESC) 

200 if is_null_or_none(value): 

201 return None 

202 return value 

203 

204 @description.setter 

205 def description(self, value: TextStringObject | None) -> None: 

206 """Set the description.""" 

207 if value is None: 

208 self.pdf_object[NameObject(FileSpecificationDictionaryEntries.DESC)] = NullObject() 

209 else: 

210 self.pdf_object[NameObject(FileSpecificationDictionaryEntries.DESC)] = value 

211 

212 @property 

213 def associated_file_relationship(self) -> str: 

214 """Retrieve the relationship of the referring document to this embedded file.""" 

215 return cast( 

216 NameObject, 

217 self.pdf_object.get("/AFRelationship", NameObject(AFRelationship.UNSPECIFIED)), 

218 ) 

219 

220 @associated_file_relationship.setter 

221 def associated_file_relationship(self, value: NameObject) -> None: 

222 """Set the relationship of the referring document to this embedded file.""" 

223 self.pdf_object[NameObject("/AFRelationship")] = value 

224 

225 @property 

226 def _embedded_file(self) -> StreamObject: 

227 """Retrieve the actual embedded file stream.""" 

228 if FileSpecificationDictionaryEntries.EF not in self.pdf_object: 

229 raise PdfReadError(f"/EF entry not found: {self.pdf_object}") 

230 ef = cast(DictionaryObject, self.pdf_object[FileSpecificationDictionaryEntries.EF]) 

231 for key in [FileSpecificationDictionaryEntries.UF, FileSpecificationDictionaryEntries.F]: 

232 if key in ef: 

233 return cast(StreamObject, ef[key].get_object()) 

234 raise PdfReadError(f"No /(U)F key found in file dictionary: {ef}") 

235 

236 @property 

237 def _params(self) -> DictionaryObject: 

238 """Retrieve the file-specific parameters.""" 

239 return cast(DictionaryObject, self._embedded_file.get("/Params", DictionaryObject()).get_object()) 

240 

241 @cached_property 

242 def _ensure_params(self) -> DictionaryObject: 

243 """Ensure the /Params dictionary exists and return it.""" 

244 embedded_file = self._embedded_file 

245 if "/Params" not in embedded_file: 

246 embedded_file[NameObject("/Params")] = DictionaryObject() 

247 return cast(DictionaryObject, embedded_file["/Params"]) 

248 

249 @property 

250 def subtype(self) -> str | None: 

251 """Retrieve the subtype. This is a MIME media type, prefixed by a slash.""" 

252 value = self._embedded_file.get("/Subtype") 

253 if is_null_or_none(value): 

254 return None 

255 return value 

256 

257 @subtype.setter 

258 def subtype(self, value: NameObject | None) -> None: 

259 """Set the subtype. This should be a MIME media type, prefixed by a slash.""" 

260 embedded_file = self._embedded_file 

261 if value is None: 

262 embedded_file[NameObject("/Subtype")] = NullObject() 

263 else: 

264 embedded_file[NameObject("/Subtype")] = value 

265 

266 @property 

267 def content(self) -> bytes: 

268 """Retrieve the actual file content.""" 

269 return self._get_content() 

270 

271 @content.setter 

272 def content(self, value: str | bytes) -> None: 

273 """Set the file content.""" 

274 if isinstance(value, str): 

275 value = value.encode("latin-1") 

276 self._embedded_file.set_data(value) 

277 

278 def _get_content(self, traversal_state: _TraversalState | None = None) -> bytes: 

279 """Retrieve the actual file content, but track the overall content budget if requested.""" 

280 content = self._embedded_file.get_data() 

281 if traversal_state is not None: 

282 traversal_state.entry_count -= len(content) 

283 if traversal_state.entry_count < 0: 

284 raise LimitReachedError("Maximum aggregate attachment content size exceeded.") 

285 return content 

286 

287 @property 

288 def size(self) -> int | None: 

289 """Retrieve the size of the uncompressed file in bytes.""" 

290 value = self._params.get("/Size") 

291 if is_null_or_none(value): 

292 return None 

293 return value 

294 

295 @size.setter 

296 def size(self, value: NumberObject | None) -> None: 

297 """Set the size of the uncompressed file in bytes.""" 

298 params = self._ensure_params 

299 if value is None: 

300 params[NameObject("/Size")] = NullObject() 

301 else: 

302 params[NameObject("/Size")] = value 

303 

304 @property 

305 def creation_date(self) -> datetime.datetime | None: 

306 """Retrieve the file creation datetime.""" 

307 return parse_iso8824_date(self._params.get("/CreationDate")) 

308 

309 @creation_date.setter 

310 def creation_date(self, value: datetime.datetime | None) -> None: 

311 """Set the file creation datetime.""" 

312 params = self._ensure_params 

313 if value is None: 

314 params[NameObject("/CreationDate")] = NullObject() 

315 else: 

316 date_str = format_iso8824_date(value) 

317 params[NameObject("/CreationDate")] = TextStringObject(date_str) 

318 

319 @property 

320 def modification_date(self) -> datetime.datetime | None: 

321 """Retrieve the datetime of the last file modification.""" 

322 return parse_iso8824_date(self._params.get("/ModDate")) 

323 

324 @modification_date.setter 

325 def modification_date(self, value: datetime.datetime | None) -> None: 

326 """Set the datetime of the last file modification.""" 

327 params = self._ensure_params 

328 if value is None: 

329 params[NameObject("/ModDate")] = NullObject() 

330 else: 

331 date_str = format_iso8824_date(value) 

332 params[NameObject("/ModDate")] = TextStringObject(date_str) 

333 

334 @property 

335 def checksum(self) -> bytes | None: 

336 """Retrieve the MD5 checksum of the (uncompressed) file.""" 

337 value = self._params.get("/CheckSum") 

338 if is_null_or_none(value): 

339 return None 

340 return value 

341 

342 @checksum.setter 

343 def checksum(self, value: ByteStringObject | None) -> None: 

344 """Set the MD5 checksum of the (uncompressed) file.""" 

345 params = self._ensure_params 

346 if value is None: 

347 params[NameObject("/CheckSum")] = NullObject() 

348 else: 

349 params[NameObject("/CheckSum")] = value 

350 

351 @property 

352 def _names(self) -> Iterator[str]: 

353 yield self.name 

354 if self.alternative_name is not None and self.alternative_name != self.name: 

355 yield self.alternative_name 

356 

357 def delete(self) -> None: 

358 """Delete the file from the document.""" 

359 if not self._parent: 

360 raise PyPdfError("Parent required to delete file from document.") 

361 if self.pdf_object in self._parent: 

362 index = self._parent.index(self.pdf_object) 

363 elif ( 

364 (indirect_reference := getattr(self.pdf_object, "indirect_reference", None)) is not None 

365 and indirect_reference in self._parent 

366 ): 

367 index = self._parent.index(indirect_reference) 

368 else: 

369 raise PyPdfError("File not found in parent object.") 

370 self._parent.pop(index) # Reference. 

371 self._parent.pop(index - 1) # Name. 

372 self.pdf_object = DictionaryObject() # Invalidate. 

373 

374 def __repr__(self) -> str: 

375 return f"<{self.__class__.__name__} name={self.name!r}>" 

376 

377 @staticmethod 

378 def _report_malformed(message: str, strict: bool) -> None: 

379 """Raise an exception in strict mode, warn otherwise.""" 

380 if strict: 

381 raise PdfReadError(message) 

382 logger_warning(message, source=__name__) 

383 

384 @classmethod 

385 def _load_from_names( 

386 cls, names: ArrayObject, strict: bool = False, *, 

387 traversal_state: _TraversalState, traversal_limit: int, 

388 ) -> Iterator[EmbeddedFile]: 

389 """ 

390 Convert the given name tree into class instances. 

391 

392 Args: 

393 names: The name tree to load the data from. 

394 strict: Whether to raise an exception on a file specification that is not a dictionary 

395 instead of issuing a warning and skipping it. 

396 traversal_state: Shared visitor counter. 

397 traversal_limit: Allowed number of embedded files. 

398 

399 Returns: 

400 Iterable of class instances for the files found. 

401 """ 

402 # This is a name tree of the format [name_1, reference_1, name_2, reference_2, ...] 

403 for i, name in enumerate(names): 

404 if not isinstance(name, str): 

405 # Skip plain strings and retrieve them as `direct_name` by index. 

406 file_dictionary = name.get_object() 

407 if isinstance(file_dictionary, NullObject): 

408 # A null value is equivalent to an omitted entry. 

409 continue 

410 if not isinstance(file_dictionary, DictionaryObject): 

411 cls._report_malformed( 

412 f"Embedded file specification is not a dictionary: {file_dictionary}", strict=strict 

413 ) 

414 continue 

415 traversal_state.entry_count += 1 

416 if traversal_state.entry_count > traversal_limit: 

417 raise LimitReachedError("Maximum embedded file entry limit exceeded.") 

418 direct_name = names[i - 1].get_object() 

419 yield EmbeddedFile(name=direct_name, pdf_object=file_dictionary, parent=names) 

420 

421 @classmethod 

422 def _load(cls, catalog: DictionaryObject, strict: bool = False) -> Iterator[EmbeddedFile]: 

423 """ 

424 Load the embedded files for the given document catalog. 

425 

426 This method and its signature are considered internal API and thus not exposed publicly for now. 

427 

428 Args: 

429 catalog: The document catalog to load from. 

430 strict: Whether to raise an exception on malformed name trees 

431 instead of issuing a warning and skipping them. 

432 

433 Returns: 

434 Iterable of class instances for the files found. 

435 """ 

436 if CatalogAttributes.NAMES not in catalog: 

437 return 

438 names = catalog[CatalogAttributes.NAMES] 

439 if isinstance(names, NullObject): 

440 # A null value is equivalent to an omitted entry. 

441 return 

442 if not isinstance(names, DictionaryObject): 

443 cls._report_malformed(f"Names tree is not a dictionary: {names}", strict=strict) 

444 return 

445 if "/EmbeddedFiles" not in names: 

446 return 

447 container = names["/EmbeddedFiles"] 

448 if isinstance(container, NullObject): 

449 return 

450 if not isinstance(container, DictionaryObject): 

451 cls._report_malformed(f"Embedded files entry is not a dictionary: {container}", strict=strict) 

452 return 

453 

454 from pypdf._utils import _TraversalState # noqa: PLC0415 

455 traversal_state = _TraversalState() 

456 

457 configuration = get_configuration() 

458 for node in _iter_name_tree(container): 

459 if not isinstance(node, DictionaryObject): 

460 cls._report_malformed(f"Embedded files kid is not a dictionary: {node}", strict=strict) 

461 continue 

462 kids = node.get("/Kids", NullObject()).get_object() 

463 if not isinstance(kids, (ArrayObject, NullObject)): 

464 cls._report_malformed(f"Embedded files /Kids is not an array: {kids}", strict=strict) 

465 node_names = node.get("/Names", NullObject()).get_object() 

466 if isinstance(node_names, NullObject): 

467 continue 

468 if not isinstance(node_names, ArrayObject): 

469 cls._report_malformed(f"Embedded files name list is not an array: {node_names}", strict=strict) 

470 continue 

471 yield from cls._load_from_names( 

472 node_names, 

473 strict=strict, 

474 traversal_state=traversal_state, 

475 traversal_limit=configuration.embedded_files_maximum_count 

476 )