Debian Codegraph @

src/lib/WPSOLEStream.cpp

raw symbols SCIP
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
2 /* librevenge
3
4 Original source: POLE - Portable C++ library to access OLE Storage
5 Copyright (C) 2002-2005 Ariya Hidayat <[email protected]>
6
7 Performance optimization: Dmitry Fedorov
8 Copyright 2009 <www.bioimage.ucsb.edu> <www.dimin.net>
9
10 Fix for more than 236 mbat block entries : Michel Boudinot
11 Copyright 2010 <[email protected]>
12
13 Version: 0.4
14
15 Redistribution and use in source and binary forms, with or without
16 modification, are permitted provided that the following conditions
17 are met:
18 * Redistributions of source code must retain the above copyright notice,
19 this list of conditions and the following disclaimer.
20 * Redistributions in binary form must reproduce the above copyright notice,
21 this list of conditions and the following disclaimer in the documentation
22 and/or other materials provided with the distribution.
23 * Neither the name of the authors nor the names of its contributors may be
24 used to endorse or promote products derived from this software without
25 specific prior written permission.
26
27 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
28 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
31 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
37 THE POSSIBILITY OF SUCH DAMAGE.
38 */
39
40 /*
41 This file taken from librevenge RVNGOLEStream.cpp
42 */
43
44 #include <string.h>
45 #include <ctype.h>
46
47 #include <cassert>
48 #include <sstream>
49 #include <iostream>
50 #include <list>
51 #include <locale>
52 #include <set>
53 #include <string>
54 #include <vector>
55
56 #include <librevenge-stream/librevenge-stream.h>
57
58 #include "libwps_internal.h"
59
60 #include "WPSStringStream.h"
61
62 #include "WPSOLEStream.h"
63
64 namespace libwps_OLE
65 {
66
67 class IStorage;
68 class IStream;
69
70 enum { Avail = 0xffffffff, Eof = 0xfffffffe, Bat = 0xfffffffd, MetaBat = 0xfffffffc, NotFound=0xfffffff0 };
71
72 static inline unsigned short readU16(const unsigned char *ptr)
73 {
74 return static_cast<unsigned short>(ptr[0]+(ptr[1]<<8));
75 }
76
77 static inline unsigned readU32(const unsigned char *ptr)
78 {
79 return unsigned(ptr[0]+(ptr[1]<<8)+(ptr[2]<<16)+(ptr[3]<<24));
80 }
81
82 static inline void writeU16(unsigned char *ptr, unsigned long data)
83 {
84 ptr[0] = static_cast<unsigned char>(data & 0xff);
85 ptr[1] = static_cast<unsigned char>((data >> 8) & 0xff);
86 }
87
88 static inline void writeU32(unsigned char *ptr, unsigned long data)
89 {
90 ptr[0] = static_cast<unsigned char>(data & 0xff);
91 ptr[1] = static_cast<unsigned char>((data >> 8) & 0xff);
92 ptr[2] = static_cast<unsigned char>((data >> 16) & 0xff);
93 ptr[3] = static_cast<unsigned char>((data >> 24) & 0xff);
94 }
95
96 static unsigned long getLength(librevenge::RVNGInputStream *const input)
97 {
98 assert(input);
99
100 const long pos = input->tell();
101 if (0 > pos)
102 return 0;
103
104 long end = 0;
105
106 if (0 == input->seek(0, librevenge::RVNG_SEEK_END))
107 end = input->tell();
108 if ((0 != input->seek(pos, librevenge::RVNG_SEEK_SET)) || (0 > end))
109 return 0;
110
111 assert(pos <= end);
112
113 return static_cast<unsigned long>(end);
114 }
115
116 class Header
117 {
118 public:
119 unsigned char m_magic[8]; // signature, or magic identifier
120 unsigned m_revision; // the file revision
121 unsigned m_num_bat; // blocks allocated for big bat
122 unsigned m_start_dirent; // starting block for directory info
123 unsigned m_threshold; // switch from small to big file (usually 4K)
124 unsigned m_start_sbat; // starting block index to store small bat
125 unsigned m_num_sbat; // blocks allocated for small bat
126 unsigned m_shift_sbat; // sbat->blockSize = 1 << m_shift_sbat
127 unsigned m_size_sbat; // the small block size, default 0x40
128 unsigned m_shift_bbat; // bbat->blockSize = 1 << m_shift_bbat
129 unsigned m_size_bbat; // the big block size, default 0x200
130 unsigned m_start_mbat; // starting block to store meta bat
131 unsigned m_num_mbat; // blocks allocated for meta bat
132 unsigned long m_blocks_bbat[109];
133
134 Header();
135 void compute_block_size()
136 {
137 assert(m_shift_bbat < 31);
138 assert(m_shift_sbat < 31);
139 m_size_bbat = 1 << m_shift_bbat;
140 m_size_sbat = 1 << m_shift_sbat;
141 }
142 bool valid_signature() const
143 {
144 for (unsigned i = 0; i < 8; i++)
145 if (m_magic[i] != s_ole_magic[i]) return false;
146 return true;
147 }
148 bool valid(unsigned long fileSize) const;
149 void load(const unsigned char *buffer, unsigned long size);
150 void save(unsigned char *buffer);
151 protected:
152 static const unsigned char s_ole_magic[];
153 };
154
155 const unsigned char Header::s_ole_magic[] =
156 { 0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1 };
157
158 class AllocTable
159 {
160 public:
161 unsigned m_blockSize;
162 AllocTable() : m_blockSize(4096), m_data()
163 {
164 resize(128); // initial size
165 }
166 void clear();
167 unsigned long count() const
168 {
169 return static_cast<unsigned long>(m_data.size());
170 }
171 void resize(unsigned long newsize)
172 {
173 m_data.resize(size_t(newsize), Avail);
174 }
175 void set(unsigned long index, unsigned long val)
176 {
177 if (index >= count())
178 resize(index+1);
179 m_data[size_t(index)] = val;
180 }
181 std::vector<unsigned long> follow(unsigned long start) const;
182 unsigned long operator[](unsigned long index) const
183 {
184 return m_data[size_t(index)];
185 }
186 void load(const unsigned char *buffer, unsigned len)
187 {
188 resize(len / 4);
189 for (unsigned i = 0; i < count(); i++)
190 set(i, readU32(buffer + i*4));
191 }
192
193 // write part
194 void setChain(std::vector<unsigned long> chain, unsigned end);
195 void save(unsigned char *buffer) const
196 {
197 auto cnt=unsigned(count());
198 unsigned i = 0;
199 for (i = 0; i < cnt; i++)
200 writeU32(buffer + i*4, m_data[i]);
201 unsigned lastFree = 128-(cnt%128);
202 if (lastFree==128) return;
203 for (i = 0; i < lastFree; i++)
204 writeU32(buffer + (cnt+i)*4, Avail);
205 }
206 // return space required to save the allocation table
207 unsigned saveSize() const
208 {
209 auto cnt=unsigned(((count()+127)/128)*128);
210 return cnt * 4;
211 }
212 private:
213 std::vector<unsigned long> m_data;
214 AllocTable(const AllocTable &);
215 AllocTable &operator=(const AllocTable &);
216 };
217
218 class DirInfo
219 {
220 public:
221 //! constructor
222 DirInfo()
223 {
224 int i = 0;
225 for (i=0; i < 4; i++)
226 m_time[i]=0;
227 for (i=0; i < 4; i++)
228 m_clsid[i]=0;
229 }
230 //! returns true if the clsid field is filed
231 bool hasCLSId() const
232 {
233 for (unsigned int i : m_clsid)
234 if (i) return true;
235 return false;
236 }
237 /** four uint32_t : the first two used for creation, the last for modification time */
238 unsigned m_time[4];
239 /** four uint32_t: the clsid data */
240 unsigned m_clsid[4];
241 };
242
243 class DirEntry
244 {
245 public:
246 enum { End= 0xffffffff };
247 //! constructor
248 DirEntry() : m_valid(false), m_macRootEntry(false), m_type(0), m_colour(0), m_size(0), m_start(0),
249 m_right(End), m_left(End), m_child(End), m_info(), m_name("")
250 {
251 }
252 //! returns true for a directory
253 bool is_dir() const
254 {
255 return m_type==1 || m_type==5;
256 }
257 //! returns the simplified file name
258 std::string name() const
259 {
260 if (m_name.length() && m_name[0]<32)
261 return m_name.substr(1);
262 return m_name;
263 }
264 /** returns the string which was store inside the file.
265
266 \note: either name() or a index (unknown) followed by name() */
267 std::string const &filename() const
268 {
269 return m_name;
270 }
271 /** sets the file name */
272 void setName(std::string const &nm)
273 {
274 m_name=nm;
275 }
276 /** reads a entry content in buffer */
277 void load(unsigned char *buffer, unsigned len);
278 //! saves a entry content in buffer */
279 void save(unsigned char *buffer) const;
280 //! returns space required to save a dir entry
281 static unsigned saveSize()
282 {
283 return 128;
284 }
285
286 bool m_valid; /** false if invalid (should be skipped) */
287 bool m_macRootEntry; /** true if this is a classic mac directory entry */
288 unsigned m_type; /** the type */
289 unsigned m_colour; /** the red/black color: 0 means red */
290 unsigned long m_size; /** size (not valid if directory) */
291 unsigned long m_start; /** starting block */
292 unsigned m_right; /** previous sibling */
293 unsigned m_left; /** next sibling */
294 unsigned m_child; /** first child */
295
296 DirInfo m_info; //! the file information
297 protected:
298 std::string m_name; /** the name, not in unicode anymore */
299 };
300
301 class DirTree
302 {
303 public:
304 /** constructor */
305 DirTree() : m_entries()
306 {
307 clear();
308 }
309 /** clear all entries, leaving only a root entries */
310 void clear();
311 /** set the root to a mac/pc root */
312 void setRootType(bool pc=true);
313 /** returns true if it is a pc file */
314 bool hasRootTypePc() const
315 {
316 return !m_entries.size() || !m_entries[0].m_macRootEntry;
317 }
318 /** returns the number of entries */
319 unsigned count() const
320 {
321 return unsigned(m_entries.size());
322 }
323 /** returns the entry with a given index */
324 DirEntry const *entry(unsigned ind) const
325 {
326 if (ind >= count()) return nullptr;
327 return &m_entries[ size_t(ind) ];
328 }
329 /** returns the entry with a given index */
330 DirEntry *entry(unsigned ind)
331 {
332 if (ind >= count()) return nullptr;
333 return &m_entries[ size_t(ind) ];
334 }
335 /** returns the entry with a given name */
336 DirEntry *entry(const std::string &name)
337 {
338 return entry(index(name));
339 }
340 /** given a fullname (e.g "/ObjectPool/_1020961869"), find the entry */
341 unsigned index(const std::string &name, bool create=false);
342 /** tries to find a child of ind with a given name */
343 unsigned find_child(unsigned ind, const std::string &name) const
344 {
345 DirEntry const *p = entry(ind);
346 if (!p || !p->m_valid) return 0;
347 std::vector<unsigned> siblingsList = get_siblings(p->m_child);
348 for (unsigned s : siblingsList)
349 {
350 p = entry(s);
351 if (!p) continue;
352 if (p->name()==name)
353 return s;
354 }
355 return 0;
356 }
357 /** returns the list of ind substream */
358 std::vector<std::string> getSubStreamList(unsigned ind=0, bool retrieveAll=false)
359 {
360 std::vector<std::string> res;
361 std::set<unsigned> seens;
362 getSubStreamList(ind, retrieveAll, "", res, seens, true);
363 return res;
364 }
365 /** tries to read the different entries */
366 void load(unsigned char *buffer, unsigned len);
367
368 // write part:
369 //! check/update so that the sibling are store with a red black tree
370 void setInRedBlackTreeForm()
371 {
372 std::set<unsigned> seens;
373 setInRedBlackTreeForm(0, seens);
374 }
375 //! return space required to save a dir entry
376 unsigned saveSize() const
377 {
378 unsigned cnt = count();
379 cnt = 4*((cnt+3)/4);
380 return cnt*DirEntry::saveSize();
381 }
382 //! save the list of direntry in buffer
383 void save(unsigned char *buffer) const
384 {
385 unsigned entrySize=DirEntry::saveSize();
386 size_t cnt = count();
387 for (size_t i = 0; i < cnt; i++)
388 m_entries[i].save(buffer+entrySize*i);
389 if ((cnt%4)==0) return;
390 DirEntry empty;
391 while (cnt%4)
392 empty.save(buffer+entrySize*cnt++);
393 }
394 protected:
395 //! returns a list of siblings corresponding to a node
396 std::vector<unsigned> get_siblings(unsigned ind) const
397 {
398 std::set<unsigned> seens;
399 get_siblings(ind, seens);
400 std::vector<unsigned> retVal;
401 for (unsigned seen : seens)
402 retVal.push_back(seen);
403 return retVal;
404 }
405 //! constructs the list of siblings ( by filling the seens set )
406 void get_siblings(unsigned ind, std::set<unsigned> &seens) const
407 {
408 if (seens.find(ind) != seens.end())
409 return;
410 seens.insert(ind);
411 DirEntry const *e = entry(ind);
412 if (!e) return;
413 unsigned cnt = count();
414 if (e->m_left>0&& e->m_left < cnt)
415 get_siblings(e->m_left, seens);
416 if (e->m_right>0 && e->m_right < cnt)
417 get_siblings(e->m_right, seens);
418 }
419 /** returns a substream list */
420 void getSubStreamList(unsigned ind, bool all, const std::string &prefix,
421 std::vector<std::string> &res, std::set<unsigned> &seen,
422 bool isRoot=false) const;
423
424 /** check that the subtrees of index is a red black tree, if not rebuild it */
425 void setInRedBlackTreeForm(unsigned id, std::set<unsigned> &seen);
426 /** rebuild all the childs m_left, m_right index as a red black
427 tree, returns the root index.
428
429 \note: this function supposes that the childs list is already sorted
430 */
431 unsigned setInRBTForm(std::vector<unsigned> const &childList,
432 unsigned firstInd, unsigned lastInd,
433 unsigned height);
434
435 /** a comparaison funcion of DirTree used to sort the entry by name */
436 struct CompareEntryName
437 {
438 //! constructor
439 explicit CompareEntryName(DirTree &tree) : m_tree(tree)
440 {
441 }
442 //! comparaison function
443 bool operator()(unsigned ind1, unsigned ind2) const
444 {
445 DirEntry const *e1=m_tree.entry(ind1);
446 DirEntry const *e2=m_tree.entry(ind2);
447 if (!e1 && !e2) return false;
448 if (!e1) return true;
449 if (!e2) return false;
450 std::string name1(e1->name()), name2(e2->name());
451 size_t len1=name1.length();
452 size_t len2=name2.length();
453 if (len1 != len2) return len1 < len2;
454 for (size_t c=0; c < len1; c++)
455 {
456 if (tolower(name1[c]) != tolower(name2[c]))
457 return tolower(name1[c]) < tolower(name2[c]);
458 }
459 return ind1 < ind2;
460 }
461
462 //! the main tree
463 DirTree &m_tree;
464 };
465
466 private:
467 std::vector<DirEntry> m_entries;
468 DirTree(const DirTree &);
469 DirTree &operator=(const DirTree &);
470 };
471
472 class IStorage
473 {
474 public:
475 // for m_result
476 enum Result { Ok, OpenFailed, NotOLE, BadOLE, UnknownError };
477
478 librevenge::RVNGInputStream *m_input;
479 Result m_result; // result of operation
480
481 Header m_header; // storage header
482 DirTree m_dirtree; // directory tree
483 AllocTable m_bbat; // allocation table for big blocks
484 AllocTable m_sbat; // allocation table for small blocks
485
486 std::vector<unsigned long> m_sb_blocks; // blocks for "small" files
487
488 explicit IStorage(librevenge::RVNGInputStream *is);
489 ~IStorage() {}
490
491 //! returns a directory entry corresponding to a index
492 DirEntry *entry(unsigned ind)
493 {
494 load();
495 return m_dirtree.entry(ind);
496 }
497 //! returns a directory entry corresponding to a name
498 DirEntry *entry(const std::string &name)
499 {
500 if (!name.length()) return nullptr;
501 load();
502 return m_dirtree.entry(name);
503 }
504 //! returns a directory entry corresponding to a index
505 unsigned index(const std::string &name)
506 {
507 if (!name.length()) return NotFound;
508 load();
509 return m_dirtree.index(name);
510 }
511 /** returns the OLE revision */
512 unsigned revision() const
513 {
514 return m_header.m_revision;
515 }
516 /** returns true if it is a pc file */
517 bool hasRootTypePc() const
518 {
519 return m_dirtree.hasRootTypePc();
520 }
521 //! returns true if the entry exists in the OLE, if so fills isDir
522 bool isSubStream(const std::string &name, bool &isDir);
523 //! returns the list of subStream given a dirEntry index
524 std::vector<std::string> getSubStreamList(unsigned ind=0, bool retrieveAll=false)
525 {
526 load();
527 return m_dirtree.getSubStreamList(ind, retrieveAll);
528 }
529
530 bool isStructured();
531 std::vector<std::string> getSubStreamNamesList();
532 void load();
533
534 bool use_big_block_for(unsigned long size) const
535 {
536 return size >= m_header.m_threshold;
537 }
538 unsigned long loadBigBlocks(std::vector<unsigned long> const &blocks, unsigned char *buffer, unsigned long maxlen) const;
539
540 unsigned long loadBigBlock(unsigned long block, unsigned char *buffer, unsigned long maxlen) const;
541
542 unsigned long loadSmallBlocks(std::vector<unsigned long> const &blocks, unsigned char *buffer, unsigned long maxlen);
543
544 unsigned long loadSmallBlock(unsigned long block, unsigned char *buffer, unsigned long maxlen);
545
546 protected:
547 bool m_isLoad;
548 private:
549 // no copy or assign
550 IStorage(const IStorage &);
551 IStorage &operator=(const IStorage &);
552
553 };
554
555 class OStorage
556 {
557 public:
558 //! constructor
559 explicit OStorage(unsigned long minSize=0) : m_header(), m_dirtree(), m_bbat(), m_num_bbat(0), m_sbat(), m_num_sbat(0), m_sb_blocks(), m_data()
560 {
561 // update data to contain at least, header
562 m_data.resize(minSize>512 ? minSize : 512);
563 }
564 //! destructor
565 ~OStorage() { }
566
567 //! function to retrieve the list of actual direntry
568 std::vector<std::string> getSubStreamList(unsigned ind=0, bool all=false)
569 {
570 return m_dirtree.getSubStreamList(ind, all);
571 }
572 /** set the OLE revision */
573 void setRevision(unsigned rev)
574 {
575 m_header.m_revision=rev;
576 }
577 //! set the root to a mac/pc root */
578 void setRootType(bool pc)
579 {
580 m_dirtree.setRootType(pc);
581 }
582 //! add a new stream knowing its data
583 bool addStream(std::string const &name, unsigned char const *buffer, unsigned long len);
584 //! add a new directory (usefull to create empty leaf dir )
585 bool addDirectory(std::string const &dir);
586 //! set a node information
587 void setInformation(std::string const &name, DirInfo const &info)
588 {
589 DirEntry *e = m_dirtree.entry(name);
590 if (!e)
591 {
592 WPS_DEBUG_MSG(("librevengeOLE::OStorage::setInformation: can not find entry %s!!!\n", name.c_str()));
593 return;
594 }
595 e->m_info = info;
596 }
597 //! try to return in data the contain of the file
598 bool getFileData(std::vector<unsigned char> &data)
599 {
600 try
601 {
602 if (!updateToSave())
603 return false;
604 data = m_data;
605 }
606 catch (...)
607 {
608 return false;
609 }
610 return true;
611 }
612
613 protected:
614 //! add stream data in a file, returns the first index
615 unsigned insertData(unsigned char const *buffer, unsigned long len, bool useBigBlock, unsigned end=Eof);
616
617 //! return true if we need to use big block
618 bool useBigBlockFor(unsigned long size) const
619 {
620 return size >= m_header.m_threshold;
621 }
622 //! returns the maximum size of a big/small block
623 static unsigned long getMaximumSize(bool isBig)
624 {
625 return isBig ? 512 : 64;
626 }
627 //! returns the address of a big/small block
628 size_t getDataAddress(unsigned block, bool isBig) const
629 {
630 if (isBig) return size_t((block+1)*512);
631 auto bId=size_t(block/8);
632 if (bId >= m_sb_blocks.size()) throw libwps::GenericException();
633 return size_t((m_sb_blocks[bId]+1)*512+64*(block%8));
634 }
635
636 //! create a new big block, resize m_data; ... and return is identifier
637 unsigned newBBlock()
638 {
639 unsigned res = m_num_bbat++;
640 if (m_data.size() < (res+2)*512) m_data.resize((res+2)*512, 0);
641 m_bbat.resize(res+1);
642 return res;
643 }
644 //! create a new small block, ... and returns is identifier
645 unsigned newSBlock()
646 {
647 unsigned res = m_num_sbat++;
648 if ((res%8)==0)
649 m_sb_blocks.push_back(newBBlock());
650 m_sbat.resize(res+1);
651 return res;
652 }
653
654 //! return a new dir entry, if it does not exists
655 DirEntry *createEntry(std::string const &name)
656 {
657 if (name.length()==0)
658 {
659 WPS_DEBUG_MSG(("librevengeOLE::OStorage::createEntry: called with no name\n"));
660 return nullptr;
661 }
662 if (m_dirtree.index(name)!=NotFound)
663 {
664 WPS_DEBUG_MSG(("librevengeOLE::OStorage::createEntry: entry %s already exists\n", name.c_str()));
665 return nullptr;
666 }
667 unsigned index = m_dirtree.index(name,true);
668 if (index == NotFound) return nullptr;
669
670 return m_dirtree.entry(index);
671 }
672
673 //! finish to update the file ( note: it is better to call this function only one time )
674 bool updateToSave();
675
676 Header m_header; // storage header
677 DirTree m_dirtree; // directory tree
678 AllocTable m_bbat; // allocation table for big blocks
679 unsigned m_num_bbat; // the number of bbat
680 AllocTable m_sbat; // allocation table for small blocks
681 unsigned m_num_sbat; // the number of sbat
682
683 std::vector<unsigned long> m_sb_blocks; // blocks for "small" files
684
685 std::vector<unsigned char> m_data;
686 private:
687 // no copy or assign
688 OStorage(const OStorage &);
689 OStorage &operator=(const OStorage &);
690 };
691
692 class IStream
693 {
694 public:
695 IStorage *m_iStorage;
696 //! the stream size
697 unsigned long m_size;
698 std::string m_name;
699
700 IStream(IStorage *io, std::string const &name);
701 ~IStream()
702 {
703 }
704 unsigned long size() const
705 {
706 return m_size;
707 }
708 unsigned long tell() const
709 {
710 return m_pos;
711 }
712 unsigned long read(unsigned char *data, unsigned long maxlen)
713 {
714 if (!m_size)
715 return 0;
716 unsigned long bytes;
717 if (m_data.size())
718 bytes = readData(tell(), data, maxlen);
719 else
720 bytes = readUsingStorage(tell(), data, maxlen);
721 m_pos += bytes;
722 return bytes;
723 }
724
725 protected:
726 //! create the data corresponding to a directory
727 bool createOleFromDirectory(IStorage *io, std::string const &name);
728 //! try to read maxlen data using m_iStorage
729 unsigned long readUsingStorage(unsigned long pos, unsigned char *data, unsigned long maxlen);
730 //! try to read maxlen data using m_data
731 unsigned long readData(unsigned long pos, unsigned char *data, unsigned long maxlen);
732
733 private:
734 std::vector<unsigned long> m_blocks;
735
736 // no copy or assign
737 IStream(const IStream &);
738 IStream &operator=(const IStream &);
739
740 // pointer for read
741 unsigned long m_pos;
742
743 // a copy of the data when the entry came for OStorage
744 std::vector<unsigned char> m_data;
745 };
746
747 } // namespace librevenge
748 // =========== Header ==========
749
750 libwps_OLE::Header::Header() :
751 m_revision(0x3e), m_num_bat(0), m_start_dirent(0), m_threshold(4096),
752 m_start_sbat(Eof), m_num_sbat(0), m_shift_sbat(6), m_size_sbat(0),
753 m_shift_bbat(9), m_size_bbat(0),
754 m_start_mbat(Eof), m_num_mbat(0)
755 {
756 for (unsigned i = 0; i < 8; i++)
757 m_magic[i] = s_ole_magic[i];
758 for (unsigned long &j : m_blocks_bbat)
759 j = Avail;
760 compute_block_size();
761 }
762
763 bool libwps_OLE::Header::valid(const unsigned long fileSize) const
764 {
765 if (m_threshold != 4096) return false;
766 // there must be at least the header, one bat sector and one dirent sector in the file
767 if ((fileSize / m_size_bbat) < 3) return false;
768 // sectors must fit into the file
769 if ((fileSize / m_size_bbat) < m_num_mbat) return false;
770 if (m_num_bat == 0) return false;
771 if ((m_num_bat > 109) && (m_num_bat > (m_num_mbat * (m_size_bbat/4-1)) + 109)) return false;
772 if ((m_num_bat < 109) && (m_num_mbat != 0)) return false;
773 if (m_shift_sbat > m_shift_bbat) return false;
774 if (m_shift_bbat <= 6) return false;
775 if (m_shift_bbat >=31) return false;
776 return true;
777 }
778
779 void libwps_OLE::Header::load(const unsigned char *buffer, unsigned long size)
780 {
781 if (size < 512)
782 return;
783 m_revision = unsigned(readU16(buffer+0x18));
784 m_shift_bbat =static_cast<unsigned int>(readU16(buffer + 0x1e));
785 if (m_shift_bbat > 31)
786 m_shift_bbat = 31;
787 m_shift_sbat =static_cast<unsigned int>(readU16(buffer + 0x20));
788 if (m_shift_sbat > 31)
789 m_shift_sbat = 31;
790 m_num_bat =static_cast<unsigned int>(readU32(buffer + 0x2c));
791 m_start_dirent =static_cast<unsigned int>(readU32(buffer + 0x30));
792 m_threshold =static_cast<unsigned int>(readU32(buffer + 0x38));
793 m_start_sbat =static_cast<unsigned int>(readU32(buffer + 0x3c));
794 m_num_sbat =static_cast<unsigned int>(readU32(buffer + 0x40));
795 m_start_mbat =static_cast<unsigned int>(readU32(buffer + 0x44));
796 m_num_mbat =static_cast<unsigned int>(readU32(buffer + 0x48));
797
798 for (unsigned i = 0; i < 8; i++)
799 m_magic[i] = buffer[i];
800 for (unsigned j=0; j<109; j++)
801 m_blocks_bbat[j] = readU32(buffer + 0x4C+j*4);
802 }
803
804 void libwps_OLE::Header::save(unsigned char *buffer)
805 {
806 memcpy(buffer, s_ole_magic, 8); // ole signature
807 memset(buffer + 8, 0, 0x4c - 8);
808 writeU32(buffer + 8, 0); // unknown
809 writeU32(buffer + 12, 0); // unknown
810 writeU32(buffer + 16, 0); // unknown
811 writeU16(buffer + 24, m_revision);
812 writeU16(buffer + 26, 3); // version ?
813 writeU16(buffer + 28, 0xfffe); // unknown
814 writeU16(buffer + 0x1e, m_shift_bbat);
815 writeU16(buffer + 0x20, m_shift_sbat);
816 writeU32(buffer + 0x2c, m_num_bat);
817 writeU32(buffer + 0x30, m_start_dirent);
818 writeU32(buffer + 0x38, m_threshold);
819 writeU32(buffer + 0x3c, m_start_sbat);
820 writeU32(buffer + 0x40, m_num_sbat);
821 writeU32(buffer + 0x44, m_start_mbat);
822 writeU32(buffer + 0x48, m_num_mbat);
823
824 for (unsigned i=0; i<109; i++)
825 writeU32(buffer + 0x4C+i*4, m_blocks_bbat[i]);
826 }
827
828
829 // =========== AllocTable ==========
830
831 std::vector<unsigned long> libwps_OLE::AllocTable::follow(unsigned long start) const
832 {
833 std::vector<unsigned long> chain;
834 if (start >= count()) return chain;
835
836 std::set<unsigned long> seens;
837 unsigned long p = start;
838 while (p < count())
839 {
840 if (p == Eof || p == Bat || p == MetaBat) break;
841 if (seens.find(p) != seens.end()) break;
842 seens.insert(p);
843 chain.push_back(p);
844 p = m_data[ p ];
845 }
846
847 return chain;
848 }
849
850 void libwps_OLE::AllocTable::setChain(std::vector<unsigned long> chain, unsigned end)
851 {
852 if (!chain.size()) return;
853
854 for (unsigned i=0; i<chain.size()-1; i++)
855 set(chain[i], chain[i+1]);
856 set(chain[ chain.size()-1 ], end);
857 }
858
859 // =========== DirEntry ==========
860 void libwps_OLE::DirEntry::load(unsigned char *buffer, unsigned len)
861 {
862 if (len != 128)
863 {
864 WPS_DEBUG_MSG(("DirEntry::load: unexpected len for DirEntry::load\n"));
865 *this=DirEntry();
866 return;
867 }
868 // 2 = file (aka stream), 1 = directory (aka storage), 5 = root
869 m_type = buffer[ 0x42];
870 m_colour = buffer[0x43];
871
872 // parse name of this entry, which stored as Unicode 16-bit
873 m_name=std::string("");
874 auto name_len = unsigned(readU16(buffer + 0x40));
875 if (name_len > 64) name_len = 64;
876 if (name_len==2 && m_type==5 && readU16(buffer)==0x5200)
877 {
878 // find in some mswork mac 4.0 file
879 m_name="R";
880 m_macRootEntry=true;
881 }
882 else
883 {
884 for (unsigned j=0; (j < name_len) && buffer[j]; j+= 2)
885 m_name.append(1, char(buffer[j]));
886 }
887
888 int i = 0;
889 for (i = 0; i < 4; i++)
890 m_info.m_clsid[i]=unsigned(readU32(buffer + 0x50 + 4*i));
891 for (i = 0; i < 4; i++)
892 m_info.m_time[i]=unsigned(readU32(buffer + 0x64 + 4*i));
893
894 m_valid = true;
895 m_start =static_cast<unsigned int>(readU32(buffer + 0x74));
896 m_size =static_cast<unsigned int>(readU32(buffer + 0x78));
897 m_left =static_cast<unsigned int>(readU32(buffer + 0x44));
898 m_right =static_cast<unsigned int>(readU32(buffer + 0x48));
899 m_child =static_cast<unsigned int>(readU32(buffer + 0x4C));
900
901 // sanity checks
902 if ((m_type != 2) && (m_type != 1) && (m_type != 5)) m_valid = false;
903 if (name_len < 1) m_valid = false;
904 }
905
906 void libwps_OLE::DirEntry::save(unsigned char *buffer) const
907 {
908 int i = 0;
909 for (i = 0; i < 128; i++) buffer[i]=0;
910
911 auto name_len = unsigned(m_name.length());
912 if (name_len>31) name_len = 31;
913 if (name_len==2 && m_macRootEntry && m_type==5)
914 buffer[1]='R';
915 else
916 {
917 for (size_t j = 0; j < name_len; j++)
918 writeU16(buffer+2*j, unsigned(m_name[j]));
919 }
920 writeU16(buffer+0x40, 2*name_len+2);
921
922 buffer[0x42]=static_cast<unsigned char>(m_type);
923 buffer[0x43]=static_cast<unsigned char>(m_colour);
924 for (i = 0; i < 4; i++)
925 writeU32(buffer + 0x50+4*i, m_info.m_clsid[i]);
926 for (i = 0; i < 4; i++)
927 writeU32(buffer + 0x64+4*i, m_info.m_time[i]);
928 writeU32(buffer + 0x74, m_start);
929 writeU32(buffer + 0x78, m_size);
930 writeU32(buffer + 0x44, m_left);
931 writeU32(buffer + 0x48, m_right);
932 writeU32(buffer + 0x4C, m_child);
933 }
934 // =========== DirTree ==========
935
936 void libwps_OLE::DirTree::clear()
937 {
938 m_entries.resize(0);
939 setRootType(true);
940 }
941
942 void libwps_OLE::DirTree::setRootType(bool pc)
943 {
944 if (!m_entries.size())
945 {
946 m_entries.resize(1);
947 m_entries[0]=DirEntry();
948 m_entries[0].m_valid = true;
949 m_entries[0].setName("Root Entry");
950 m_entries[0].m_type = 5;
951 }
952 if (pc)
953 m_entries[0].setName("Root Entry");
954 else
955 {
956 m_entries[0].setName("R");
957 m_entries[0].m_macRootEntry = true;
958 }
959 }
960
961 unsigned libwps_OLE::DirTree::index(const std::string &name, bool create)
962 {
963
964 if (name.length()==0) return NotFound;
965
966 // quick check for "/" (that's root)
967 if (name == "/") return 0;
968
969 // split the names, e.g "/ObjectPool/_1020961869" will become:
970 // "ObjectPool" and "_1020961869"
971 std::list<std::string> names;
972 std::string::size_type start = 0, end = 0;
973 if (name[0] == '/') start++;
974 while (start < name.length())
975 {
976 end = name.find_first_of('/', start);
977 if (end == std::string::npos) end = name.length();
978 names.push_back(name.substr(start, end-start));
979 start = end+1;
980 }
981
982 // start from root
983 unsigned ind = 0 ;
984
985 // trace one by one
986 std::list<std::string>::const_iterator it;
987 size_t depth = 0;
988
989 for (it = names.begin(); it != names.end(); ++it, ++depth)
990 {
991 std::string childName(*it);
992 if (childName.length() && childName[0]<32)
993 childName= it->substr(1);
994
995 unsigned child = find_child(ind, childName);
996 // traverse to the child
997 if (child > 0)
998 {
999 ind = child;
1000 continue;
1001 }
1002 else if (!create) return NotFound;
1003
1004 // create a new entry
1005 unsigned parent = ind;
1006 m_entries.push_back(DirEntry());
1007 ind = count()-1;
1008 DirEntry *e = entry(ind);
1009 e->m_valid = true;
1010 e->setName(*it);
1011 e->m_type = depth+1==names.size() ? 2 : 1;
1012 // e->m_start = Eof; CHECKME
1013 e->m_left = entry(parent)->m_child;
1014 entry(parent)->m_child = ind;
1015 }
1016
1017 return ind;
1018 }
1019
1020 void libwps_OLE::DirTree::load(unsigned char *buffer, unsigned size)
1021 {
1022 m_entries.clear();
1023
1024 for (unsigned i = 0; i < size/128; i++)
1025 {
1026 DirEntry e;
1027 e.load(buffer+i*128, 128);
1028 m_entries.push_back(e);
1029 }
1030 }
1031
1032 void libwps_OLE::DirTree::getSubStreamList(unsigned ind, bool all, const std::string &prefix,
1033 std::vector<std::string> &res,
1034 std::set<unsigned> &seen,
1035 bool isRoot) const
1036 {
1037 if (seen.find(ind) != seen.end())
1038 return;
1039 seen.insert(ind);
1040 unsigned cnt = count();
1041 DirEntry const *p = entry(ind);
1042 if (!p || !p->m_valid)
1043 return;
1044 std::string name(prefix);
1045 if (ind && !isRoot)
1046 {
1047 if (p->filename().length())
1048 name+= p->filename();
1049 else
1050 return;
1051 }
1052 if (!p->is_dir())
1053 {
1054 res.push_back(name);
1055 return;
1056 }
1057 if (ind)
1058 name += "/";
1059 if (all)
1060 {
1061 if (ind)
1062 res.push_back(name);
1063 else
1064 res.push_back("/");
1065 }
1066 if (p->m_child >= cnt)
1067 return;
1068 std::vector<unsigned> siblings=get_siblings(p->m_child);
1069 for (unsigned sibling : siblings)
1070 getSubStreamList(sibling, all, name, res, seen);
1071 }
1072
1073 void libwps_OLE::DirTree::setInRedBlackTreeForm(unsigned ind, std::set<unsigned> &seen)
1074 {
1075 if (seen.find(ind) != seen.end())
1076 return;
1077 seen.insert(ind);
1078
1079 DirEntry *p = entry(ind);
1080 if (!p || !p->m_valid)
1081 return;
1082
1083 p->m_colour=1; // set all nodes blacks
1084 std::vector<unsigned> childs=get_siblings(p->m_child);
1085 size_t numChild=childs.size();
1086 for (size_t s=0; s < numChild; s++)
1087 setInRedBlackTreeForm(childs[s], seen);
1088 if (numChild <= 1)
1089 return;
1090 CompareEntryName compare(*this);
1091 std::set<unsigned,CompareEntryName> set(childs.begin(),childs.end(),compare);
1092 std::vector<unsigned> sortedChildren;
1093 for (unsigned iter : set)
1094 sortedChildren.push_back(iter);
1095 if (sortedChildren.size() != numChild)
1096 {
1097 WPS_DEBUG_MSG(("DirTree::setInRedBlackTreeForm: OOPS pb with numChild\n"));
1098 return;
1099 }
1100 unsigned h=1;
1101 unsigned hNumChild=1;
1102 while (2*hNumChild+1<=numChild)
1103 {
1104 hNumChild=2*hNumChild+1;
1105 h++;
1106 }
1107 p->m_child=setInRBTForm(sortedChildren, 0, unsigned(numChild-1), h);
1108 }
1109
1110 unsigned libwps_OLE::DirTree::setInRBTForm(std::vector<unsigned> const &childs,
1111 unsigned firstInd, unsigned lastInd,
1112 unsigned height)
1113 {
1114 unsigned middle = (firstInd+lastInd)/2;
1115 unsigned ind=childs[middle];
1116 DirEntry *p = entry(ind);
1117 if (!p)
1118 {
1119 WPS_DEBUG_MSG(("DirTree::setInRedBlackTreeForm: OOPS can not find tree to modified\n"));
1120 throw libwps::GenericException();
1121 }
1122 unsigned newH = height==0 ? 0 : height-1;
1123 if (height==0)
1124 {
1125 p->m_colour = 0;
1126 if (firstInd!=middle || lastInd!=middle)
1127 {
1128 WPS_DEBUG_MSG(("DirTree::setInRedBlackTreeForm: OOPS problem setting RedBlack colour\n"));
1129 }
1130 }
1131 if (firstInd!=middle)
1132 p->m_left=setInRBTForm(childs, firstInd,unsigned(middle-1),newH);
1133 else
1134 p->m_left=DirEntry::End;
1135 if (lastInd!=middle)
1136 p->m_right=setInRBTForm(childs, unsigned(middle+1),lastInd,newH);
1137 else
1138 p->m_right=DirEntry::End;
1139 return ind;
1140 }
1141
1142
1143 // =========== IStorage ==========
1144
1145 libwps_OLE::IStorage::IStorage(librevenge::RVNGInputStream *is) :
1146 m_input(is),
1147 m_result(libwps_OLE::IStorage::Ok),
1148 m_header(), m_dirtree(),
1149 m_bbat(), m_sbat(), m_sb_blocks(),
1150 m_isLoad(false)
1151 {
1152 m_bbat.m_blockSize = m_header.m_size_bbat;
1153 m_sbat.m_blockSize = m_header.m_size_sbat;
1154 }
1155
1156 bool libwps_OLE::IStorage::isStructured()
1157 {
1158 load();
1159 return (m_result == libwps_OLE::IStorage::Ok);
1160 }
1161
1162 std::vector<std::string> libwps_OLE::IStorage::getSubStreamNamesList()
1163 {
1164 load();
1165 if (m_result != Ok)
1166 return std::vector<std::string>();
1167 return m_dirtree.getSubStreamList(0, true);
1168 }
1169
1170 bool libwps_OLE::IStorage::isSubStream(const std::string &name, bool &isDir)
1171 {
1172 if (!name.length()) return false;
1173 load();
1174 // search in the entries
1175 DirEntry *e = m_dirtree.entry(name);
1176 if (!e) return false;
1177 isDir = e->is_dir();
1178 return true;
1179 }
1180
1181 void libwps_OLE::IStorage::load()
1182 {
1183 if (m_isLoad)
1184 return;
1185 m_isLoad = true;
1186 m_result = NotOLE;
1187 if (!m_input)
1188 return;
1189
1190 std::vector<unsigned long> blocks;
1191
1192 // load header
1193 unsigned long numBytesRead = 0;
1194 m_input->seek(0, librevenge::RVNG_SEEK_SET);
1195 const unsigned char *buf = m_input->read(512, numBytesRead);
1196
1197 if (numBytesRead < 512)
1198 return;
1199
1200 m_header.load(buf, numBytesRead);
1201
1202 // check OLE magic id
1203 if (!m_header.valid_signature())
1204 return;
1205
1206 // important block size
1207 m_header.compute_block_size();
1208 m_bbat.m_blockSize = m_header.m_size_bbat;
1209 m_sbat.m_blockSize = m_header.m_size_sbat;
1210
1211 // sanity checks
1212 m_result = BadOLE;
1213 if (!m_header.valid(getLength(m_input))) return;
1214 if (m_header.m_threshold != 4096) return;
1215
1216 // find blocks allocated to store big bat
1217 // the first 109 blocks are in header, the rest in meta bat
1218 blocks.clear();
1219 blocks.resize(m_header.m_num_bat);
1220 for (unsigned j = 0; j < 109; j++)
1221 if (j >= m_header.m_num_bat) break;
1222 else blocks[j] = m_header.m_blocks_bbat[j];
1223 if ((m_header.m_num_bat > 109) && (m_header.m_num_mbat > 0))
1224 {
1225 std::vector<unsigned char> buffer2(m_bbat.m_blockSize);
1226 unsigned k = 109;
1227 unsigned long sector;
1228 for (unsigned r = 0; r < m_header.m_num_mbat && k > 0; r++)
1229 {
1230 if (r == 0) // 1st meta bat location is in file header.
1231 sector = m_header.m_start_mbat;
1232 else // next meta bat location is the last current block value.
1233 sector = blocks[--k];
1234 unsigned long readData=loadBigBlock(sector, &buffer2[0], m_bbat.m_blockSize);
1235 for (unsigned s=0; s < m_bbat.m_blockSize; s+=4)
1236 {
1237 // check that for maximum block and that the data are correctly read
1238 if (k >= m_header.m_num_bat || s>=readData) break;
1239 else blocks[k++] = readU32(&buffer2[s]);
1240 }
1241 }
1242 }
1243
1244 // load big bat
1245 if (blocks.size()*m_bbat.m_blockSize > 0)
1246 {
1247 std::vector<unsigned char> buffer(blocks.size()*m_bbat.m_blockSize);
1248 unsigned long readData=loadBigBlocks(blocks, &buffer[0], buffer.size());
1249 m_bbat.load(&buffer[0], unsigned(readData));
1250 }
1251
1252 // load small bat
1253 blocks.clear();
1254 blocks = m_bbat.follow(m_header.m_start_sbat);
1255 if (blocks.size()*m_bbat.m_blockSize > 0)
1256 {
1257 std::vector<unsigned char> buffer(blocks.size()*m_bbat.m_blockSize);
1258 unsigned long readData=loadBigBlocks(blocks, &buffer[0], buffer.size());
1259 m_sbat.load(&buffer[0], unsigned(readData));
1260 }
1261
1262 // load directory tree
1263 blocks.clear();
1264 blocks = m_bbat.follow(m_header.m_start_dirent);
1265 if (blocks.size()*m_bbat.m_blockSize > 0)
1266 {
1267 std::vector<unsigned char> buffer(blocks.size()*m_bbat.m_blockSize);
1268 unsigned long readData=loadBigBlocks(blocks, &buffer[0], buffer.size());
1269 m_dirtree.load(&buffer[0], unsigned(readData));
1270 if (readData >= 0x74 + 4)
1271 {
1272 unsigned sb_start = readU32(&buffer[0x74]);
1273
1274 // fetch block chain as data for small-files
1275 m_sb_blocks = m_bbat.follow(sb_start); // small files
1276
1277 // so far so good
1278 m_result = libwps_OLE::IStorage::Ok;
1279 }
1280 }
1281 }
1282
1283 unsigned long libwps_OLE::IStorage::loadBigBlocks(std::vector<unsigned long> const &blocks,
1284 unsigned char *data, unsigned long maxlen) const
1285 {
1286 // sentinel
1287 if (!data) return 0;
1288 if (blocks.size() < 1) return 0;
1289 if (maxlen == 0) return 0;
1290
1291 // read block one by one, seems fast enough
1292 unsigned long bytes = 0;
1293 for (unsigned long i=0; (i < blocks.size()) && (bytes<maxlen); i++)
1294 {
1295 unsigned long block = blocks[i];
1296 unsigned long pos = m_bbat.m_blockSize * (block+1);
1297 unsigned long p = (m_bbat.m_blockSize < maxlen-bytes) ? m_bbat.m_blockSize : maxlen-bytes;
1298
1299 if (m_input->seek(long(pos), librevenge::RVNG_SEEK_SET)!=0)
1300 continue;
1301 unsigned long numBytesRead = 0;
1302 const unsigned char *buf = m_input->read(p, numBytesRead);
1303 memcpy(data+bytes, buf, numBytesRead);
1304 bytes += numBytesRead;
1305 }
1306
1307 return bytes;
1308 }
1309
1310 unsigned long libwps_OLE::IStorage::loadBigBlock(unsigned long block,
1311 unsigned char *data, unsigned long maxlen) const
1312 {
1313 // sentinel
1314 if (!data) return 0;
1315
1316 // wraps call for loadBigBlocks
1317 std::vector<unsigned long> blocks;
1318 blocks.resize(1);
1319 blocks[ 0 ] = block;
1320
1321 return loadBigBlocks(blocks, data, maxlen);
1322 }
1323
1324 // return number of bytes which has been read
1325 unsigned long libwps_OLE::IStorage::loadSmallBlocks(std::vector<unsigned long> const &blocks,
1326 unsigned char *data, unsigned long maxlen)
1327 {
1328 // sentinel
1329 if (!data || blocks.size() < 1 || maxlen == 0) return 0;
1330
1331 // our own local buffer
1332 std::vector<unsigned char> tmpBuf(m_bbat.m_blockSize);
1333
1334 // read small block one by one
1335 unsigned long bytes = 0;
1336 for (unsigned long i=0; (i<blocks.size()) && (bytes<maxlen); i++)
1337 {
1338 unsigned long block = blocks[i];
1339
1340 // find where the small-block exactly is
1341 unsigned long pos = block * m_sbat.m_blockSize;
1342 unsigned long bbindex = pos / m_bbat.m_blockSize;
1343 if (bbindex >= m_sb_blocks.size()) break;
1344
1345 unsigned long readData=loadBigBlock(m_sb_blocks[ bbindex ], &tmpBuf[0], m_bbat.m_blockSize);
1346
1347 // copy the data
1348 unsigned long offset = pos % m_bbat.m_blockSize;
1349 unsigned long p = (maxlen-bytes < m_bbat.m_blockSize-offset) ? maxlen-bytes : m_bbat.m_blockSize-offset;
1350 // sanety check
1351 if (m_sbat.m_blockSize<p) p=m_sbat.m_blockSize;
1352 if (readData < p) p = readData;
1353 memcpy(data + bytes, &tmpBuf[offset], p);
1354 bytes += p;
1355 }
1356
1357 return bytes;
1358 }
1359
1360 unsigned long libwps_OLE::IStorage::loadSmallBlock(unsigned long block,
1361 unsigned char *data, unsigned long maxlen)
1362 {
1363 // sentinel
1364 if (!data) return 0;
1365
1366 // wraps call for loadSmallBlocks
1367 std::vector<unsigned long> blocks;
1368 blocks.resize(1);
1369 blocks.assign(1, block);
1370
1371 return loadSmallBlocks(blocks, data, maxlen);
1372 }
1373
1374 // =========== OStorage ==========
1375 bool libwps_OLE::OStorage::addDirectory(std::string const &dir)
1376 {
1377 DirEntry *e=createEntry(dir);
1378 if (!e) return false;
1379
1380 e->m_type=1;
1381 return true;
1382 }
1383
1384 bool libwps_OLE::OStorage::addStream(std::string const &name, unsigned char const *buffer, unsigned long len)
1385 {
1386 DirEntry *e=createEntry(name);
1387 if (!e) return false;
1388
1389 if (!len)
1390 {
1391 WPS_DEBUG_MSG(("librevengeOLE::OStorage::addStream: call to create an empty file!!!\n"));
1392 return true;
1393 }
1394 e->m_start = insertData(buffer, len, useBigBlockFor(len));
1395 e->m_size = len;
1396 return true;
1397 }
1398
1399 bool libwps_OLE::OStorage::updateToSave()
1400 {
1401 unsigned long dirSize = m_dirtree.saveSize();
1402 DirEntry *rEntry = m_dirtree.entry(0);
1403 if (!dirSize || !rEntry)
1404 {
1405 WPS_DEBUG_MSG(("librevengeOLE::OStorage::updateToSave: can not find dir tree size!!!\n"));
1406 return false;
1407 }
1408 m_dirtree.setInRedBlackTreeForm();
1409
1410 std::vector<unsigned char> buffer;
1411 // first add the small block allocation table
1412 unsigned long sbatSize = m_sbat.saveSize();
1413 if (!sbatSize)
1414 m_header.m_start_sbat = Bat;
1415 else
1416 {
1417 // FIXME: set m_header.m_start_sbat
1418 buffer.resize(sbatSize);
1419 m_sbat.save(&buffer[0]);
1420 m_header.m_num_sbat = unsigned(sbatSize+511)/512;
1421 m_header.m_start_sbat = insertData(&buffer[0], sbatSize, true, unsigned(Eof));
1422 if (m_sb_blocks.size())
1423 {
1424 rEntry->m_start = unsigned(m_sb_blocks[0]);
1425 m_bbat.setChain(m_sb_blocks, unsigned(Eof));
1426 }
1427 rEntry->m_size = 64*m_num_sbat;
1428 }
1429 // then add dirtree
1430 buffer.resize(dirSize);
1431 m_dirtree.save(&buffer[0]);
1432 m_header.m_start_dirent=insertData(&buffer[0], dirSize, true, unsigned(Eof));
1433
1434 // now update the big alloc table to add size for self and for the meta data
1435 unsigned numBBlock = m_num_bbat;
1436 if (numBBlock==0)
1437 {
1438 WPS_DEBUG_MSG(("librevengeOLE::OStorage::updateToSave: can not find any big block!!!\n"));
1439 return false;
1440 }
1441 unsigned numBAlloc = (numBBlock+127)/128;
1442 unsigned numMAlloc = (numBAlloc+17)/127; // ie. 109->0, 110->1, ...
1443 while (numBBlock+numBAlloc+numMAlloc > numBAlloc*128)
1444 {
1445 numBAlloc++;
1446 numMAlloc = (numBAlloc+17)/127;
1447 }
1448
1449 std::vector<unsigned long> mainBlocks(numBAlloc);
1450 unsigned b = 0;
1451 for (b = 0; b < numBAlloc; b++)
1452 {
1453 mainBlocks[b]=numBBlock+b;
1454 m_bbat.set(mainBlocks[b], unsigned(Bat));
1455 }
1456 if (numMAlloc)
1457 {
1458 for (b = 0; b < numMAlloc; b++)
1459 m_bbat.set(numBBlock+numBAlloc+b, unsigned(MetaBat));
1460 }
1461
1462 // now add the small block allocation table
1463 unsigned long bbatSize = m_bbat.saveSize();
1464 if (bbatSize)
1465 {
1466 buffer.resize(bbatSize);
1467 m_bbat.save(&buffer[0]);
1468 insertData(&buffer[0], bbatSize, true, unsigned(Bat));
1469 }
1470
1471 for (b = 0; b < numBAlloc; b++)
1472 {
1473 if (b >= 109)
1474 break;
1475 m_header.m_blocks_bbat[b]=mainBlocks[b];
1476 }
1477 if (numMAlloc)
1478 {
1479 buffer.resize(numMAlloc*512,0);
1480 size_t wPos=0;
1481 for (b=109; b < numBAlloc; b++)
1482 {
1483 if ((wPos%512)==508)
1484 {
1485 writeU32(&buffer[wPos],numBBlock+numBAlloc+(wPos+4)/512);
1486 wPos+=4;
1487 }
1488 writeU32(&buffer[wPos],mainBlocks[b]);
1489 wPos+=4;
1490 }
1491 while (wPos%512)
1492 {
1493 writeU32(&buffer[wPos], Avail);
1494 wPos+=4;
1495 }
1496 m_header.m_start_mbat = insertData(reinterpret_cast<unsigned char const *>(buffer.data()), 512*numMAlloc, true, unsigned(Eof));
1497 m_header.m_start_mbat = numBBlock+numBAlloc;
1498 }
1499 m_header.m_num_bat = (m_num_bbat+127)/128;
1500 m_header.m_num_mbat = numMAlloc;
1501
1502 m_data.resize((m_num_bbat+1)*512,0);
1503 // save the header
1504 m_header.save(&m_data[0]);
1505 return true;
1506 }
1507
1508 unsigned libwps_OLE::OStorage::insertData(unsigned char const *buffer, unsigned long len, bool useBigBlock, unsigned end)
1509 {
1510 if (buffer==nullptr || len == 0)
1511 {
1512 WPS_DEBUG_MSG(("librevengeOLE::OStorage::insertData: call with no data\n"));
1513 return 0;
1514 }
1515
1516 unsigned long bSize = getMaximumSize(useBigBlock);
1517 size_t nBlock = ((len+bSize-1)/bSize);
1518 std::vector<unsigned long> chain;
1519 for (size_t b=0; b < nBlock; b++)
1520 {
1521 unsigned block=useBigBlock ? newBBlock() : newSBlock();
1522 chain.push_back(block);
1523 size_t wPos = getDataAddress(block, useBigBlock);
1524 unsigned long wSize = len > bSize ? bSize : len;
1525 memcpy(&m_data[wPos], &buffer[0], wSize);
1526 buffer += bSize;
1527 len -= wSize;
1528 }
1529 if (useBigBlock)
1530 m_bbat.setChain(chain, end);
1531 else
1532 m_sbat.setChain(chain, end);
1533 return unsigned(chain[0]);
1534 }
1535
1536 // =========== IStream ==========
1537
1538 libwps_OLE::IStream::IStream(libwps_OLE::IStorage *s, std::string const &name) :
1539 m_iStorage(s),
1540 m_size(0),
1541 m_name(name),
1542 m_blocks(),
1543 m_pos(0),
1544 m_data()
1545 {
1546 if (!name.length() || !m_iStorage) return;
1547 m_iStorage->load();
1548 DirEntry *entry = m_iStorage->entry(name);
1549 if (!entry)
1550 return;
1551 if (entry->is_dir())
1552 {
1553 createOleFromDirectory(s, name);
1554 return;
1555 }
1556
1557 m_size = entry->m_size;
1558
1559 unsigned blockSize = 0;
1560
1561 if (m_iStorage->use_big_block_for(entry->m_size))
1562 {
1563 m_blocks = m_iStorage->m_bbat.follow(entry->m_start);
1564 blockSize = m_iStorage->m_bbat.m_blockSize;
1565 }
1566 else
1567 {
1568 m_blocks = m_iStorage->m_sbat.follow(entry->m_start);
1569 blockSize = m_iStorage->m_sbat.m_blockSize;
1570 }
1571
1572 // sanity check of stream size
1573 const auto maxSize = unsigned(blockSize * m_blocks.size());
1574 if (m_size > maxSize)
1575 {
1576 WPS_DEBUG_MSG(("libwps_OLE::IStream::IStream: size %lu is wrong, using an approximated value %u\n", m_size, maxSize));
1577 m_size = maxSize;
1578 entry->m_size = m_size;
1579 }
1580 }
1581
1582 unsigned long libwps_OLE::IStream::readData(unsigned long pos, unsigned char *data, unsigned long maxlen)
1583 {
1584 // sanity checks
1585 if (!data || (maxlen == 0) || static_cast<unsigned long>(m_data.size()) != m_size || !m_size)
1586 return 0;
1587
1588 if (pos >= m_size)
1589 return 0;
1590 unsigned long count = m_size - pos;
1591 if (count > maxlen) count = maxlen;
1592 memcpy(data, &m_data[size_t(pos)], count);
1593 return count;
1594 }
1595
1596 unsigned long libwps_OLE::IStream::readUsingStorage(unsigned long pos, unsigned char *data, unsigned long maxlen)
1597 {
1598 // sanity checks
1599 if (!data || (maxlen == 0) || !m_iStorage || !m_size) return 0;
1600
1601 unsigned long totalbytes = 0;
1602
1603 if (!m_iStorage->use_big_block_for(size()))
1604 {
1605 // small file
1606 unsigned sBlockSize = m_iStorage->m_sbat.m_blockSize;
1607 unsigned long index = pos / sBlockSize;
1608
1609 if (index >= m_blocks.size()) return 0;
1610
1611 std::vector<unsigned char> buf(sBlockSize);
1612 unsigned long offset = pos % sBlockSize;
1613 while (totalbytes < maxlen)
1614 {
1615 if (index >= m_blocks.size()) break;
1616 m_iStorage->loadSmallBlock(m_blocks[index], &buf[0], m_iStorage->m_bbat.m_blockSize);
1617 unsigned long count = sBlockSize - offset;
1618 if (count > maxlen-totalbytes) count = maxlen-totalbytes;
1619 memcpy(data+totalbytes, &buf[offset], count);
1620 totalbytes += count;
1621 offset = 0;
1622 index++;
1623 }
1624 }
1625 else
1626 {
1627 // big file
1628 unsigned bBlockSize = m_iStorage->m_bbat.m_blockSize;
1629 unsigned long index = pos / bBlockSize;
1630
1631 if (index >= m_blocks.size()) return 0;
1632
1633 std::vector<unsigned char> buf(bBlockSize);
1634 unsigned long offset = pos % bBlockSize;
1635 while (totalbytes < maxlen)
1636 {
1637 if (index >= m_blocks.size()) break;
1638 m_iStorage->loadBigBlock(m_blocks[index], &buf[0], bBlockSize);
1639 unsigned long count = bBlockSize - offset;
1640 if (count > maxlen-totalbytes) count = maxlen-totalbytes;
1641 memcpy(data+totalbytes, &buf[offset], count);
1642 totalbytes += count;
1643 index++;
1644 offset = 0;
1645 }
1646 }
1647
1648 return totalbytes;
1649 }
1650
1651 bool libwps_OLE::IStream::createOleFromDirectory(IStorage *io, std::string const &name)
1652 {
1653 // sanety check
1654 if (!name.length() || !io) return false;
1655 m_iStorage->load();
1656 DirEntry *entry = io->entry(name);
1657 if (!entry || !entry->is_dir()) return false;
1658
1659 unsigned index = io->index(name);
1660 if (index==libwps_OLE::NotFound) return false;
1661 std::vector<std::string> nodes=io->getSubStreamList(index, true);
1662 if (nodes.size() <= 1)
1663 {
1664 WPS_DEBUG_MSG(("libwps_OLE::IStream::createOleFromDirectory: can not find any child for %s\n", name.c_str()));
1665 return false;
1666 }
1667 try
1668 {
1669 std::string dir(name);
1670 size_t len=dir.length();
1671 if (len && dir[len-1]=='/') dir.resize(len-1);
1672 std::vector<unsigned char> buffer;
1673
1674 // try to compute a minimum data size
1675 unsigned long minimalSize = 0;
1676 size_t l=0;
1677 for (l=0; l < nodes.size(); l++)
1678 {
1679 std::string fullName=dir+nodes[l];
1680 entry=io->entry(fullName);
1681 if (!entry || !entry->m_valid)
1682 continue;
1683 minimalSize += 128; // DirEntry
1684 if (!entry->is_dir() && entry->m_size < 50000000)
1685 minimalSize+=((entry->m_size+63)/64)*64;
1686 }
1687
1688 libwps_OLE::OStorage storage(minimalSize);
1689 storage.setRevision(io->revision());
1690 if (!io->hasRootTypePc())
1691 storage.setRootType(false);
1692 for (l=0; l < nodes.size(); l++)
1693 {
1694 std::string fullName=dir+nodes[l];
1695 entry=io->entry(fullName);
1696 if (!entry)
1697 {
1698 WPS_DEBUG_MSG(("libwps_OLE::IStream::createOleFromDirectory: can not find child for %s\n", fullName.c_str()));
1699 continue;
1700 }
1701 if (entry->is_dir())
1702 {
1703 if (entry->m_child == libwps_OLE::DirEntry::End)
1704 storage.addDirectory(nodes[l]);
1705 continue;
1706 }
1707 libwps_OLE::IStream leafStream(io,fullName);
1708 unsigned long sz=leafStream.size();
1709 bool ok = true;
1710 if (sz)
1711 {
1712 // a test because empty file are rare but seems to exists
1713 buffer.resize(sz);
1714 ok = leafStream.read(&buffer[0], sz) == sz;
1715 if (ok)
1716 ok=storage.addStream(nodes[l], &buffer[0], sz);
1717 }
1718 else
1719 {
1720 ok=storage.addStream(nodes[l], nullptr, 0);
1721 }
1722 if (!ok)
1723 {
1724 WPS_DEBUG_MSG(("libwps_OLE::IStream::createOleFromDirectory: can not read %s\n", fullName.c_str()));
1725 return false;
1726 }
1727 }
1728 // finally try to update the storage info
1729 std::vector<std::string> resNodes=storage.getSubStreamList(0, true);
1730 for (l=0; l < resNodes.size(); l++)
1731 {
1732 std::string fullName=dir+resNodes[l];
1733 entry=io->entry(fullName);
1734 if (!entry) continue;
1735 if (resNodes[l].length())
1736 storage.setInformation(resNodes[l], entry->m_info);
1737 }
1738
1739 // retrieve the data
1740 if (!storage.getFileData(m_data))
1741 {
1742 m_data.resize(0);
1743 return false;
1744 }
1745 // ok, we can update size
1746 m_size = static_cast<unsigned long>(m_data.size());
1747 return true;
1748 }
1749 catch (...)
1750 {
1751 }
1752 return false;
1753 }
1754
1755 namespace libwps_OLE
1756 {
1757 //////////////////////////////////////////////////
1758 /** internal class used to create a RVNGInputStream from an OLE file */
1759 class WPSOLEStream final: public librevenge::RVNGInputStream
1760 {
1761 public:
1762 //! constructor
1763 explicit WPSOLEStream(RVNGInputStreamPtr &input)
1764 : m_input(input)
1765 , m_streamNameList()
1766 {
1767 if (!m_input) return;
1768 IStorage storage(m_input.get());
1769 if (storage.isStructured())
1770 {
1771 m_streamNameList=storage.getSubStreamNamesList();
1772 // time to do some cleaning ( remove ^A, ^B, ... )
1773 for (auto &re : m_streamNameList)
1774 {
1775 std::string str=re, finalStr("");
1776 for (char s : str)
1777 if (s>=32)
1778 finalStr+=s;
1779 re=finalStr;
1780 }
1781 }
1782 }
1783 //! destructor
1784 ~WPSOLEStream() final
1785 {
1786 }
1787 /**! reads numbytes data.
1788
1789 * \return a pointer to the read elements
1790 */
1791 const unsigned char *read(unsigned long, unsigned long &) final
1792 {
1793 return nullptr;
1794 }
1795 //! returns actual offset position
1796 long tell() final
1797 {
1798 return 0;
1799 }
1800 /*! \brief seeks to a offset position, from actual, beginning or ending position
1801 * \return 0 if ok
1802 */
1803 int seek(long, librevenge::RVNG_SEEK_TYPE) final
1804 {
1805 return 1;
1806 }
1807 //! returns true if we are at the end of the section/file
1808 bool isEnd() final
1809 {
1810 return true;
1811 }
1812
1813 /** returns true if the stream is ole*/
1814 bool isStructured() final
1815 {
1816 return !m_streamNameList.empty();
1817 }
1818 /** returns the number of sub streams.*/
1819 unsigned subStreamCount() final
1820 {
1821 return unsigned(m_streamNameList.size());
1822 }
1823 /** returns the ith sub streams name*/
1824 const char *subStreamName(unsigned id) final
1825 {
1826 if (id>=unsigned(m_streamNameList.size()))
1827 return nullptr;
1828 return m_streamNameList[size_t(id)].c_str();
1829 }
1830 /** returns true if a substream with name exists*/
1831 bool existsSubStream(const char *name) final
1832 {
1833 for (const auto &i : m_streamNameList)
1834 {
1835 if (i == name)
1836 return true;
1837 }
1838 return false;
1839 }
1840 /** return a new stream for a ole zone */
1841 librevenge::RVNGInputStream *getSubStreamByName(const char *name) final;
1842 /** return a new stream for a ole zone */
1843 librevenge::RVNGInputStream *getSubStreamById(unsigned id) final
1844 {
1845 return getSubStreamByName(subStreamName(id));
1846 }
1847
1848 protected:
1849 //! the main input
1850 RVNGInputStreamPtr m_input;
1851 //! return the name list
1852 std::vector<std::string> m_streamNameList;
1853 private:
1854 WPSOLEStream(const WPSOLEStream &) = delete; // copy is not allowed
1855 WPSOLEStream &operator=(const WPSOLEStream &) = delete; // assignment is not allowed
1856 };
1857
1858 librevenge::RVNGInputStream *WPSOLEStream::getSubStreamByName(const char *name)
1859 {
1860 if (!isStructured())
1861 return nullptr;
1862
1863 IStorage storage(m_input.get());
1864 IStream tmpStream(&storage, name);
1865 if (storage.m_result != storage.Ok || !tmpStream.size())
1866 return nullptr;
1867
1868 std::vector<unsigned char> buf(tmpStream.size());
1869 unsigned long tmpLength;
1870 tmpLength = tmpStream.read(&buf[0], tmpStream.size());
1871
1872 // sanity check
1873 if (tmpLength != tmpStream.size())
1874 /* something went wrong here and we do not trust the
1875 resulting buffer */
1876 return nullptr;
1877
1878 return new WPSStringStream(&buf[0], unsigned(tmpLength));
1879 }
1880
1881 RVNGInputStreamPtr getOLEInputStream(RVNGInputStreamPtr input)
1882 {
1883 RVNGInputStreamPtr ole=std::make_shared<WPSOLEStream>(input);
1884 if (!ole->isStructured())
1885 return RVNGInputStreamPtr();
1886 return ole;
1887 }
1888
1889 }
1890 /* vim:set shiftwidth=4 softtabstop=4 noexpandtab: */