Tools/PalmDoc.pm

filter: Statementstmt 76.0% 19 / 25 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 87.5% 7 / 8 Podpod n/a totaltotal 78.7% 26 / 33 CC 1 SCAR 1.5
CC
1
Cov
76%
import
2.0
BEGIN
1.3
BEGIN
1.0
CRAP 1.2
↑ Summary Tools/EReader.pm »
1 package EBook::Tools::PalmDoc;
2 1 ▶use warnings; use strict; use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
3 1 ▶use version 0.74; our $VERSION = qv("0.5.2");
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 # Mixed case subs and the variable %record are inherited from Palm::PDB
6 ## no critic (ProhibitAmbiguousNames)
7 ## no critic (ProhibitMixedCaseSubs)
8 # RequireBriefOpen seems to be way too brief to be useful
9 ## no critic (RequireBriefOpen)
10  
11 =head1 NAME
12  
13 EBook::Tools::PalmDoc - Palm::PDB handler for manipulating the PalmDoc/PilotDoc/AportisDoc format
14  
15 =head1 SYNOPSIS
16  
17 use EBook::Tools::PalmDoc qw(uncompress_palmdoc);
18 use Palm::PDB;
19  
20 my $pdb = Palm::PDB->new();
21  
22 or
23  
24 use EBook::Tools::PalmDoc qw(:all);
25  
26 my $pdb = EBook::Tools::PalmDoc->new();
27 $pdb->set_text($text);
28 $pdb->Write('textfile.pdb');
29  
30 my $pdb2 = EBook::Tools::PalmDoc->new();
31 $pdb2->{attributes}{resource} = 1;
32 $pdb->import_textfile('textfile.txt');
33 $pdb->Write('textfile.prc');
34  
35 =head1 DESCRIPTION
36  
37 This module contains a L<Palm::PDB> handler (subclassed from
38 L<Palm::Raw>) and some associated general procedures for dealing with
39 PalmDoc books. This handles PalmDoc and only PalmDoc. For
40 Mobipocket, eReader, or other .pdb/.prc formats, see the module
41 specific to the format.
42  
43 =cut
44  
45 require Exporter;
46 1 ▶use base qw(Exporter Palm::Raw);
Subroutine BEGIN: called CC=1 SCAR=0.0
47  
48 our @EXPORT_OK;
49 @EXPORT_OK = qw (
50 &compress_palmdoc
51 &parse_palmdoc_header
52 &uncompress_palmdoc
53 );
54 our %EXPORT_TAGS = ('all' => [@EXPORT_OK]);
55  
56 sub import ## no critic (Always unpack @_ first)
57 0 ▶{
Subroutine import: not called CC=1 SCAR=6.9
58 0 &Palm::PDB::RegisterPDBHandlers( __PACKAGE__, [ "REAd", "TEXt" ], );
59 0 &Palm::PDB::RegisterPRCHandlers( __PACKAGE__, [ "REAd", "TEXt" ], );
60 0 EBook::Tools::PalmDoc->export_to_level(1, @_);
61 0 return;
62 }
63  
64 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
65 0 ▶use EBook::Tools qw(debug hexstring);
Subroutine BEGIN: called CC=1 SCAR=2.6
66 use File::Basename qw(fileparse);
67 use Palm::PDB;
68 use Palm::Raw();
69  
70 my $htmlsupport = 0;
71 eval
72 {
73 require HTML::TextToHTML;
74 EBook::Tools::DRM->import();
75 }; # Trailing semicolon is required here
76 unless($@){ $htmlsupport = 1; }
77  
78  
79 #################################
80 ########## CONSTRUCTOR ##########
81 #################################
82  
83 =head1 CONSTRUCTOR
84  
85 =head2 C<new()>
86  
87 Instantiates a new Ebook::Tools::PalmDoc object. To create a Palm
88 Resource file instead of a Palm Database file, set
89 C<< $self->{attributes}{resource} >> to be true immediately after
90 construction.
91  
92 Create a new Doc object. By default, it's not a resource database. Setting
93 C<< $self->{attributes}{resource} >> to C<1> before any manipulations will
94 cause it to become a resource database.
95  
96 =cut
97  
98 sub new ## no critic (Always unpack @_ first)
99 {
100 my $class = shift;
101 my $self = $class->SUPER::new(@_);
102  
103 $self->{'creator'} = 'REAd';
104 $self->{'type'} = 'TEXt';
105  
106 $self->{attributes}{resource} = 0;
107  
108 $self->{appinfo} = undef;
109 $self->{sort} = undef;
110 $self->{records} = [];
111 $self->{text} = '';
112 $self->{bookmarks} = {};
113  
114 return $self;
115 }
116  
117  
118 ######################################
119 ########## ACCESSOR METHODS ##########
120 ######################################
121  
122 =head1 ACCESSOR METHODS
123  
124 =head2 C<bookmarks()>
125  
126 Returns a hash of bookmarks, where the keys are the bookmark offsets
127 and the values are the bookmark names.
128  
129 =cut
130  
131 sub bookmarks :method
132 {
133 my $self = shift;
134 my %bookmarks;
135  
136 if($self->{bookmarks} and ref($self->{bookmarks}) eq 'HASH')
137 {
138 %bookmarks = %{$self->{bookmarks}};
139 }
140 elsif($self->{bookmarks})
141 {
142 %bookmarks = $self->{bookmarks}
143 }
144 else
145 {
146 %bookmarks = ();
147 }
148 return %bookmarks;
149 }
150  
151  
152 =head2 C<text()>
153  
154 Returns the text of the file
155  
156 =cut
157  
158 sub text :method
159 {
160 my $self = shift;
161 my $subname = ( caller(0) )[3];
162 debug(2,"DEBUG[",$subname,"]");
163  
164 my $length = length($self->{text});
165  
166 carp("WARNING: actual text length (",$length,
167 ") does not match specified text length (",
168 $self->{header}{textlength},")\n")
169 unless($length == $self->{header}{textlength});
170  
171 return $self->{text};
172 }
173  
174  
175 =head2 C<html()>
176  
177 Returns the text of the file converted to HTML via L<HTML::TextToHTML>.
178  
179 =cut
180  
181 sub html :method
182 {
183 my $self = shift;
184 my $subname = ( caller(0) )[3];
185 debug(2,"DEBUG[",$subname,"]");
186  
187 croak("HTML support requires that HTML::TextToHTML be installed!\n")
188 unless($htmlsupport);
189  
190 my $conv = HTML::TextToHTML->new();
191 my $header = "<html>\n<head>\n <title>" . $self->{name} . "</title>\n";
192 $header .= "</head>\n<body>\n";
193 my $footer = "</body>\n</html>\n";
194  
195 return $header . $conv->process_chunk($self->{text}) . $footer;
196 }
197  
198  
199 ######################################
200 ########## MODIFIER METHODS ##########
201 ######################################
202  
203 =head1 MODIFIER METHODS
204  
205 These methods have two naming/capitalization schemes -- methods
206 directly related to the subclassing of Palm::PDB use its
207 MethodName capitalization style. Any other methods are
208 lowercase_with_underscores for consistency with the rest of
209 EBook::Tools.
210  
211  
212 =head2 C<ParseRecord(%record)>
213  
214 Parses PDB records, updating the object attributes. This method is
215 called automatically on every database record (in .pdb files) during
216 C<Load()>.
217  
218 =cut
219  
220 sub ParseRecord :method ## no critic (Always unpack @_ first)
221 {
222 my $self = shift;
223 my %record = @_;
224 my $subname = ( caller(0) )[3];
225 debug(3,"DEBUG[",$subname,"]");
226  
227 my $currentrecord = scalar @{$$self{records}};
228  
229 if($currentrecord == 0)
230 {
231 $$self{header} = parse_palmdoc_header($record{data});
232 return \%record;
233 }
234  
235 if($currentrecord <= $$self{header}{textrecords})
236 {
237 $self->ParseRecordText($record{data});
238 }
239 else
240 {
241 # Bookmark records at end of file
242 $self->ParseRecordBookmark($record{data},$currentrecord);
243 }
244 return \%record;
245 }
246  
247  
248 =head2 C<ParseResource(%resource)>
249  
250 Parses PDB resources, updating object attributes. This is called
251 automatically on every database resource (in .prc files) during
252 C<Load()>.
253  
254 =cut
255  
256 sub ParseResource :method ## no critic (Always unpack @_ first)
257 {
258 my $self = shift;
259 my %resource = @_;
260 my $subname = ( caller(0) )[3];
261 debug(3,"DEBUG[",$subname,"]");
262  
263 my $currentresource = scalar @{$$self{resources}};
264  
265 if($currentresource == 0)
266 {
267 $self->{header} = parse_palmdoc_header($resource{data});
268 return \%resource;
269 }
270  
271 if($currentresource <= $self->{header}{textrecords})
272 {
273 $self->ParseRecordText($resource{data});
274 }
275 else
276 {
277 # Bookmark records at end of file
278 $self->ParseRecordBookmark($resource{data},$currentresource);
279 }
280 return \%resource;
281 }
282  
283  
284 =head2 C<ParseRecordBookmark($data,$currentrecord)>
285  
286 Parses bookmark records/resources, updating object attributes, most
287 notably C<< $self->{bookmarks} >>.
288  
289 The C<$currentrecord> argument is optional, but without it the
290 debugging information may be less useful. This is called
291 automatically by L<ParseRecord()> and L<ParseResource()> as needed.
292  
293 =cut
294  
295 sub ParseRecordBookmark :method ## no critic (Always unpack @_ first)
296 {
297 my $self = shift;
298 my ($data,$currentrecord) = @_;
299 my $subname = ( caller(0) )[3];
300 debug(2,"DEBUG[",$subname,"]");
301  
302 $currentrecord = '[unknown]' unless(defined $currentrecord);
303 my $bookmark;
304 my $offset;
305  
306 if(length($data) < 20)
307 {
308 croak($subname,"(): bookmark record ",$currentrecord,
309 " is only ",length($data)," bytes (need 20)\n");
310 }
311 elsif(length($data) == 20)
312 {
313 debug(1,"bookmark record ",$currentrecord," is ",
314 length($data)," bytes (expected 20)");
315 }
316  
317 $bookmark = substr($data,0,18);
318 $bookmark =~ s/\0+//gx;
319 $offset = unpack('n',substr($data,18,2));
320 $self->{bookmarks}->{$offset} = $bookmark;
321 debug(1,"DEBUG: record ",$currentrecord,
322 " is bookmark '",$bookmark,"' [offset ",$offset,"]");
323 return 1;
324 }
325  
326  
327 =head2 C<ParseRecordText($data)>
328  
329 Parses text records, updating object attributes, most notably
330 appending text to C<< $self->{text} >>.
331  
332 This is called automatically by L</ParseRecord()> and
333 L</ParseResource()> as needed.
334  
335 =cut
336  
337 sub ParseRecordText :method
338 {
339 my $self = shift;
340 my $data = shift;
341 my $subname = ( caller(0) )[3];
342 debug(2,"DEBUG[",$subname,"]");
343  
344 my $compression = $self->{header}{compression};
345  
346 if($compression == 1) # No compression
347 {
348 $self->{text} .= $data;
349 }
350 elsif($compression == 2) # PalmDoc compression
351 {
352 $self->{text} .= uncompress_palmdoc($data);
353 }
354 else
355 {
356 croak($subname,"(): unknown compression value (",
357 $compression,")\n");
358 }
359 return 1;
360 }
361  
362  
363 =head2 C<set_text(@text)>
364  
365 Uses the contents of C<@text> (concatenated) as the text of the PDB.
366  
367 =cut
368  
369 sub set_text ## no critic (Always unpack @_ first)
370 {
371 my $self = shift;
372 my $text = join('',@_);
373 my $subname = ( caller(0) )[3];
374 debug(2,"DEBUG[",$subname,"]");
375  
376 my $isresource = $self->{attributes}{resource};
377 my $record0;
378 my $record;
379 my $compression = 2;
380 my $offset;
381 my $textblock;
382  
383 $self->{'records'} = [];
384 $self->{'resources'} = [];
385  
386 $record0 = ($isresource)?
387 $self->append_Resource()
388 : $self->append_Record();
389 $record0->{'compression'} = $compression;
390 $record0->{'length'} = 0;
391 $record0->{'spare'} = 0;
392 $record0->{'textrecords'} = 0;
393 $record0->{'recsize'} = 4096;
394  
395 for($offset = 0; $offset < length($text); $offset += 4096 )
396 {
397 $record = ($isresource) ?
398 $self->append_Resource
399 : $self->append_Record;
400 $textblock = substr($text,$offset,4096);
401 $record->{'data'} = compress_palmdoc($textblock);
402  
403 $record0->{'textrecords'} ++;
404 $record0->{'length'} += length($text);
405 }
406 if($record0->{'length'} < 4096)
407 {
408 $record0->{'recsize'} = $record0->{'length'};
409 }
410  
411 $record0->{'data'} =
412 pack('nnNnnN',
413 $record0->{'compression'}, $record0->{'spare'},
414 $record0->{'length'},
415 $record0->{'textrecords'}, $record0->{'recsize'}, 0 );
416  
417 return 1;
418 }
419  
420  
421 =head2 import_textfile($filename)
422  
423 Set the contents of the Doc to the contents of the file and sets the
424 name of the PDB to the basename of the file.
425  
426 =cut
427  
428 sub import_textfile :method
429 {
430 my $self = shift;
431 my $filename = shift;
432 my $subname = ( caller(0) )[3];
433 debug(2,"DEBUG[",$subname,"]");
434  
435 my $fh;
436 open($fh,"<:raw",$filename)
437 or croak($subname,"(): unable to open '",$filename,"' [",@!,"]");
438 $self->set_text('',<$fh>);
439 close($fh)
440 or croak($subname,"(): unable to close '",$filename,"' [",@!,"]");
441  
442 $self->{'name'} = fileparse($filename,'\.\w+$');
443 return 1;
444 }
445  
446  
447 ################################
448 ########## PROCEDURES ##########
449 ################################
450  
451 =head1 PROCEDURES
452  
453 All procedures are exportable, but none are exported by default.
454  
455 =head2 C<compress_palmdoc($text)>
456  
457 Compresses input text using the simplified Lempel-Ziv 77 encoding used
458 by PalmDoc and some other formats and returns the compressed string.
459  
460 See L</uncompress_palmdoc()> for more details on the algorithm.
461  
462 This procedure was taken from L<Palm::Doc> with some minor changes.
463  
464 =cut
465  
466 sub compress_palmdoc
467 {
468 my $text = shift;
469 my $subname = ( caller(0) )[3];
470 debug(3,"DEBUG[",$subname,"]");
471  
472 my $textlength = length($text);
473 my $compressed = '';
474  
475 debug(1,"WARNING: input text is longer than 4096 bytes (",$textlength,
476 " bytes) and may not produce a valid PDB if used.")
477 if($textlength > 4096);
478  
479 my $offset = 0;
480 while($offset < $textlength)
481 {
482 # See http://web.archive.org/web/20061024025145/http://patb.dyndns.org/Programming/PilotDoc.htm
483  
484 # Try type B compression first.
485 # If the next 3 to 10 bytes are already in the compressed
486 # buffer, we can encode them into a 2 byte sequence. Don't
487 # bother too close to the ends, however... Makes the boundary
488 # conditions simpler.
489 if( $offset > 10 and $textlength - $offset > 10 )
490 {
491 my $chunk = '';
492 my $match = -1;
493  
494 # the preamble is what'll be in the decoders output buffer.
495 my $preamble = substr( $text, 0, $offset );
496 for( my $j = 10; $j >= 3; $j -- )
497 {
498 $chunk = substr($text,$offset,$j); # grab next $j characters
499 $match = rindex($preamble,$chunk); # in the output?
500  
501 # type B code has a 2047 byte sliding window, so
502 # matches have to be within that range to be useful
503 last if $match >= 0 and ($offset - $match) <= 2047;
504 $match = -1;
505 }
506  
507 my $n = length $chunk;
508 if( $match >= 0 and $n <= 10 and $n >= 3 )
509 {
510 my $m = $offset - $match;
511  
512 # first 2 bits are 10, next 11 are offset, next 3 are length-3
513 $compressed .= pack( "n", 0x8000 + (($m<<3)&0x3ff8) + ($n-3) );
514  
515 $offset += $n;
516  
517 next;
518 }
519 }
520  
521 my $ch = substr( $text, $offset ++, 1 );
522 my $och = ord($ch);
523  
524 # Try type C compression.
525 if( $offset+1 < $textlength and $ch eq ' ' )
526 {
527 my $nch = substr( $text, $offset, 1 );
528 my $onch = ord($nch);
529  
530 if( $onch >= 0x40 and $onch < 0x80 )
531 {
532 # space plus ASCII character compression
533 $compressed .= chr($onch ^ 0x80);
534 $offset ++;
535  
536 next;
537 }
538 }
539  
540 if( $och == 0 or ($och >= 9 and $och < 0x80) )
541 {
542 # pass through
543 $compressed .= $ch;
544 }
545 else
546 {
547 # Type A code. This is essentially an 'escape' like '\\'
548 # in strings. For efficiency, it's best to encode as long
549 # a sequence as possible with one copy.
550 #
551 # This might seem like it would cause us to miss out on a
552 # type B sequence, but in actuality keeping long binary
553 # strings together improves the likelyhood of a later type
554 # B sequence than interspersing them with x01's.
555  
556 my $next = substr($text,$offset - 1);
557 if( $next =~ /([\x01-\x08\x80-\xff]{1,8})/o )
558 {
559 my $binseq = $1;
560 $compressed .= chr(length $binseq);
561 $compressed .= $binseq;
562 # first char, $ch, is already counted
563 $offset += length( $binseq ) - 1;
564 }
565 }
566 }
567 return $compressed;
568 }
569  
570  
571 =head2 C<parse_palmdoc_header($data)>
572  
573 Takes as an argument a scalar containing the 16 bytes of the PalmDoc
574 header (also used by Mobipocket). Returns a hashref containing those
575 values keyed to recognizable names.
576  
577 See:
578  
579 http://wiki.mobileread.com/wiki/DOC#PalmDOC
580  
581 and
582  
583 http://wiki.mobileread.com/wiki/MOBI
584  
585 =head3 keys
586  
587 The returned hashref will have the following keys:
588  
589 =over
590  
591 =item * C<compression>
592  
593 Possible values:
594  
595 =over
596  
597 =item 1 - no compression
598  
599 =item 2 - PalmDoc compression
600  
601 =item 128 - iSilo3?
602  
603 =item 17480 (the characters 'DH') - Mobipocket 'Dictionary Huffman'
604 compression (aka HuffDic aka Huff/CDIC)
605  
606 =back
607  
608 A warning will be carped if an unknown value is found.
609  
610 =item * C<textlength>
611  
612 Uncompressed length of book text in bytes
613  
614 =item * C<textrecords>
615  
616 Number of PDB records used for book text
617  
618 =item * C<recordsize>
619  
620 Maximum size of each record containing book text. This should always
621 be 2048 (for some Mobipocket files) or 4096 (for everything else). A
622 warning will be carped if it isn't.
623  
624 =item * C<spare>
625  
626 Two bytes that should always be zero. A warning will be carped if
627 they aren't.
628  
629 =item * C<unknown12>
630  
631 32 bits of unknown data, generally zero. This key may be changed
632 later if more information is discovered. Use with caution.
633  
634 =back
635  
636 Note that the current position component of the header is discarded.
637  
638 =cut
639  
640 sub parse_palmdoc_header
641 {
642 my $data = shift;
643 my $subname = ( caller(0) )[3];
644 debug(2,"DEBUG[",$subname,"]");
645  
646 my %pdbcompression = (
647 1 => 'no compression',
648 2 => 'PalmDoc compression',
649 128 => 'iSilo3 compression',
650 17480 => 'Dictionary Huffman compression',
651 );
652  
653 # We're expecting 16 bytes of data exactly. We won't croak on
654 # more, but it will be reported
655 croak($subname,"(): record 0 is too short (only ",
656 length($data)," bytes, need at least 16)!\n")
657 if(length($data) < 16);
658 debug(1,"DEBUG: ",length($data)," bytes of PalmDoc header data",
659 " (expected 16)")
660 if(length($data) != 16);
661  
662 my @list = unpack("nnNnnN",$data);
663 my %header;
664  
665 $header{compression} = $list[0]; # Bytes 00-01
666 $header{spare} = $list[1]; # Bytes 01-02
667 $header{textlength} = $list[2]; # Bytes 03-07
668 $header{textrecords} = $list[3]; # Bytes 08-09
669 $header{recordsize} = $list[4]; # Bytes 10-11
670 $header{unknown12} = $list[5]; # Bytes 12-15
671  
672 carp($subname,"(): value ",$header{spare},
673 " found in header 'spare' (expected 0)")
674 unless($header{spare} == 0);
675 carp($subname,"(): found text record size ",$header{recordsize},
676 ", expected 2048 or 4096")
677 unless($header{recordsize} == 2048
678 or $header{recordsize} == 4096);
679 carp($subname,"(): found unknown compression value ",$header{compression})
680 unless(defined $pdbcompression{$header{compression}});
681 debug(1,"DEBUG: PDB compression type is ",
682 $pdbcompression{$header{compression}});
683  
684 foreach my $key (sort keys %header)
685 {
686 debug(2,'DEBUG: palmdoc{',$key,'}=0x',sprintf("%04x",$header{$key}));
687 }
688 return \%header;
689 }
690  
691  
692 =head2 C<uncompress_palmdoc($data,%args)>
693  
694 Uncompresses data compressed using the simplified Lempel-Ziv 77 scheme
695 used by PalmDoc and some other formats, and returns the uncompressed
696 string.
697  
698 If an error is encountered during uncompression outputs a debug
699 message and returns undef.
700  
701 =head3 Arguments
702  
703 C<uncompress_palmdoc> takes one optional named argument:
704  
705 =over
706  
707 =item C<trailing>
708  
709 This specifies the number of trailing bytes to ignore on each record
710 during decompression. Extra data such as this is sometimes found on
711 version 6 Mobipocket records.
712  
713 =back
714  
715 =head3 Algorithm
716  
717 The decoding mechanism is as follows:
718  
719 Start by reading a byte from the compressed stream. If the byte is:
720  
721 =over
722  
723 =item * 0x00: copy unmodified
724  
725 =item * 0x01 to 0x08: "Type A" command
726  
727 This specifies that the next 1-8 bytes are to be copied unmodified.
728  
729 =item * 0x09 to 0x7f: copy unmodified
730  
731 =item * 0x80 to 0xbf: "Type B" command
732  
733 This specifies that the 16 bits (two characters) starting at that
734 point represent a length-offset pair. Of the 16 bits that make up
735 these two bytes, the two leftmost bits (which should be '10') are
736 simply an identifier and are discarded. The next 11 bits encode the
737 offset backwards from the end of uncompressed text, and the last three
738 encode the length of text to copy from that point (copying n+3 bytes).
739  
740 =item * 0xc0 to 0xff: "Type C" command
741  
742 This compresses spaces with the next character, with the value of that
743 character being XORed with 0x80.
744  
745 =back
746  
747 =cut
748  
749 sub uncompress_palmdoc
750 {
751 my $data = shift;
752 my (%args) = @_;
753 my $subname = ( caller(0) )[3];
754 debug(3,"DEBUG[",$subname,"]");
755  
756 my %valid_args = (
757 'trailing' => 1,
758 );
759 foreach my $arg (keys %args)
760 {
761 croak($subname,"(): invalid argument '",$arg,"'")
762 if(!$valid_args{$arg});
763 }
764  
765 my $trailing = $args{trailing} || 0;
766 my $reallength = length($data);
767 my $length = $reallength - $trailing;
768 my $traildata = substr($data,$length,$trailing);
769  
770 my $offset = 0; # Current offset into data
771 my $char; # Character being examined
772 my $ord; # Ordinal of $char
773 my $lz77; # 16-bit Lempel-Ziv 77 length-offset pair
774 my $lz77offset; # LZ77 offset
775 my $lz77length; # LZ77 length
776 my $lz77pos; # Position inside $lz77length
777 my $text = ''; # Output (uncompressed) text
778 my $textlength; # Length of uncompressed text during LZ77 pass
779 my $textpos; # Position inside $text during LZ77 pass
780  
781 while($offset < $length)
782 {
783 $char = substr($data,$offset++,1);
784 $ord = ord($char);
785  
786 # The long if-elsif chain is the best logic for $ord handling
787 ## no critic (Cascading if-elsif chain)
788 if($ord == 0)
789 {
790 # Nulls are literal
791 $text .= $char;
792 }
793 elsif($ord <= 8)
794 {
795 # Next $ord bytes are literal
796 if($offset + $ord > $length)
797 {
798 debug(1,"WARNING: ",$ord," literal bytes starting at ",$offset,
799 " exceeds data size (",$length,")");
800 return $text;
801 }
802 $text .= substr($data,$offset,$ord);
803 $offset += $ord;
804 }
805 elsif($ord <= 0x7f)
806 {
807 # Values from 0x09 through 0x7f are literal
808 $text .= $char;
809 }
810 elsif($ord <= 0xbf)
811 {
812 # Data is LZ77-compressed
813  
814 # From Wikipedia:
815 # "A length-distance pair is always encoded by a two-byte
816 # sequence. Of the 16 bits that make up these two bytes,
817 # 11 bits go to encoding the distance, 3 go to encoding
818 # the length, and the remaining two are used to make sure
819 # the decoder can identify the first byte as the beginning
820 # of such a two-byte sequence."
821  
822 $offset++;
823 if($offset > length($data))
824 {
825 debug(1,"WARNING: offset to LZ77 bits (",$offset,
826 ") is outside of the data (size ",length($data),")");
827 return $text;
828 }
829 $lz77 = unpack('n',substr($data,$offset-2,2));
830  
831 # Leftmost two bits are ID bits and need to be dropped
832 $lz77 &= 0x3fff;
833  
834 # Length is rightmost 3 bits + 3
835 $lz77length = ($lz77 & 0x0007) + 3;
836  
837 # Remaining 11 bits are offset
838 $lz77offset = $lz77 >> 3;
839 if($lz77offset < 1)
840 {
841 debug(1,"WARNING: LZ77 decompression offset at ",$offset,
842 " is invalid!");
843 return;
844 }
845  
846 # Getting text from the offset is a little tricky, because
847 # in theory you can be referring to characters you haven't
848 # actually decompressed yet. You therefore have to check
849 # the reference one character at a time.
850 $textlength = length($text);
851 for($lz77pos = 0; $lz77pos < $lz77length; $lz77pos++)
852 {
853 $textpos = $textlength - $lz77offset;
854 if($textpos < 0)
855 {
856 debug(1,"WARNING: LZ77 decompression reference is before",
857 " beginning of text!");
858 debug(2," textlength=${textlength}, lz77offset=${lz77offset}");
859 return;
860 }
861 $text .= substr($text,$textpos,1);
862 $textlength++;
863 }
864 }
865 else
866 {
867 # 0xc0 - 0xff are single characters (XOR 0x80) preceded by
868 # a space
869 $text .= ' ' . chr($ord ^ 0x80);
870 }
871 }
872 if($reallength > $length)
873 {
874 debug(3,"DEBUG: skipping ",$trailing," bytes at end of record: 0x",
875 hexstring($traildata));
876 }
877 return $text;
878 }
879  
880 1;
881 __END__
↑ Summary Tools/EReader.pm »