Debian Codegraph @

src/lib/QXPMacFileParser.cpp

raw
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /*
3 * This file is part of the libqxp project.
4 *
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 */
9
10 #include "QXPMacFileParser.h"
11
12 #include <cmath>
13 #include <cstring>
14 #include <limits>
15 #include <map>
16 #include <vector>
17
18 #include "QXPMemoryStream.h"
19 #include "libqxp_utils.h"
20
21 namespace libqxp
22 {
23
24 /*! \class MWAWInputStream
25 * \brief Internal class used to read the file stream
26 * Internal class used to read the file stream,
27 * this class adds some usefull functions to the basic librevenge::RVNGInputStream:
28 * - read number (int8, int16, int32) in low or end endian
29 * - selection of a section of a stream
30 * - read block of data
31 * - interface with modified librevenge::RVNGOLEStream
32 */
33 class MWAWInputStream
34 {
35 public:
36 /*!\brief creates a stream with given endian
37 * \param input the given input
38 * \param inverted must be set to true for pc doc and ole part and to false for mac doc
39 */
40 MWAWInputStream(std::shared_ptr<librevenge::RVNGInputStream> input, bool inverted);
41
42 /*!\brief creates a stream with given endian from an existing input
43 *
44 * Note: this functions does not delete input
45 */
46 MWAWInputStream(librevenge::RVNGInputStream *input, bool inverted, bool checkCompression=false);
47 //! destructor
48 ~MWAWInputStream();
49
50 //! returns the basic librevenge::RVNGInputStream
51 std::shared_ptr<librevenge::RVNGInputStream> input()
52 {
53 return m_stream;
54 }
55 //! returns a new input stream corresponding to a librevenge::RVNGBinaryData
56 static std::shared_ptr<MWAWInputStream> get(librevenge::RVNGBinaryData const &data, bool inverted);
57
58 //! returns the endian mode (see constructor)
59 bool readInverted() const
60 {
61 return m_inverseRead;
62 }
63 //! sets the endian mode
64 void setReadInverted(bool newVal)
65 {
66 m_inverseRead = newVal;
67 }
68 //
69 // Position: access
70 //
71
72 /*! \brief seeks to a offset position, from actual, beginning or ending position
73 * \return 0 if ok
74 * \sa pushLimit popLimit
75 */
76 int seek(long offset, librevenge::RVNG_SEEK_TYPE seekType);
77 //! returns actual offset position
78 long tell();
79 //! returns the stream size
80 long size() const
81 {
82 return m_streamSize;
83 }
84 //! checks if a position is or not a valid file position
85 bool checkPosition(long pos) const
86 {
87 if (pos < 0) return false;
88 if (m_readLimit > 0 && pos > m_readLimit) return false;
89 return pos<=m_streamSize;
90 }
91 //! returns true if we are at the end of the section/file
92 bool isEnd();
93
94 /*! \brief defines a new section in the file (from actualPos to newLimit)
95 * next call of seek, tell, atEos, ... will be restrained to this section
96 */
97 void pushLimit(long newLimit)
98 {
99 m_prevLimits.push_back(m_readLimit);
100 m_readLimit = newLimit > m_streamSize ? m_streamSize : newLimit;
101 }
102 //! pops a section defined by pushLimit
103 void popLimit()
104 {
105 if (m_prevLimits.size())
106 {
107 m_readLimit = m_prevLimits.back();
108 m_prevLimits.pop_back();
109 }
110 else m_readLimit = -1;
111 }
112
113 //
114 // get data
115 //
116
117 //! returns a uint8, uint16, uint32 readed from actualPos
118 unsigned long readULong(int num)
119 {
120 return readULong(m_stream.get(), num, 0, m_inverseRead);
121 }
122 //! return a int8, int16, int32 readed from actualPos
123 long readLong(int num);
124 //! try to read a double of size 8: 1.5 bytes exponent, 6.5 bytes mantisse
125 bool readDouble8(double &res, bool &isNotANumber);
126 //! try to read a double of size 8: 6.5 bytes mantisse, 1.5 bytes exponent
127 bool readDoubleReverted8(double &res, bool &isNotANumber);
128 //! try to read a double of size 10: 2 bytes exponent, 8 bytes mantisse
129 bool readDouble10(double &res, bool &isNotANumber);
130
131 /**! reads numbytes data, WITHOUT using any endian or section consideration
132 * \return a pointer to the read elements
133 */
134 const uint8_t *read(size_t numBytes, unsigned long &numBytesRead);
135 /*! \brief internal function used to read num byte,
136 * - where a is the previous read data
137 */
138 static unsigned long readULong(librevenge::RVNGInputStream *stream, int num, unsigned long a, bool inverseRead);
139
140 //! reads a librevenge::RVNGBinaryData with a given size in the actual section/file
141 bool readDataBlock(long size, librevenge::RVNGBinaryData &data);
142 //! reads a librevenge::RVNGBinaryData from actPos to the end of the section/file
143 bool readEndDataBlock(librevenge::RVNGBinaryData &data);
144
145 //
146 // OLE/Zip access
147 //
148
149 //! return true if the stream is ole
150 bool isStructured();
151 //! returns the number of substream
152 unsigned subStreamCount();
153 //! returns the name of the i^th substream
154 std::string subStreamName(unsigned id);
155
156 //! return a new stream for a ole zone
157 std::shared_ptr<MWAWInputStream> getSubStreamByName(std::string const &name);
158 //! return a new stream for a ole zone
159 std::shared_ptr<MWAWInputStream> getSubStreamById(unsigned id);
160
161 //
162 // Finder Info access
163 //
164 /** returns the finder info type and creator (if known) */
165 bool getFinderInfo(std::string &type, std::string &creator) const
166 {
167 if (!m_fInfoType.length() || !m_fInfoCreator.length())
168 {
169 type = creator = "";
170 return false;
171 }
172 type = m_fInfoType;
173 creator = m_fInfoCreator;
174 return true;
175 }
176
177 //
178 // Resource Fork access
179 //
180
181 /** returns true if the data fork block exists */
182 bool hasDataFork() const
183 {
184 return bool(m_stream);
185 }
186 /** returns true if the resource fork block exists */
187 bool hasResourceFork() const
188 {
189 return bool(m_resourceFork);
190 }
191 /** returns the resource fork if find */
192 std::shared_ptr<MWAWInputStream> getResourceForkStream()
193 {
194 return m_resourceFork;
195 }
196
197
198 protected:
199 //! update the stream size ( must be called in the constructor )
200 void updateStreamSize();
201 //! internal function used to read a byte
202 static uint8_t readU8(librevenge::RVNGInputStream *stream);
203
204 //! unbinhex the data in the file is a BinHex 4.0 file of a mac file
205 bool unBinHex();
206 //! unzip the data in the file is a zip file of a mac file
207 bool unzipStream();
208 //! check if some stream are in MacMIME format, if so de MacMIME
209 bool unMacMIME();
210 //! de MacMIME an input stream
211 bool unMacMIME(MWAWInputStream *input,
212 std::shared_ptr<librevenge::RVNGInputStream> &dataInput,
213 std::shared_ptr<librevenge::RVNGInputStream> &rsrcInput) const;
214 //! check if a stream is an internal merge stream
215 bool unsplitInternalMergeStream();
216
217 private:
218 MWAWInputStream(MWAWInputStream const &orig) = delete;
219 MWAWInputStream &operator=(MWAWInputStream const &orig) = delete;
220
221 protected:
222 //! the initial input
223 std::shared_ptr<librevenge::RVNGInputStream> m_stream;
224 //! the stream size
225 long m_streamSize;
226
227 //! actual section limit (-1 if no limit)
228 long m_readLimit;
229 //! list of previous limits
230 std::vector<long> m_prevLimits;
231
232 //! finder info type
233 mutable std::string m_fInfoType;
234 //! finder info type
235 mutable std::string m_fInfoCreator;
236 //! the resource fork
237 std::shared_ptr<MWAWInputStream> m_resourceFork;
238 //! big or normal endian
239 bool m_inverseRead;
240 };
241
242 MWAWInputStream::MWAWInputStream(std::shared_ptr<librevenge::RVNGInputStream> inp, bool inverted)
243 : m_stream(inp), m_streamSize(0), m_readLimit(-1), m_prevLimits(),
244 m_fInfoType(""), m_fInfoCreator(""), m_resourceFork(), m_inverseRead(inverted)
245 {
246 updateStreamSize();
247 }
248
249 MWAWInputStream::MWAWInputStream(librevenge::RVNGInputStream *inp, bool inverted, bool checkCompression)
250 : m_stream(), m_streamSize(0), m_readLimit(-1), m_prevLimits(),
251 m_fInfoType(""), m_fInfoCreator(""), m_resourceFork(), m_inverseRead(inverted)
252 {
253 if (!inp) return;
254
255 m_stream = std::shared_ptr<librevenge::RVNGInputStream>(inp, QXPDummyDeleter());
256 updateStreamSize();
257 if (!checkCompression)
258 return;
259
260 // first check if the file is "local" structure one
261 if (unsplitInternalMergeStream())
262 updateStreamSize();
263 // then check the zip format
264 if (unzipStream())
265 updateStreamSize();
266
267 // then check if the data are in binhex format
268 if (unBinHex())
269 updateStreamSize();
270
271 // now check for MacMIME format in m_stream or in m_resourceFork
272 if (unMacMIME())
273 updateStreamSize();
274 if (m_stream)
275 seek(0, librevenge::RVNG_SEEK_SET);
276 if (m_resourceFork)
277 m_resourceFork->seek(0, librevenge::RVNG_SEEK_SET);
278 }
279
280 MWAWInputStream::~MWAWInputStream()
281 {
282 }
283
284 std::shared_ptr<MWAWInputStream> MWAWInputStream::get(librevenge::RVNGBinaryData const &data, bool inverted)
285 {
286 std::shared_ptr<MWAWInputStream> res;
287 if (!data.size())
288 return res;
289 librevenge::RVNGInputStream *dataStream = const_cast<librevenge::RVNGInputStream *>(data.getDataStream());
290 if (!dataStream)
291 {
292 QXP_DEBUG_MSG(("MWAWInputStream::get: can not retrieve a librevenge::RVNGInputStream\n"));
293 return res;
294 }
295 res.reset(new MWAWInputStream(dataStream, inverted));
296 if (res && res->size()>=long(data.size()))
297 {
298 res->seek(0, librevenge::RVNG_SEEK_SET);
299 return res;
300 }
301 QXP_DEBUG_MSG(("MWAWInputStream::get: the final stream seems bad\n"));
302 res.reset();
303 return res;
304 }
305
306 void MWAWInputStream::updateStreamSize()
307 {
308 if (!m_stream)
309 m_streamSize=0;
310 else
311 {
312 long actPos = tell();
313 m_stream->seek(0, librevenge::RVNG_SEEK_END);
314 m_streamSize=tell();
315 m_stream->seek(actPos, librevenge::RVNG_SEEK_SET);
316 }
317 }
318
319 const uint8_t *MWAWInputStream::read(size_t numBytes, unsigned long &numBytesRead)
320 {
321 if (!hasDataFork())
322 throw FileAccessError();
323 return m_stream->read(numBytes, numBytesRead);
324 }
325
326 long MWAWInputStream::tell()
327 {
328 if (!hasDataFork())
329 return 0;
330 return m_stream->tell();
331 }
332
333 int MWAWInputStream::seek(long offset, librevenge::RVNG_SEEK_TYPE seekType)
334 {
335 if (!hasDataFork())
336 {
337 if (offset == 0)
338 return 0;
339 throw FileAccessError();
340 }
341
342 if (seekType == librevenge::RVNG_SEEK_CUR)
343 offset += tell();
344 else if (seekType==librevenge::RVNG_SEEK_END)
345 offset += m_streamSize;
346
347 if (offset < 0)
348 offset = 0;
349 if (m_readLimit > 0 && offset > long(m_readLimit))
350 offset = long(m_readLimit);
351 if (offset > size())
352 offset = size();
353
354 return m_stream->seek(offset, librevenge::RVNG_SEEK_SET);
355 }
356
357 bool MWAWInputStream::isEnd()
358 {
359 if (!hasDataFork())
360 return true;
361 long pos = m_stream->tell();
362 if (m_readLimit > 0 && pos >= m_readLimit) return true;
363 if (pos >= size()) return true;
364
365 return m_stream->isEnd();
366 }
367
368 unsigned long MWAWInputStream::readULong(librevenge::RVNGInputStream *stream, int num, unsigned long a, bool inverseRead)
369 {
370 if (!stream || num <= 0 || stream->isEnd()) return a;
371 if (num > 8) // reading more than 8 bytes does not make any sense, ...
372 {
373 QXP_DEBUG_MSG(("MWAWInputStream::readULong: argh called with %d bytes, resets it to 8 bytes\n", num));
374 num = 8;
375 }
376 else if (num > 4) // normally, must be (not recursively) called with 1, 2, 4 bytes, so...
377 {
378 QXP_DEBUG_MSG(("MWAWInputStream::readULong: argh called with %d bytes\n", num));
379 }
380 if (inverseRead)
381 {
382 unsigned long val = readU8(stream);
383 return val + (readULong(stream, num-1, 0, inverseRead) << 8);
384 }
385 switch (num)
386 {
387 case 4:
388 case 2:
389 case 1:
390 {
391 unsigned long numBytesRead;
392 uint8_t const *p = stream->read(static_cast<unsigned long>(num), numBytesRead);
393 if (!p || int(numBytesRead) != num)
394 return 0;
395 switch (num)
396 {
397 case 4:
398 return static_cast<unsigned long>(p[3])|(static_cast<unsigned long>(p[2])<<8)|
399 (static_cast<unsigned long>(p[1])<<16)|(static_cast<unsigned long>(p[0])<<24)|((a<<16)<<16);
400 case 2:
401 return (static_cast<unsigned long>(p[1]))|(static_cast<unsigned long>(p[0])<<8)|(a<<16);
402 case 1:
403 return (static_cast<unsigned long>(p[0]))|(a<<8);
404 default:
405 break;
406 }
407 break;
408 }
409 default:
410 return readULong(stream, num-1,(a<<8) + static_cast<unsigned long>(readU8(stream)), inverseRead);
411 }
412 return 0;
413 }
414
415 long MWAWInputStream::readLong(int num)
416 {
417 long v = long(readULong(num));
418 switch (num)
419 {
420 case 4:
421 return static_cast<int32_t>(v);
422 case 2:
423 return static_cast<int16_t>(v);
424 case 1:
425 return static_cast<int8_t>(v);
426 default:
427 break;
428 }
429
430 if ((v & long(0x1 << (num*8-1))) == 0) return v;
431 return v | long(0xFFFFFFFF << 8*num);
432 }
433
434 uint8_t MWAWInputStream::readU8(librevenge::RVNGInputStream *stream)
435 {
436 if (!stream)
437 return 0;
438 unsigned long numBytesRead;
439 uint8_t const *p = stream->read(sizeof(uint8_t), numBytesRead);
440
441 if (!p || numBytesRead != sizeof(uint8_t))
442 return 0;
443
444 return *p;
445 }
446
447 bool MWAWInputStream::readDouble8(double &res, bool &isNotANumber)
448 {
449 if (!m_stream) return false;
450 long pos=tell();
451 if (m_readLimit > 0 && pos+8 > m_readLimit) return false;
452 if (pos+8 > m_streamSize) return false;
453
454 isNotANumber=false;
455 res=0;
456 int mantExp=int(readULong(1));
457 int val=static_cast<int>(readULong(1));
458 int exp=(mantExp<<4)+(val>>4);
459 double mantisse=double(val&0xF)/16.;
460 double factor=1./16/256.;
461 for (int j = 0; j < 6; ++j, factor/=256)
462 mantisse+=double(readULong(1))*factor;
463 int sign = 1;
464 if (exp & 0x800)
465 {
466 exp &= 0x7ff;
467 sign = -1;
468 }
469 if (exp == 0)
470 {
471 if (mantisse <= 1.e-5 || mantisse >= 1-1.e-5)
472 return true;
473 // a Nan representation ?
474 return false;
475 }
476 if (exp == 0x7FF)
477 {
478 if (mantisse >= 1.-1e-5)
479 {
480 isNotANumber=true;
481 res=std::numeric_limits<double>::quiet_NaN();
482 return true; // ok 0x7FF and 0xFFF are nan
483 }
484 return false;
485 }
486 exp -= 0x3ff;
487 res = std::ldexp(1.+mantisse, exp);
488 if (sign == -1)
489 res *= -1.;
490 return true;
491 }
492
493 bool MWAWInputStream::readDouble10(double &res, bool &isNotANumber)
494 {
495 if (!m_stream) return false;
496 long pos=tell();
497 if (m_readLimit > 0 && pos+10 > m_readLimit) return false;
498 if (pos+10 > m_streamSize) return false;
499
500 int exp = static_cast<int>(readULong(2));
501 int sign = 1;
502 if (exp & 0x8000)
503 {
504 exp &= 0x7fff;
505 sign = -1;
506 }
507 exp -= 0x3fff;
508
509 isNotANumber=false;
510 unsigned long mantisse = static_cast<unsigned long>(readULong(4));
511 if ((mantisse & 0x80000001) == 0)
512 {
513 // unormalized number are not frequent, but can appear at least for date, ...
514 if (readULong(4) != 0)
515 seek(-4, librevenge::RVNG_SEEK_CUR);
516 else
517 {
518 if (exp == -0x3fff && mantisse == 0)
519 {
520 res=0;
521 return true; // ok zero
522 }
523 if (exp == 0x4000 && (mantisse & 0xFFFFFFL)==0) // ok Nan
524 {
525 isNotANumber = true;
526 res=std::numeric_limits<double>::quiet_NaN();
527 return true;
528 }
529 return false;
530 }
531 }
532 // or std::ldexp((total value)/double(0x80000000), exp);
533 res=std::ldexp(double(readULong(4)), exp-63)+std::ldexp(double(mantisse), exp-31);
534 if (sign == -1)
535 res *= -1.;
536 return true;
537 }
538
539 bool MWAWInputStream::readDoubleReverted8(double &res, bool &isNotANumber)
540 {
541 if (!m_stream) return false;
542 long pos=tell();
543 if (m_readLimit > 0 && pos+8 > m_readLimit) return false;
544 if (pos+8 > m_streamSize) return false;
545
546 isNotANumber=false;
547 res=0;
548 int bytes[6];
549 for (int i=0; i<6; ++i) bytes[i]=static_cast<int>(readULong(1));
550
551 int val=static_cast<int>(readULong(1));
552 int mantExp=int(readULong(1));
553 int exp=(mantExp<<4)+(val>>4);
554 double mantisse=double(val&0xF)/16.;
555 double factor=1./16./256.;
556 for (int j = 0; j < 6; ++j, factor/=256)
557 mantisse+=double(bytes[5-j])*factor;
558 int sign = 1;
559 if (exp & 0x800)
560 {
561 exp &= 0x7ff;
562 sign = -1;
563 }
564 if (exp == 0)
565 {
566 if (mantisse <= 1.e-5 || mantisse >= 1-1.e-5)
567 return true;
568 // a Nan representation ?
569 return false;
570 }
571 if (exp == 0x7FF)
572 {
573 if (mantisse >= 1.-1e-5)
574 {
575 isNotANumber=true;
576 res=std::numeric_limits<double>::quiet_NaN();
577 return true; // ok 0x7FF and 0xFFF are nan
578 }
579 return false;
580 }
581 exp -= 0x3ff;
582 res = std::ldexp(1.+mantisse, exp);
583 if (sign == -1)
584 res *= -1.;
585 return true;
586 }
587
588 ////////////////////////////////////////////////////////////
589 //
590 // BinHex 4.0
591 //
592 ////////////////////////////////////////////////////////////
593 bool MWAWInputStream::unBinHex()
594 {
595 if (!hasDataFork() || size() < 45)
596 return false;
597 // check header
598 seek(0, librevenge::RVNG_SEEK_SET);
599 unsigned long nRead;
600 char const *str=reinterpret_cast<char const *>(read(45, nRead));
601 if (str==0 || nRead!=45
602 || strncmp(str, "(This file must be converted with BinHex 4.0)", 45))
603 return false;
604 int numEOL = 0;
605 while (!isEnd())
606 {
607 char c = char(readLong(1));
608 if (c == '\n')
609 {
610 numEOL++;
611 continue;
612 }
613 seek(-1, librevenge::RVNG_SEEK_CUR);
614 break;
615 }
616 if (isEnd() || !numEOL || (char(readLong(1)))!= ':')
617 return false;
618
619 // first phase reconstruct the file
620 static char const binChar[65] = "!\"#$%&'()*+,-012345689@ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr";
621 std::map<unsigned char, int> binMap;
622 for (int i = 0; i < 64; i++) binMap[static_cast<unsigned char>(binChar[i])]=i;
623 bool endData = false;
624 int numActByte = 0, actVal = 0;
625 librevenge::RVNGBinaryData content;
626 bool findRepetitif = false;
627 while (1)
628 {
629 if (isEnd())
630 {
631 QXP_DEBUG_MSG(("MWAWInputStream::unBinHex: do not find ending ':' character\n"));
632 return false;
633 }
634 unsigned char c = static_cast<unsigned char>(readLong(1));
635 if (c == '\n') continue;
636 int readVal = 0;
637 if (c == ':')
638 endData = true;
639 else if (binMap.find(c) == binMap.end())
640 {
641 QXP_DEBUG_MSG(("MWAWInputStream::unBinHex: find unexpected char when decoding file\n"));
642 return false;
643 }
644 else
645 readVal = binMap.find(c)->second;
646 int wVal = -1;
647 if (numActByte==0)
648 actVal |= (readVal<<2);
649 else if (numActByte==2)
650 {
651 wVal = (actVal | readVal);
652 actVal = 0;
653 }
654 else if (numActByte==4)
655 {
656 wVal = actVal | ((readVal>>2)&0xF);
657 actVal = (readVal&0x3)<<6;
658 }
659 else if (numActByte==6)
660 {
661 wVal = actVal | ((readVal>>4)&0x3);
662 actVal = (readVal&0xf)<<4;
663 }
664 numActByte = (numActByte+6)%8;
665
666 int maxToWrite = (endData&&actVal) ? 2 : 1;
667 for (int wPos = 0; wPos < maxToWrite; wPos++)
668 {
669 int value = wPos ? actVal : wVal;
670 if (value == -1) continue;
671 if (!findRepetitif && value != 0x90)
672 {
673 content.append(static_cast<unsigned char>(value));
674 continue;
675 }
676 if (value == 0x90 && !findRepetitif)
677 {
678 findRepetitif = true;
679 continue;
680 }
681
682 if (value == 1 || value == 2)
683 {
684 QXP_DEBUG_MSG(("MWAWInputStream::unBinHex: find bad value after repetitif character\n"));
685 return false;
686 }
687 findRepetitif = false;
688 if (value == 0)
689 {
690 content.append(0x90);
691 continue;
692 }
693 if (content.size()==0)
694 {
695 QXP_DEBUG_MSG(("MWAWInputStream::unBinHex: find repetitif character in the first position\n"));
696 return false;
697 }
698 unsigned char lChar = content.getDataBuffer()[content.size()-1];
699 for (int i = 0; i < value-1; i++)
700 content.append(lChar);
701 continue;
702 }
703 if (endData) break;
704 }
705 if (findRepetitif)
706 {
707 QXP_DEBUG_MSG(("MWAWInputStream::unBinHex: find repetitif character in the last position\n"));
708 return false;
709 }
710 long contentSize=long(content.size());
711 if (contentSize < 27)
712 {
713 QXP_DEBUG_MSG(("MWAWInputStream::unBinHex: the content file is too small\n"));
714 return false;
715 }
716 librevenge::RVNGInputStream *contentInput=const_cast<librevenge::RVNGInputStream *>(content.getDataStream());
717 int fileLength = static_cast<int>(readU8(contentInput));
718 if (fileLength < 1 || fileLength > 64 || long(fileLength+21) > contentSize)
719 {
720 QXP_DEBUG_MSG(("MWAWInputStream::unBinHex: the file name size seems odd\n"));
721 return false;
722 }
723 contentInput->seek(fileLength+1, librevenge::RVNG_SEEK_CUR); // filename + version
724 // creator, type
725 std::string type(""), creator("");
726 for (int p = 0; p < 4; p++)
727 {
728 char c = char(readU8(contentInput));
729 if (c)
730 type += c;
731 }
732 for (int p = 0; p < 4; p++)
733 {
734 char c = char(readU8(contentInput));
735 if (c)
736 creator += c;
737 }
738 if (creator.length()==4 && type.length()==4)
739 {
740 m_fInfoType = type;
741 m_fInfoCreator = creator;
742 }
743 else if (creator.length() || type.length())
744 {
745 QXP_DEBUG_MSG(("MWAWInputStream::unBinHex: the file name size seems odd\n"));
746 }
747 contentInput->seek(2, librevenge::RVNG_SEEK_CUR); // skip flags
748 long dataLength = long(readULong(contentInput, 4, 0, false));
749 long rsrcLength = long(readULong(contentInput, 4, 0, false));
750 long pos = contentInput->tell()+2; // skip CRC
751 if (dataLength<0 || rsrcLength < 0 || (dataLength==0 && rsrcLength==0) ||
752 pos+dataLength+rsrcLength+4 > contentSize)
753 {
754 QXP_DEBUG_MSG(("MWAWInputStream::unBinHex: the data/rsrc fork size seems odd\n"));
755 return false;
756 }
757 // now read the rsrc and the data fork
758 if (rsrcLength && getResourceForkStream())
759 {
760 QXP_DEBUG_MSG(("MWAWInputStream::unBinHex: I already have a resource fork!!!!\n"));
761 }
762 else if (rsrcLength)
763 {
764 contentInput->seek(pos+dataLength+2, librevenge::RVNG_SEEK_SET);
765 unsigned long numBytesRead = 0;
766 const unsigned char *data =
767 contentInput->read(static_cast<unsigned long>(rsrcLength), numBytesRead);
768 if (numBytesRead != static_cast<unsigned long>(rsrcLength) || !data)
769 {
770 QXP_DEBUG_MSG(("MWAWInputStream::unBinHex: can not read the resource fork\n"));
771 }
772 else
773 {
774 std::shared_ptr<librevenge::RVNGInputStream> rsrc(new QXPMemoryStream(data, static_cast<unsigned int>(numBytesRead)));
775 m_resourceFork.reset(new MWAWInputStream(rsrc, false));
776 }
777 }
778 if (!dataLength)
779 m_stream.reset();
780 else
781 {
782 contentInput->seek(pos, librevenge::RVNG_SEEK_SET);
783 unsigned long numBytesRead = 0;
784 const unsigned char *data =
785 contentInput->read(static_cast<unsigned long>(dataLength), numBytesRead);
786 if (numBytesRead != static_cast<unsigned long>(dataLength) || !data)
787 {
788 QXP_DEBUG_MSG(("MWAWInputStream::unBinHex: can not read the data fork\n"));
789 return false;
790 }
791 m_stream.reset(new QXPMemoryStream(data, static_cast<unsigned int>(numBytesRead)));
792 }
793
794 return true;
795 }
796
797 ////////////////////////////////////////////////////////////
798 //
799 // Internal : if the main stream is a structured file, which
800 // contains a DataFork, a RsrcFork and a InfoFork or RsrcInfo
801 // stream, ...
802 //
803 ////////////////////////////////////////////////////////////
804 bool MWAWInputStream::unsplitInternalMergeStream()
805 {
806 if (!isStructured() || m_resourceFork || !m_stream->existsSubStream("DataFork"))
807 return false;
808 try
809 {
810 if (m_stream->subStreamCount()==2 && m_stream->existsSubStream("RsrcInfo"))
811 {
812 std::shared_ptr<librevenge::RVNGInputStream> newRsrcFork(m_stream->getSubStreamByName("RsrcInfo"));
813 if (newRsrcFork) // rsrcinfo must be a MacMIME file, it can not be empty
814 {
815 m_stream.reset(m_stream->getSubStreamByName("DataFork")); // empty data fork is rare, but possible
816 m_resourceFork.reset(new MWAWInputStream(newRsrcFork, m_inverseRead)); // rsrcinfo will be decoded by unMacMIME
817 }
818 else
819 {
820 QXP_DEBUG_MSG(("MWAWInputStream::unsplitInternalMergeStream: sorry, can not extract the data fork or the rsrc info fork\n"));
821 }
822 }
823 else if (m_stream->subStreamCount()==3 && m_stream->existsSubStream("RsrcFork") && m_stream->existsSubStream("InfoFork"))
824 {
825 std::shared_ptr<librevenge::RVNGInputStream> newRsrcFork(m_stream->getSubStreamByName("RsrcFork"));
826 if (newRsrcFork)
827 {
828 std::shared_ptr<librevenge::RVNGInputStream> newInfo(m_stream->getSubStreamByName("InfoFork"));
829 m_stream.reset(m_stream->getSubStreamByName("DataFork"));
830 m_resourceFork.reset(new MWAWInputStream(newRsrcFork, m_inverseRead));
831 // we must decode the information here
832 unsigned long numBytesRead = 0;
833 const unsigned char *data = newInfo ? newInfo->read(8, numBytesRead) : 0;
834 if (numBytesRead != 8 || !data)
835 {
836 QXP_DEBUG_MSG(("MWAWInputStream::unsplitInternalMergeStream: sorry, unknown file information size\n"));
837 }
838 else
839 {
840 bool ok = true;
841 std::string type(""), creator("");
842 for (int p = 0; p < 4; p++)
843 {
844 if (!data[p])
845 {
846 ok = false;
847 break;
848 }
849 type += char(data[p]);
850 }
851 for (int p = 4; ok && p < 8; p++)
852 {
853 if (!data[p])
854 {
855 ok = false;
856 break;
857 }
858 creator += char(data[p]);
859 }
860 if (ok)
861 {
862 m_fInfoType = type;
863 m_fInfoCreator = creator;
864 }
865 else if (type.length())
866 {
867 QXP_DEBUG_MSG(("MWAWInputStream::unsplitInternalMergeStream: can not read find info\n"));
868 }
869 }
870 }
871 else
872 {
873 QXP_DEBUG_MSG(("MWAWInputStream::unsplitInternalMergeStream: sorry, can not extract the data fork or the rsrc info fork\n"));
874 }
875 }
876 }
877 catch (...)
878 {
879 }
880 return false;
881 }
882
883 ////////////////////////////////////////////////////////////
884 //
885 // Zip
886 //
887 ////////////////////////////////////////////////////////////
888 bool MWAWInputStream::unzipStream()
889 {
890 if (!isStructured()) return false;
891 seek(0, librevenge::RVNG_SEEK_SET);
892 unsigned numStream=m_stream->subStreamCount();
893 std::vector<std::string> names;
894 for (unsigned n=0; n < numStream; ++n)
895 {
896 char const *nm=m_stream->subStreamName(n);
897 if (!nm) continue;
898 std::string name(nm);
899 if (name.empty() || name[name.length()-1]=='/') continue;
900 names.push_back(nm);
901 }
902 if (names.size() == 1)
903 {
904 // ok as the OLE file must have at least MN and MN0 OLE
905 m_stream.reset(m_stream->getSubStreamByName(names[0].c_str()));
906 return true;
907 }
908 if (names.size() != 2)
909 return false;
910 // test if XXX and ._XXX or __MACOSX/._XXX
911 if (names[1].length() < names[0].length())
912 {
913 std::string tmp = names[1];
914 names[1] = names[0];
915 names[0] = tmp;
916 }
917 size_t length = names[0].length();
918 std::string prefix("");
919 if (names[1].length()==length+2)
920 prefix = "._";
921 else if (names[1].length()==length+11)
922 prefix = "__MACOSX/._";
923 prefix += names[0];
924 if (prefix != names[1]) return false;
925 std::shared_ptr<librevenge::RVNGInputStream> rsrcPtr(m_stream->getSubStreamByName(names[1].c_str()));
926 m_resourceFork.reset(new MWAWInputStream(rsrcPtr, false));
927 m_stream.reset(m_stream->getSubStreamByName(names[0].c_str()));
928 return true;
929 }
930
931 ////////////////////////////////////////////////////////////
932 //
933 // MacMIME part
934 //
935 ////////////////////////////////////////////////////////////
936 bool MWAWInputStream::unMacMIME()
937 {
938 if (m_resourceFork)
939 {
940 std::shared_ptr<librevenge::RVNGInputStream> newDataInput, newRsrcInput;
941 bool ok = unMacMIME(m_resourceFork.get(), newDataInput, newRsrcInput);
942 if (ok && newDataInput)
943 {
944 QXP_DEBUG_MSG(("MWAWInputStream::unMacMIME: Argh!!! find data stream in the resource block\n"));
945 ok = false;
946 }
947 if (ok && newRsrcInput)
948 m_resourceFork.reset(new MWAWInputStream(newRsrcInput, false));
949 else if (ok)
950 m_resourceFork.reset();
951 }
952
953 if (m_stream)
954 {
955 std::shared_ptr<librevenge::RVNGInputStream> newDataInput, newRsrcInput;
956 bool ok = unMacMIME(this, newDataInput, newRsrcInput);
957 if (ok && !newDataInput)
958 {
959 QXP_DEBUG_MSG(("MWAWInputStream::unMacMIME: Argh!!! data block contains only resources\n"));
960 }
961 if (ok)
962 {
963 m_stream = newDataInput;
964 if (newRsrcInput)
965 {
966 if (m_resourceFork)
967 {
968 QXP_DEBUG_MSG(("MWAWInputStream::unMacMIME: Oops!!! find a second resource block, ignored\n"));
969 }
970 else
971 m_resourceFork.reset(new MWAWInputStream(newRsrcInput, false));
972 }
973 }
974 }
975 return true;
976 }
977
978 /* freely inspired from http://tools.ietf.org/html/rfc1740#appendix-A
979 */
980 bool MWAWInputStream::unMacMIME(MWAWInputStream *inp,
981 std::shared_ptr<librevenge::RVNGInputStream> &dataInput,
982 std::shared_ptr<librevenge::RVNGInputStream> &rsrcInput) const
983 {
984 dataInput.reset();
985 rsrcInput.reset();
986 if (!inp || !inp->hasDataFork() || inp->size()<26) return false;
987
988 try
989 {
990 inp->seek(0, librevenge::RVNG_SEEK_SET);
991 long magicNumber = long(inp->readULong(4));
992 if (magicNumber != 0x00051600 && magicNumber != 0x00051607)
993 return false;
994 long version = long(inp->readULong(4));
995 if (version != 0x20000)
996 {
997 QXP_DEBUG_MSG(("MWAWInputStream::unMacMIME: unknown version: %lx\n", static_cast<long unsigned int>(version)));
998 return false;
999 }
1000 inp->seek(16, librevenge::RVNG_SEEK_CUR); // filename
1001 long numEntries = long(inp->readULong(2));
1002 if (inp->checkPosition(inp->tell() + 12 * numEntries)) // minimal sanity check
1003 numEntries = (inp->size() - inp->tell()) / 12;
1004 if (inp->isEnd() || numEntries == 0)
1005 {
1006 QXP_DEBUG_MSG(("MWAWInputStream::unMacMIME: can not read number of entries\n"));
1007 return false;
1008 }
1009 #ifdef DEBUG
1010 static const char *what[] =
1011 {
1012 "", "Data", "Rsrc", "FileName", "Comment", "IconBW", "IconColor", "",
1013 "FileDates", "FinderInfo", "MacInfo", "ProDosInfo",
1014 "MSDosInfo", "AFPName", "AFPInfo", "AFPDirId"
1015 };
1016 #endif
1017 for (int i = 0; i < numEntries && !inp->isEnd(); i++)
1018 {
1019 long pos = inp->tell();
1020 int wh = static_cast<int>(inp->readULong(4));
1021 if (wh <= 0 || wh >= 16 || inp->isEnd())
1022 {
1023 QXP_DEBUG_MSG(("MWAWInputStream::unMacMIME: find unknown id: %d\n", wh));
1024 return false;
1025 }
1026 QXP_DEBUG_MSG(("MWAWInputStream::unMacMIME: find %s entry\n", what[wh]));
1027 if (wh > 2 && wh != 9)
1028 {
1029 inp->seek(8, librevenge::RVNG_SEEK_CUR);
1030 continue;
1031 }
1032 long entryPos = long(inp->readULong(4));
1033 unsigned long entrySize = inp->readULong(4);
1034 if (entrySize == 0)
1035 {
1036 QXP_DEBUG_MSG(("MWAWInputStream::unMacMIME: %s entry is empty\n", what[wh]));
1037 continue;
1038 }
1039 if (entryPos <= pos || entrySize == 0)
1040 {
1041 QXP_DEBUG_MSG(("MWAWInputStream::unMacMIME: find bad entry pos\n"));
1042 return false;
1043 }
1044 /* try to read the data */
1045 if (inp->seek(entryPos, librevenge::RVNG_SEEK_SET) != 0)
1046 {
1047 QXP_DEBUG_MSG(("MWAWInputStream::unMacMIME: can not seek entry pos %lx\n", static_cast<long unsigned int>(entryPos)));
1048 return false;
1049 }
1050 unsigned long numBytesRead = 0;
1051 const unsigned char *data = inp->read(entrySize, numBytesRead);
1052 if (numBytesRead != entrySize || !data)
1053 {
1054 QXP_DEBUG_MSG(("MWAWInputStream::unMacMIME: can not read %lX byte\n", static_cast<long unsigned int>(entryPos)));
1055 return false;
1056 }
1057 if (wh==1)
1058 dataInput.reset(new QXPMemoryStream(data, static_cast<unsigned int>(numBytesRead)));
1059 else if (wh==2)
1060 rsrcInput.reset(new QXPMemoryStream(data, static_cast<unsigned int>(numBytesRead)));
1061 else // the finder info
1062 {
1063 if (entrySize < 8)
1064 {
1065 QXP_DEBUG_MSG(("MWAWInputStream::unMacMIME: finder info size is odd\n"));
1066 }
1067 else
1068 {
1069 bool ok = true;
1070 std::string type(""), creator("");
1071 for (int p = 0; p < 4; p++)
1072 {
1073 if (!data[p])
1074 {
1075 ok = false;
1076 break;
1077 }
1078 type += char(data[p]);
1079 }
1080 for (int p = 4; ok && p < 8; p++)
1081 {
1082 if (!data[p])
1083 {
1084 ok = false;
1085 break;
1086 }
1087 creator += char(data[p]);
1088 }
1089 if (ok)
1090 {
1091 m_fInfoType = type;
1092 m_fInfoCreator = creator;
1093 }
1094 else if (type.length())
1095 {
1096 QXP_DEBUG_MSG(("MWAWInputStream::unMacMIME: can not read find info\n"));
1097 }
1098 }
1099 }
1100
1101 inp->seek(pos+12, librevenge::RVNG_SEEK_SET);
1102 }
1103 }
1104 catch (...)
1105 {
1106 return false;
1107 }
1108 return true;
1109 }
1110
1111 ////////////////////////////////////////////////////////////
1112 //
1113 // OLE part
1114 //
1115 ////////////////////////////////////////////////////////////
1116
1117 bool MWAWInputStream::isStructured()
1118 {
1119 if (!m_stream) return false;
1120 long pos=m_stream->tell();
1121 bool ok=m_stream->isStructured();
1122 m_stream->seek(pos, librevenge::RVNG_SEEK_SET);
1123 return ok;
1124 }
1125
1126 unsigned MWAWInputStream::subStreamCount()
1127 {
1128 if (!m_stream || !m_stream->isStructured())
1129 {
1130 QXP_DEBUG_MSG(("MWAWInputStream::subStreamCount: called on unstructured file\n"));
1131 return 0;
1132 }
1133 return m_stream->subStreamCount();
1134 }
1135
1136 std::string MWAWInputStream::subStreamName(unsigned id)
1137 {
1138 if (!m_stream || !m_stream->isStructured())
1139 {
1140 QXP_DEBUG_MSG(("MWAWInputStream::subStreamName: called on unstructured file\n"));
1141 return std::string("");
1142 }
1143 char const *nm=m_stream->subStreamName(id);
1144 if (!nm)
1145 {
1146 QXP_DEBUG_MSG(("MWAWInputStream::subStreamName: can not find stream %d\n", int(id)));
1147 return std::string("");
1148 }
1149 return std::string(nm);
1150 }
1151
1152 std::shared_ptr<MWAWInputStream> MWAWInputStream::getSubStreamByName(std::string const &name)
1153 {
1154 std::shared_ptr<MWAWInputStream> empty;
1155 if (!m_stream || !m_stream->isStructured() || name.empty())
1156 {
1157 QXP_DEBUG_MSG(("MWAWInputStream::getSubStreamByName: called on unstructured file\n"));
1158 return empty;
1159 }
1160
1161 long actPos = tell();
1162 seek(0, librevenge::RVNG_SEEK_SET);
1163 std::shared_ptr<librevenge::RVNGInputStream> res(m_stream->getSubStreamByName(name.c_str()));
1164 seek(actPos, librevenge::RVNG_SEEK_SET);
1165
1166 if (!res)
1167 return empty;
1168 std::shared_ptr<MWAWInputStream> inp(new MWAWInputStream(res, m_inverseRead));
1169 inp->seek(0, librevenge::RVNG_SEEK_SET);
1170 return inp;
1171 }
1172
1173 std::shared_ptr<MWAWInputStream> MWAWInputStream::getSubStreamById(unsigned id)
1174 {
1175 std::shared_ptr<MWAWInputStream> empty;
1176 if (!m_stream || !m_stream->isStructured())
1177 {
1178 QXP_DEBUG_MSG(("MWAWInputStream::getSubStreamById: called on unstructured file\n"));
1179 return empty;
1180 }
1181
1182 long actPos = tell();
1183 seek(0, librevenge::RVNG_SEEK_SET);
1184 std::shared_ptr<librevenge::RVNGInputStream> res(m_stream->getSubStreamById(id));
1185 seek(actPos, librevenge::RVNG_SEEK_SET);
1186
1187 if (!res)
1188 return empty;
1189 std::shared_ptr<MWAWInputStream> inp(new MWAWInputStream(res, m_inverseRead));
1190 inp->seek(0, librevenge::RVNG_SEEK_SET);
1191 return inp;
1192 }
1193
1194 ////////////////////////////////////////////////////////////
1195 //
1196 // a function to read a data block
1197 //
1198 ////////////////////////////////////////////////////////////
1199
1200 bool MWAWInputStream::readDataBlock(long sz, librevenge::RVNGBinaryData &data)
1201 {
1202 if (!hasDataFork()) return false;
1203
1204 data.clear();
1205 if (sz < 0) return false;
1206 if (sz == 0) return true;
1207 long endPos=tell()+sz;
1208 if (endPos > size()) return false;
1209 if (m_readLimit > 0 && endPos > long(m_readLimit)) return false;
1210
1211 const unsigned char *readData;
1212 unsigned long sizeRead;
1213 if ((readData=m_stream->read(static_cast<unsigned long>(sz), sizeRead)) == 0 || long(sizeRead)!=sz)
1214 return false;
1215 data.append(readData, sizeRead);
1216 return true;
1217 }
1218
1219 bool MWAWInputStream::readEndDataBlock(librevenge::RVNGBinaryData &data)
1220 {
1221 data.clear();
1222 if (!hasDataFork()) return false;
1223
1224 long endPos=m_readLimit>0 ? m_readLimit : size();
1225 return readDataBlock(endPos-tell(), data);
1226 }
1227
1228 }
1229
1230 namespace libqxp
1231 {
1232
1233 QXPMacFileParser::QXPMacFileParser(std::shared_ptr<librevenge::RVNGInputStream> &dataFork, std::string &type, std::string &creator)
1234 : m_dataFork(dataFork)
1235 , m_type(type)
1236 , m_creator(creator)
1237 {
1238 }
1239
1240 bool QXPMacFileParser::parse(const std::shared_ptr<librevenge::RVNGInputStream> &input)
1241 {
1242 MWAWInputStream strm(input.get(), false, true);
1243 m_dataFork = strm.input();
1244 return strm.hasDataFork() && strm.getFinderInfo(m_type, m_creator);
1245 }
1246
1247 }
1248
1249 /* vim:set shiftwidth=2 softtabstop=2 expandtab: */