mirror of
https://github.com/D-Modem/bbs.git
synced 2026-11-28 17:38:04 -08:00
FidoNet: ARC, ARJ and LHA bundles, in an archive package of our own
internal/archive reads ZIP, ARC (stored, packed, squeezed, crunched, squashed), ARJ (methods 0 to 4) and LHA (-lh0-, -lh4- to -lh7-, header levels 0 to 2) in Go, with no other programs, and writes ARC, ARJ and LHA stored. Sizes are checked before memory is given to them and every entry against its CRC; it was fuzzed, and stressed with 350,000 damaged archives (none slower than 30 ms). The test archives were made by the real programs (arc 5.21q, ARJ32 3.10, jlha), and what is written here passes their own tests. Bundles from links are tossed whatever their format (known by their first bytes, not their names); packer = arc, arj or lha bundles in those (stored). A test packs packets with the real programs, compressing, where they are installed. The file base lists and takes FILE_ID.DIZ from ARC, ARJ and LHA archives too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AFQhReUqUc7F5srk2hViqr
This commit is contained in:
38 files changed
+1810
-72
No files matched your search
@@ -0,0 +1,319 @@
|
||||
package archive
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var arcMethods = map[byte]string{1: "stored", 2: "stored", 3: "packed", 4: "squeezed", 8: "crunched", 9: "squashed"}
|
||||
|
||||
// walkARC reads an ARC archive (SEA's, and PKPAK's methods it shares).
|
||||
func walkARC(r io.ReaderAt, size int64, fn func(e Entry, open Opener) bool) error {
|
||||
off := int64(0)
|
||||
for {
|
||||
h, err := readAt(r, size, off, 2)
|
||||
if err != nil {
|
||||
return nil // the file ends: as good as an end mark
|
||||
}
|
||||
if h[0] != 0x1A {
|
||||
return ErrCorrupt
|
||||
}
|
||||
method := h[1]
|
||||
if method == 0 {
|
||||
return nil
|
||||
}
|
||||
hlen := int64(29)
|
||||
if method == 1 {
|
||||
hlen = 25 // the oldest: no unpacked size
|
||||
}
|
||||
h, err = readAt(r, size, off, hlen)
|
||||
if err != nil {
|
||||
return ErrCorrupt
|
||||
}
|
||||
name := cString(h[2:15])
|
||||
packed := int64(le32(h[15:]))
|
||||
mod := dosTime(le16(h[19:]), le16(h[21:]))
|
||||
want := le16(h[23:])
|
||||
orig := packed
|
||||
if method != 1 {
|
||||
orig = int64(le32(h[25:]))
|
||||
}
|
||||
dataOff := off + hlen
|
||||
mname, known := arcMethods[method]
|
||||
if !known {
|
||||
mname = "method " + string(rune('0'+method%10))
|
||||
}
|
||||
e := Entry{Name: strings.ReplaceAll(name, "\\", "/"), Size: orig, Packed: packed, Method: mname, Modified: mod}
|
||||
open := func(max int64) ([]byte, error) {
|
||||
if err := sized(orig, max); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
src, err := readAt(r, size, dataOff, packed)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []byte
|
||||
switch method {
|
||||
case 1, 2:
|
||||
out = src
|
||||
case 3:
|
||||
out, err = unRLE90(src, orig)
|
||||
case 4:
|
||||
var sq []byte
|
||||
if sq, err = unsqueeze(src, max); err == nil {
|
||||
out, err = unRLE90(sq, orig)
|
||||
}
|
||||
case 8:
|
||||
if len(src) == 0 || src[0] != 12 {
|
||||
return nil, ErrCorrupt // the bits it was crunched to: always 12
|
||||
}
|
||||
var lz []byte
|
||||
if lz, err = unLZW(src[1:], 12, max); err == nil {
|
||||
out, err = unRLE90(lz, orig)
|
||||
}
|
||||
case 9:
|
||||
out, err = unLZW(src, 13, max)
|
||||
default:
|
||||
return nil, ErrMethod
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if int64(len(out)) != orig {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
if crc16(out) != want {
|
||||
return nil, ErrChecksum
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
if !fn(e, open) {
|
||||
return nil
|
||||
}
|
||||
off = dataOff + packed
|
||||
}
|
||||
}
|
||||
|
||||
// unRLE90 undoes ARC's run-length coding: 0x90 n repeats the byte before
|
||||
// it to n times in all, 0x90 0 is a 0x90.
|
||||
func unRLE90(src []byte, size int64) ([]byte, error) {
|
||||
out := make([]byte, 0, size)
|
||||
var last byte
|
||||
rep := false
|
||||
for _, c := range src {
|
||||
switch {
|
||||
case rep:
|
||||
if c == 0 {
|
||||
out = append(out, 0x90)
|
||||
} else {
|
||||
for i := 1; i < int(c); i++ {
|
||||
out = append(out, last)
|
||||
}
|
||||
}
|
||||
rep = false
|
||||
case c == 0x90:
|
||||
rep = true
|
||||
default:
|
||||
out = append(out, c)
|
||||
last = c
|
||||
}
|
||||
if int64(len(out)) > size {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// unsqueeze undoes ARC's squeezing: a Huffman tree (its node count, then
|
||||
// pairs of children: a leaf is -(byte+1), 256 the end), then the codes,
|
||||
// low bit first.
|
||||
func unsqueeze(src []byte, max int64) ([]byte, error) {
|
||||
if len(src) < 2 {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
n := int(le16(src))
|
||||
if n > 256 || 2+4*n > len(src) {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
if n == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
tree := make([][2]int16, n)
|
||||
for i := range tree {
|
||||
tree[i] = [2]int16{int16(le16(src[2+4*i:])), int16(le16(src[4+4*i:]))}
|
||||
}
|
||||
var out []byte
|
||||
node := int16(0)
|
||||
for _, c := range src[2+4*n:] {
|
||||
for bit := 0; bit < 8; bit++ {
|
||||
node = tree[node][c>>bit&1]
|
||||
if node < 0 {
|
||||
v := -(int(node) + 1)
|
||||
if v == 256 {
|
||||
return out, nil
|
||||
}
|
||||
out = append(out, byte(v))
|
||||
if int64(len(out)) > max {
|
||||
return nil, ErrTooBig
|
||||
}
|
||||
node = 0
|
||||
} else if int(node) >= n {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
}
|
||||
}
|
||||
return out, nil // no end mark: what there was
|
||||
}
|
||||
|
||||
// unLZW undoes ARC's crunching and squashing: LZW of 9 bits growing to
|
||||
// maxbits, code 256 clearing the table, codes low bit first and read in
|
||||
// groups of their width's bytes, as Unix's compress reads them.
|
||||
func unLZW(src []byte, maxbits uint, max int64) ([]byte, error) {
|
||||
const clear, first = 256, 257
|
||||
maxmax := 1 << maxbits
|
||||
prefix := make([]uint16, maxmax)
|
||||
suffix := make([]byte, maxmax)
|
||||
for i := 0; i < 256; i++ {
|
||||
suffix[i] = byte(i)
|
||||
}
|
||||
nbits := uint(9)
|
||||
maxcode := 1<<nbits - 1
|
||||
free := first
|
||||
clearFlag := false
|
||||
pos := 0
|
||||
var group []byte
|
||||
gbit, gsize := 0, 0 // the bit at in the group, the group's usable bits
|
||||
getcode := func() int {
|
||||
if clearFlag || gbit >= gsize || free > maxcode {
|
||||
if free > maxcode {
|
||||
nbits++
|
||||
if nbits >= maxbits {
|
||||
nbits = maxbits
|
||||
maxcode = maxmax
|
||||
} else {
|
||||
maxcode = 1<<nbits - 1
|
||||
}
|
||||
}
|
||||
if clearFlag {
|
||||
nbits = 9
|
||||
maxcode = 1<<nbits - 1
|
||||
clearFlag = false
|
||||
}
|
||||
if pos >= len(src) {
|
||||
return -1
|
||||
}
|
||||
end := pos + int(nbits)
|
||||
if end > len(src) {
|
||||
end = len(src)
|
||||
}
|
||||
group = src[pos:end]
|
||||
pos = end
|
||||
gbit = 0
|
||||
gsize = len(group)*8 - int(nbits-1)
|
||||
}
|
||||
code := 0
|
||||
for i := uint(0); i < nbits; i++ {
|
||||
b := gbit + int(i)
|
||||
if b/8 < len(group) && group[b/8]>>(b%8)&1 != 0 {
|
||||
code |= 1 << i
|
||||
}
|
||||
}
|
||||
gbit += int(nbits)
|
||||
return code
|
||||
}
|
||||
var out []byte
|
||||
stack := make([]byte, 0, maxmax)
|
||||
old := getcode()
|
||||
if old < 0 {
|
||||
return nil, nil
|
||||
}
|
||||
if old > 255 {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
fin := byte(old)
|
||||
out = append(out, fin)
|
||||
for {
|
||||
code := getcode()
|
||||
if code < 0 {
|
||||
return out, nil
|
||||
}
|
||||
if code == clear {
|
||||
free = first - 1
|
||||
clearFlag = true
|
||||
if code = getcode(); code < 0 {
|
||||
return out, nil
|
||||
}
|
||||
}
|
||||
in := code
|
||||
stack = stack[:0]
|
||||
if code >= free {
|
||||
if code > free {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
stack = append(stack, fin)
|
||||
code = old
|
||||
}
|
||||
for code >= 256 {
|
||||
if code >= maxmax || len(stack) >= maxmax {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
stack = append(stack, suffix[code])
|
||||
code = int(prefix[code])
|
||||
}
|
||||
fin = suffix[code]
|
||||
stack = append(stack, fin)
|
||||
for i := len(stack) - 1; i >= 0; i-- {
|
||||
out = append(out, stack[i])
|
||||
}
|
||||
if int64(len(out)) > max {
|
||||
return nil, ErrTooBig
|
||||
}
|
||||
if free < maxmax {
|
||||
prefix[free] = uint16(old)
|
||||
suffix[free] = fin
|
||||
free++
|
||||
}
|
||||
old = in
|
||||
}
|
||||
}
|
||||
|
||||
// arcName is a name as ARC keeps it: 8.3, in capitals.
|
||||
func arcName(n string) string {
|
||||
n = strings.ToUpper(n)
|
||||
if len(n) > 12 {
|
||||
base, ext, _ := strings.Cut(n, ".")
|
||||
if len(base) > 8 {
|
||||
base = base[:8]
|
||||
}
|
||||
if len(ext) > 3 {
|
||||
ext = ext[:3]
|
||||
}
|
||||
n = base
|
||||
if ext != "" {
|
||||
n += "." + ext
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// writeARC writes files stored (method 2).
|
||||
func writeARC(w io.Writer, files []File) error {
|
||||
var b bytes.Buffer
|
||||
for _, f := range files {
|
||||
h := make([]byte, 29)
|
||||
h[0], h[1] = 0x1A, 2
|
||||
copy(h[2:14], arcName(f.Name))
|
||||
put32(h[15:], uint32(len(f.Data)))
|
||||
date, tm := dosStamp(f.Modified)
|
||||
put16(h[19:], date)
|
||||
put16(h[21:], tm)
|
||||
put16(h[23:], crc16(f.Data))
|
||||
put32(h[25:], uint32(len(f.Data)))
|
||||
b.Write(h)
|
||||
b.Write(f.Data)
|
||||
}
|
||||
b.Write([]byte{0x1A, 0})
|
||||
_, err := w.Write(b.Bytes())
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
// Package archive reads the archives FidoNet moves mail and files in, in
|
||||
// Go and without other programs: ZIP, ARC (stored, packed, squeezed,
|
||||
// crunched and squashed), ARJ (methods 0 to 4) and LHA (-lh0-, -lh4- to
|
||||
// -lh7-, header levels 0 to 2). It writes ZIP, and ARC, ARJ and LHA
|
||||
// stored (each format's own "no compression"), which every unpacker
|
||||
// takes.
|
||||
//
|
||||
// Archives come from other systems: every size is checked before memory
|
||||
// is given to it, every entry against its CRC, and nothing is written to
|
||||
// disk here.
|
||||
package archive
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"hash/crc32"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Kind is an archive's format.
|
||||
type Kind string
|
||||
|
||||
// The formats.
|
||||
const (
|
||||
ZIP Kind = "zip"
|
||||
ARC Kind = "arc"
|
||||
ARJ Kind = "arj"
|
||||
LHA Kind = "lha"
|
||||
)
|
||||
|
||||
// Kinds are the formats read, in the order Detect tries them.
|
||||
var Kinds = []Kind{ZIP, ARJ, LHA, ARC}
|
||||
|
||||
// Errors.
|
||||
var (
|
||||
ErrFormat = errors.New("not an archive this BBS reads (ZIP, ARC, ARJ, LHA)")
|
||||
ErrCorrupt = errors.New("the archive is damaged")
|
||||
ErrChecksum = errors.New("an entry does not match its CRC")
|
||||
ErrMethod = errors.New("an entry is packed by a method this BBS does not unpack")
|
||||
ErrTooBig = errors.New("an entry unpacks too big")
|
||||
)
|
||||
|
||||
// Entry is a file in an archive.
|
||||
type Entry struct {
|
||||
Name string // as the archive has it (it may have a path: check it)
|
||||
Size int64 // unpacked
|
||||
Packed int64
|
||||
Method string // "stored", "crunched", "-lh5-", "method 4"...
|
||||
Modified time.Time
|
||||
Dir bool
|
||||
}
|
||||
|
||||
// Detect is an archive's format by its first bytes ("": none of them).
|
||||
func Detect(head []byte) Kind {
|
||||
switch {
|
||||
case len(head) >= 4 && string(head[:4]) == "PK\x03\x04", len(head) >= 4 && string(head[:4]) == "PK\x05\x06":
|
||||
return ZIP
|
||||
case len(head) >= 4 && head[0] == 0x60 && head[1] == 0xEA:
|
||||
return ARJ
|
||||
case len(head) >= 7 && head[2] == '-' && head[6] == '-' && (head[3] == 'l') && (head[4] == 'h' || head[4] == 'z'):
|
||||
return LHA
|
||||
case len(head) >= 2 && head[0] == 0x1A && head[1] <= 11:
|
||||
return ARC
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// KindByName is the format a file's name says ("": none of them).
|
||||
func KindByName(name string) Kind {
|
||||
n := strings.ToLower(name)
|
||||
switch {
|
||||
case strings.HasSuffix(n, ".zip"):
|
||||
return ZIP
|
||||
case strings.HasSuffix(n, ".arc"):
|
||||
return ARC
|
||||
case strings.HasSuffix(n, ".arj"):
|
||||
return ARJ
|
||||
case strings.HasSuffix(n, ".lzh"), strings.HasSuffix(n, ".lha"):
|
||||
return LHA
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Opener unpacks an entry: its contents, checked against its CRC, or an
|
||||
// error. max is the most it may unpack to (ErrTooBig past it).
|
||||
type Opener func(max int64) ([]byte, error)
|
||||
|
||||
// Walk calls fn for each entry of the archive in r (size bytes long), in
|
||||
// order, until fn returns false or the archive ends.
|
||||
func Walk(r io.ReaderAt, size int64, fn func(e Entry, open Opener) bool) error {
|
||||
head := make([]byte, 8)
|
||||
n, _ := r.ReadAt(head, 0)
|
||||
switch Detect(head[:n]) {
|
||||
case ZIP:
|
||||
return walkZIP(r, size, fn)
|
||||
case ARC:
|
||||
return walkARC(r, size, fn)
|
||||
case ARJ:
|
||||
return walkARJ(r, size, fn)
|
||||
case LHA:
|
||||
return walkLHA(r, size, fn)
|
||||
}
|
||||
return ErrFormat
|
||||
}
|
||||
|
||||
// WalkBytes is Walk over an archive in memory.
|
||||
func WalkBytes(b []byte, fn func(e Entry, open Opener) bool) error {
|
||||
return Walk(bytes.NewReader(b), int64(len(b)), fn)
|
||||
}
|
||||
|
||||
// readAt reads exactly n bytes at off, or ErrCorrupt.
|
||||
func readAt(r io.ReaderAt, size, off, n int64) ([]byte, error) {
|
||||
if off < 0 || n < 0 || off+n > size {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
b := make([]byte, n)
|
||||
if _, err := r.ReadAt(b, off); err != nil && !(err == io.EOF && off+n == size) {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// dosTime is an MS-DOS date and time (as ARC, ARJ and LHA level 0 and 1
|
||||
// keep them), in local time as DOS knew no other.
|
||||
func dosTime(date, tm uint16) time.Time {
|
||||
if date == 0 {
|
||||
return time.Time{}
|
||||
}
|
||||
return time.Date(int(date>>9)+1980, time.Month(date>>5&15), int(date&31),
|
||||
int(tm>>11), int(tm>>5&63), int(tm&31)*2, 0, time.Local)
|
||||
}
|
||||
|
||||
// dosStamp is a time as DOS's date and time.
|
||||
func dosStamp(t time.Time) (date, tm uint16) {
|
||||
if t.Year() < 1980 {
|
||||
return 1<<5 | 1, 0 // 1980-01-01
|
||||
}
|
||||
return uint16((t.Year()-1980)<<9 | int(t.Month())<<5 | t.Day()),
|
||||
uint16(t.Hour()<<11 | t.Minute()<<5 | t.Second()/2)
|
||||
}
|
||||
|
||||
// crc16 is the CRC ARC and LHA keep (CRC-16/ARC: 0xA001 reflected, from 0).
|
||||
func crc16(b []byte) uint16 {
|
||||
var c uint16
|
||||
for _, x := range b {
|
||||
c ^= uint16(x)
|
||||
for i := 0; i < 8; i++ {
|
||||
if c&1 != 0 {
|
||||
c = c>>1 ^ 0xA001
|
||||
} else {
|
||||
c >>= 1
|
||||
}
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// crc32 is the CRC ARJ keeps (the usual one).
|
||||
func crc32sum(b []byte) uint32 { return crc32.ChecksumIEEE(b) }
|
||||
|
||||
func le16(b []byte) uint16 { return uint16(b[0]) | uint16(b[1])<<8 }
|
||||
func le32(b []byte) uint32 { return uint32(le16(b)) | uint32(le16(b[2:]))<<16 }
|
||||
|
||||
func put16(b []byte, v uint16) { b[0], b[1] = byte(v), byte(v>>8) }
|
||||
func put32(b []byte, v uint32) { put16(b, uint16(v)); put16(b[2:], uint16(v>>16)) }
|
||||
|
||||
// cString is a NUL-ended string's text.
|
||||
func cString(b []byte) string {
|
||||
if i := bytes.IndexByte(b, 0); i >= 0 {
|
||||
b = b[:i]
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// sized is an Opener's start: refuse what is too big before taking any
|
||||
// memory for it.
|
||||
func sized(size, max int64) error {
|
||||
if size < 0 || size > max {
|
||||
return ErrTooBig
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
package archive
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The testdata archives were made by the real programs (arc 5.21q, ARJ32
|
||||
// 3.10, jlha 0.1.6) from msgs.pkt, small.txt and rle.bin, and an empty
|
||||
// file.
|
||||
func originals(t *testing.T) map[string][]byte {
|
||||
t.Helper()
|
||||
m := map[string][]byte{"empty.pkt": {}}
|
||||
for _, n := range []string{"msgs.pkt", "small.txt", "rle.bin"} {
|
||||
b, err := os.ReadFile(filepath.Join("testdata", n))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m[n] = b
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func TestRead(t *testing.T) {
|
||||
want := originals(t)
|
||||
for _, c := range []struct {
|
||||
file string
|
||||
kind Kind
|
||||
names string
|
||||
methods string
|
||||
}{
|
||||
{"crunch.arc", ARC, "empty.pkt msgs.pkt small.txt", "crunched packed stored"},
|
||||
{"squash.arc", ARC, "msgs.pkt small.txt", "packed squashed"},
|
||||
{"store.arc", ARC, "rle.bin small.txt", "stored"},
|
||||
{"mixed.arc", ARC, "rle.bin sq.bin", "crunched"},
|
||||
{"m0.arj", ARJ, "rle.bin small.txt", "stored"},
|
||||
{"m1.arj", ARJ, "msgs.pkt rle.bin small.txt", "method 1"},
|
||||
{"m2.arj", ARJ, "msgs.pkt rle.bin small.txt", "method 2"},
|
||||
{"m3.arj", ARJ, "msgs.pkt rle.bin small.txt", "method 3"},
|
||||
{"m4.arj", ARJ, "msgs.pkt rle.bin small.txt", "method 4"},
|
||||
{"empty.arj", ARJ, "empty.pkt small.txt", "method 1 stored"},
|
||||
{"lh0.lzh", LHA, "rle.bin small.txt", "-lh0-"},
|
||||
{"lh5.lzh", LHA, "msgs.pkt rle.bin small.txt", "-lh5-"},
|
||||
{"lh5l0.lzh", LHA, "msgs.pkt small.txt", "-lh5-"},
|
||||
{"lh5l1.lzh", LHA, "msgs.pkt small.txt", "-lh5-"},
|
||||
{"lh6.lzh", LHA, "msgs.pkt rle.bin small.txt", "-lh6-"},
|
||||
{"lh7.lzh", LHA, "msgs.pkt rle.bin small.txt", "-lh7-"},
|
||||
} {
|
||||
b, err := os.ReadFile(filepath.Join("testdata", c.file))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if k := Detect(b); k != c.kind {
|
||||
t.Errorf("%s: detected as %q", c.file, k)
|
||||
}
|
||||
var names []string
|
||||
methods := map[string]bool{}
|
||||
err = WalkBytes(b, func(e Entry, open Opener) bool {
|
||||
names = append(names, e.Name)
|
||||
methods[e.Method] = true
|
||||
data, err := open(1 << 20)
|
||||
if err != nil {
|
||||
t.Errorf("%s: %s (%s): %v", c.file, e.Name, e.Method, err)
|
||||
return true
|
||||
}
|
||||
if int64(len(data)) != e.Size {
|
||||
t.Errorf("%s: %s: %d bytes, the header says %d", c.file, e.Name, len(data), e.Size)
|
||||
}
|
||||
if w, ok := want[e.Name]; ok && !bytes.Equal(data, w) {
|
||||
t.Errorf("%s: %s (%s) unpacks wrong", c.file, e.Name, e.Method)
|
||||
}
|
||||
if e.Modified.Year() != time.Now().Year() && e.Modified.Year() < 2020 {
|
||||
t.Errorf("%s: %s: dated %v", c.file, e.Name, e.Modified)
|
||||
}
|
||||
return true
|
||||
})
|
||||
if err != nil {
|
||||
t.Errorf("%s: %v", c.file, err)
|
||||
}
|
||||
sort.Strings(names)
|
||||
if got := strings.Join(names, " "); got != c.names {
|
||||
t.Errorf("%s: entries %q, want %q", c.file, got, c.names)
|
||||
}
|
||||
var ms []string
|
||||
for m := range methods {
|
||||
ms = append(ms, m)
|
||||
}
|
||||
sort.Strings(ms)
|
||||
if got := strings.Join(ms, " "); got != c.methods {
|
||||
t.Errorf("%s: methods %q, want %q", c.file, got, c.methods)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestWrite: each kind written, then read back.
|
||||
func TestWrite(t *testing.T) {
|
||||
want := originals(t)
|
||||
files := []File{{Name: "msgs.pkt", Data: want["msgs.pkt"], Modified: time.Now()},
|
||||
{Name: "small.txt", Data: want["small.txt"], Modified: time.Now()},
|
||||
{Name: "empty.pkt", Data: nil, Modified: time.Now()}}
|
||||
for _, k := range []Kind{ZIP, ARC, ARJ, LHA} {
|
||||
var b bytes.Buffer
|
||||
if err := Write(&b, k, "out."+string(k), files); err != nil {
|
||||
t.Fatalf("%s: %v", k, err)
|
||||
}
|
||||
if got := Detect(b.Bytes()); got != k {
|
||||
t.Errorf("%s: detected as %q", k, got)
|
||||
}
|
||||
n := 0
|
||||
err := WalkBytes(b.Bytes(), func(e Entry, open Opener) bool {
|
||||
name := strings.ToLower(e.Name)
|
||||
data, err := open(1 << 20)
|
||||
if err != nil || !bytes.Equal(data, want[name]) {
|
||||
t.Errorf("%s: %s: %v", k, e.Name, err)
|
||||
}
|
||||
n++
|
||||
return true
|
||||
})
|
||||
if err != nil || n != 3 {
|
||||
t.Errorf("%s: %d entries, %v", k, n, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestHostile: damage, lies about sizes and truncation end in errors,
|
||||
// never in a panic or a great deal of memory.
|
||||
func TestHostile(t *testing.T) {
|
||||
ents, _ := filepath.Glob("testdata/*.*")
|
||||
for _, p := range ents {
|
||||
b, _ := os.ReadFile(p)
|
||||
if Detect(b) == "" {
|
||||
continue
|
||||
}
|
||||
for _, cut := range []int{len(b) / 3, len(b) - 7, 40} {
|
||||
if cut <= 0 || cut >= len(b) {
|
||||
continue
|
||||
}
|
||||
WalkBytes(b[:cut], func(e Entry, open Opener) bool { open(1 << 20); return true })
|
||||
}
|
||||
for i := 30; i < len(b); i += 97 { // a byte changed here and there
|
||||
x := append([]byte(nil), b...)
|
||||
x[i] ^= 0x5A
|
||||
WalkBytes(x, func(e Entry, open Opener) bool { open(1 << 20); return true })
|
||||
}
|
||||
}
|
||||
// a size past the limit is refused before anything is unpacked
|
||||
b, _ := os.ReadFile("testdata/m1.arj")
|
||||
err := WalkBytes(b, func(e Entry, open Opener) bool {
|
||||
if e.Name == "msgs.pkt" {
|
||||
if _, err := open(100); !errors.Is(err, ErrTooBig) {
|
||||
t.Errorf("a big entry: %v", err)
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
// a damaged entry fails its CRC
|
||||
b, _ = os.ReadFile("testdata/store.arc")
|
||||
b[len(b)-10] ^= 1
|
||||
bad := false
|
||||
WalkBytes(b, func(e Entry, open Opener) bool {
|
||||
if _, err := open(1 << 20); errors.Is(err, ErrChecksum) {
|
||||
bad = true
|
||||
}
|
||||
return true
|
||||
})
|
||||
if !bad {
|
||||
t.Error("a damaged entry passed")
|
||||
}
|
||||
if err := WalkBytes([]byte("not an archive at all"), func(Entry, Opener) bool { return true }); !errors.Is(err, ErrFormat) {
|
||||
t.Errorf("text: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSqueezed: ARC's method 4, which arc 5.21 no longer chooses, from a
|
||||
// tree made by hand: a is 0, b is 10, the end is 11 (first bit lowest).
|
||||
func TestSqueezed(t *testing.T) {
|
||||
sq := []byte{2, 0, // two nodes
|
||||
0x9E, 0xFF, 1, 0, // node 0: a (-98), node 1
|
||||
0x9D, 0xFF, 0xFF, 0xFE, // node 1: b (-99), the end (-257)
|
||||
0x34} // 0 0 10 11: a a b, the end
|
||||
var arc []byte
|
||||
h := make([]byte, 29)
|
||||
h[0], h[1] = 0x1A, 4
|
||||
copy(h[2:], "AAB.TXT")
|
||||
put32(h[15:], uint32(len(sq)))
|
||||
put16(h[19:], 0x5B4D)
|
||||
put16(h[23:], crc16([]byte("aab")))
|
||||
put32(h[25:], 3)
|
||||
arc = append(append(append(arc, h...), sq...), 0x1A, 0)
|
||||
got := ""
|
||||
err := WalkBytes(arc, func(e Entry, open Opener) bool {
|
||||
b, err := open(100)
|
||||
if err != nil || e.Method != "squeezed" {
|
||||
t.Errorf("%s: %v", e.Method, err)
|
||||
}
|
||||
got = string(b)
|
||||
return true
|
||||
})
|
||||
if err != nil || got != "aab" {
|
||||
t.Errorf("%q, %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
// FuzzWalk: no archive, however made, panics or unpacks past its limit.
|
||||
func FuzzWalk(f *testing.F) {
|
||||
ents, _ := filepath.Glob("testdata/*.*")
|
||||
for _, p := range ents {
|
||||
if b, _ := os.ReadFile(p); Detect(b) != "" && len(b) < 2000 {
|
||||
f.Add(b)
|
||||
}
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, b []byte) {
|
||||
WalkBytes(b, func(e Entry, open Opener) bool {
|
||||
if data, err := open(1 << 16); err == nil && len(data) > 1<<16 {
|
||||
t.Fatalf("%d bytes past the limit", len(data))
|
||||
}
|
||||
return true
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package archive
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const arjMaxHeader = 2600 // ARJ's own limit on a basic header
|
||||
|
||||
// arjHeader reads the header at off: its basic header, and where what
|
||||
// follows it (its data) begins; nil at the end of the archive.
|
||||
func arjHeader(r io.ReaderAt, size, off int64) (h []byte, next int64, err error) {
|
||||
id, err := readAt(r, size, off, 4)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if id[0] != 0x60 || id[1] != 0xEA {
|
||||
return nil, 0, ErrCorrupt
|
||||
}
|
||||
n := int64(le16(id[2:]))
|
||||
if n == 0 {
|
||||
return nil, 0, nil
|
||||
}
|
||||
if n < 30 || n > arjMaxHeader {
|
||||
return nil, 0, ErrCorrupt
|
||||
}
|
||||
h, err = readAt(r, size, off+4, n+4)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if crc32sum(h[:n]) != le32(h[n:]) {
|
||||
return nil, 0, ErrCorrupt
|
||||
}
|
||||
pos := off + 4 + n + 4
|
||||
for { // the extended headers: skipped
|
||||
x, err := readAt(r, size, pos, 2)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
xn := int64(le16(x))
|
||||
pos += 2
|
||||
if xn == 0 {
|
||||
break
|
||||
}
|
||||
pos += xn + 4
|
||||
}
|
||||
return h[:n], pos, nil
|
||||
}
|
||||
|
||||
// walkARJ reads an ARJ archive: methods 0 (stored) to 4.
|
||||
func walkARJ(r io.ReaderAt, size int64, fn func(e Entry, open Opener) bool) error {
|
||||
main, off, err := arjHeader(r, size, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if main == nil || main[6] != 2 {
|
||||
return ErrCorrupt // the first is the archive's own header
|
||||
}
|
||||
for {
|
||||
h, data, err := arjHeader(r, size, off)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if h == nil {
|
||||
return nil
|
||||
}
|
||||
first := int(h[0])
|
||||
if first < 30 || first > len(h) {
|
||||
return ErrCorrupt
|
||||
}
|
||||
method := h[5]
|
||||
ftype := h[6]
|
||||
stamp := le32(h[8:])
|
||||
packed := int64(le32(h[12:]))
|
||||
orig := int64(le32(h[16:]))
|
||||
want := le32(h[20:])
|
||||
rest := h[first:]
|
||||
name := cString(rest)
|
||||
name = strings.ReplaceAll(name, "\\", "/")
|
||||
e := Entry{Name: name, Size: orig, Packed: packed, Method: "stored",
|
||||
Modified: dosTime(uint16(stamp>>16), uint16(stamp)), Dir: ftype == 3}
|
||||
if method != 0 {
|
||||
e.Method = "method " + string(rune('0'+method))
|
||||
}
|
||||
open := func(max int64) ([]byte, error) {
|
||||
if err := sized(orig, max); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if h[4]&1 != 0 {
|
||||
return nil, ErrMethod // garbled (a password)
|
||||
}
|
||||
src, err := readAt(r, size, data, packed)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []byte
|
||||
switch method {
|
||||
case 0:
|
||||
if packed != orig {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
out = src
|
||||
case 1, 2, 3:
|
||||
out, err = unhuf(src, orig, 16)
|
||||
case 4:
|
||||
out, err = unarj4(src, orig)
|
||||
default:
|
||||
return nil, ErrMethod
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if crc32sum(out) != want {
|
||||
return nil, ErrChecksum
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
if ftype != 2 && !fn(e, open) {
|
||||
return nil
|
||||
}
|
||||
off = data + packed
|
||||
}
|
||||
}
|
||||
|
||||
// unarj4 unpacks ARJ's method 4 ("fastest"): a literal or a match, each
|
||||
// of lengths and distances in a code of growing widths.
|
||||
func unarj4(src []byte, size int64) ([]byte, error) {
|
||||
r := &bitReader{b: src}
|
||||
// a unary count of more widths from start up to stop, then that many bits
|
||||
value := func(start, stop uint) int {
|
||||
plus, pwr := 0, 1<<start
|
||||
width := start
|
||||
for ; width < stop; width++ {
|
||||
if r.bits(1) == 0 {
|
||||
break
|
||||
}
|
||||
plus += pwr
|
||||
pwr <<= 1
|
||||
}
|
||||
c := 0
|
||||
if width != 0 {
|
||||
c = int(r.bits(width))
|
||||
}
|
||||
return c + plus
|
||||
}
|
||||
out := make([]byte, 0, size)
|
||||
for int64(len(out)) < size {
|
||||
if r.overrun() {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
n := value(0, 7)
|
||||
if n == 0 {
|
||||
out = append(out, byte(r.bits(8)))
|
||||
continue
|
||||
}
|
||||
n += hufThreshold - 1
|
||||
p := value(9, 13)
|
||||
from := len(out) - p - 1
|
||||
for ; n > 0 && int64(len(out)) < size; n-- {
|
||||
if from < 0 {
|
||||
out = append(out, ' ')
|
||||
} else {
|
||||
out = append(out, out[from])
|
||||
}
|
||||
from++
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// arjBasic is a basic header, its CRC after it.
|
||||
func arjBasic(method, ftype byte, stamp, packed, orig, crc uint32, name string) []byte {
|
||||
h := make([]byte, 30)
|
||||
h[0] = 30
|
||||
h[1] = 11 // the version that wrote it: ARJ 2.50's
|
||||
h[2] = 1 // the version to read it
|
||||
h[3] = 0 // MS-DOS
|
||||
h[5] = method
|
||||
h[6] = ftype
|
||||
put32(h[8:], stamp)
|
||||
put32(h[12:], packed)
|
||||
put32(h[16:], orig)
|
||||
put32(h[20:], crc)
|
||||
put16(h[26:], 0x20) // archive
|
||||
h = append(h, name...)
|
||||
h = append(h, 0, 0) // the name's end, an empty comment
|
||||
var b bytes.Buffer
|
||||
b.Write([]byte{0x60, 0xEA})
|
||||
var n [2]byte
|
||||
put16(n[:], uint16(len(h)))
|
||||
b.Write(n[:])
|
||||
b.Write(h)
|
||||
var c [4]byte
|
||||
put32(c[:], crc32sum(h))
|
||||
b.Write(c[:])
|
||||
b.Write([]byte{0, 0}) // no extended header
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
// writeARJ writes files stored (method 0) in an archive called name.
|
||||
func writeARJ(w io.Writer, name string, files []File) error {
|
||||
var b bytes.Buffer
|
||||
b.Write(arjBasic(0, 2, 0, 0, 0, 0, name))
|
||||
for _, f := range files {
|
||||
date, tm := dosStamp(f.Modified)
|
||||
n := f.Name
|
||||
if len(n) > 500 {
|
||||
n = n[:500]
|
||||
}
|
||||
b.Write(arjBasic(0, 0, uint32(date)<<16|uint32(tm), uint32(len(f.Data)), uint32(len(f.Data)),
|
||||
crc32sum(f.Data), n))
|
||||
b.Write(f.Data)
|
||||
}
|
||||
b.Write([]byte{0x60, 0xEA, 0, 0})
|
||||
_, err := w.Write(b.Bytes())
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
package archive
|
||||
|
||||
// The static Huffman coding of LHA's -lh4- to -lh7- and ARJ's methods 1
|
||||
// to 3 (Haruhiko Okumura's, as both use it): blocks, each with its own
|
||||
// code tables, of literals and (length, distance) pairs.
|
||||
|
||||
// bitReader reads bits from the first (most significant) down, as LHA and
|
||||
// ARJ write them; past the end it reads zeros (the output's size, known,
|
||||
// ends the decoding).
|
||||
type bitReader struct {
|
||||
b []byte
|
||||
pos int
|
||||
buf uint32 // the next bits, from bit 31 down
|
||||
n uint // how many of them are good
|
||||
}
|
||||
|
||||
func (r *bitReader) fill() {
|
||||
for r.n <= 24 {
|
||||
var c byte
|
||||
if r.pos < len(r.b) {
|
||||
c = r.b[r.pos]
|
||||
}
|
||||
r.pos++
|
||||
r.buf |= uint32(c) << (24 - r.n)
|
||||
r.n += 8
|
||||
}
|
||||
}
|
||||
|
||||
// peek is the next 16 bits.
|
||||
func (r *bitReader) peek() uint16 {
|
||||
r.fill()
|
||||
return uint16(r.buf >> 16)
|
||||
}
|
||||
|
||||
func (r *bitReader) skip(n uint) {
|
||||
r.fill()
|
||||
r.buf <<= n
|
||||
r.n -= n
|
||||
}
|
||||
|
||||
// bits reads n (at most 16) bits.
|
||||
func (r *bitReader) bits(n uint) uint16 {
|
||||
if n == 0 {
|
||||
return 0
|
||||
}
|
||||
v := r.peek() >> (16 - n)
|
||||
r.skip(n)
|
||||
return v
|
||||
}
|
||||
|
||||
// overrun reports whether far more was read than there is: a corrupt
|
||||
// stream decoding zeros.
|
||||
func (r *bitReader) overrun() bool { return r.pos > len(r.b)+8 }
|
||||
|
||||
const (
|
||||
hufThreshold = 3
|
||||
hufMaxMatch = 256
|
||||
hufNC = 255 + hufMaxMatch + 2 - hufThreshold // 510: literals and lengths
|
||||
hufCBit = 9
|
||||
hufNT = 16 + 3 // the code lengths' code
|
||||
hufTBit = 5
|
||||
hufMaxNP = 0x11
|
||||
)
|
||||
|
||||
// huf decodes one stream.
|
||||
type huf struct {
|
||||
r bitReader
|
||||
np int // positions' codes: the dictionary's bits + 1
|
||||
pbit uint // bits that say how many there are
|
||||
blocksize int
|
||||
cLen [hufNC]byte
|
||||
ptLen [hufNT + hufMaxNP]byte
|
||||
cTable [4096]uint16
|
||||
ptTable [256]uint16
|
||||
left [2*hufNC - 1]uint16
|
||||
right [2*hufNC - 1]uint16
|
||||
}
|
||||
|
||||
// makeTable builds a decoding table of tablebits from code lengths, with
|
||||
// a tree beside it for codes longer than that; false if the lengths do
|
||||
// not make a code.
|
||||
func (h *huf) makeTable(nchar int, bitlen []byte, tablebits uint, table []uint16) bool {
|
||||
var count [17]uint32
|
||||
var start, weight [18]uint32
|
||||
for i := 0; i < nchar; i++ {
|
||||
if bitlen[i] > 16 {
|
||||
return false
|
||||
}
|
||||
count[bitlen[i]]++
|
||||
}
|
||||
for i := 1; i <= 16; i++ {
|
||||
start[i+1] = start[i] + count[i]<<(16-i)
|
||||
}
|
||||
if start[17] != 1<<16 {
|
||||
return false
|
||||
}
|
||||
jut := 16 - tablebits
|
||||
for i := uint(1); i <= tablebits; i++ {
|
||||
start[i] >>= jut
|
||||
weight[i] = 1 << (tablebits - i)
|
||||
}
|
||||
for i := tablebits + 1; i <= 16; i++ {
|
||||
weight[i] = 1 << (16 - i)
|
||||
}
|
||||
if i := start[tablebits+1] >> jut; i != 1<<16>>jut {
|
||||
for k := uint32(1) << tablebits; i < k; i++ {
|
||||
table[i] = 0
|
||||
}
|
||||
}
|
||||
avail := nchar
|
||||
mask := uint32(1) << (15 - tablebits)
|
||||
for ch := 0; ch < nchar; ch++ {
|
||||
l := uint(bitlen[ch])
|
||||
if l == 0 {
|
||||
continue
|
||||
}
|
||||
next := start[l] + weight[l]
|
||||
if l <= tablebits {
|
||||
if next > 1<<tablebits {
|
||||
return false
|
||||
}
|
||||
for i := start[l]; i < next; i++ {
|
||||
table[i] = uint16(ch)
|
||||
}
|
||||
} else {
|
||||
k := start[l]
|
||||
p := &table[k>>jut]
|
||||
for i := l - tablebits; i != 0; i-- {
|
||||
if *p == 0 {
|
||||
if avail >= len(h.left) {
|
||||
return false
|
||||
}
|
||||
h.left[avail], h.right[avail] = 0, 0
|
||||
*p = uint16(avail)
|
||||
avail++
|
||||
}
|
||||
if int(*p) >= len(h.left) {
|
||||
return false
|
||||
}
|
||||
if k&mask != 0 {
|
||||
p = &h.right[*p]
|
||||
} else {
|
||||
p = &h.left[*p]
|
||||
}
|
||||
k <<= 1
|
||||
}
|
||||
*p = uint16(ch)
|
||||
}
|
||||
start[l] = next
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// readPtLen reads the lengths of a pt code: nn codes, nbit bits for how
|
||||
// many; after the special'th (if any) a 2-bit count of zeros.
|
||||
func (h *huf) readPtLen(nn int, nbit uint, special int) bool {
|
||||
n := int(h.r.bits(nbit))
|
||||
if n == 0 {
|
||||
c := h.r.bits(nbit)
|
||||
for i := 0; i < nn; i++ {
|
||||
h.ptLen[i] = 0
|
||||
}
|
||||
for i := range h.ptTable {
|
||||
h.ptTable[i] = c
|
||||
}
|
||||
return true
|
||||
}
|
||||
if n > nn {
|
||||
return false
|
||||
}
|
||||
i := 0
|
||||
for i < n {
|
||||
c := int(h.r.peek() >> 13)
|
||||
if c == 7 {
|
||||
for mask := uint16(1) << 12; mask&h.r.peek() != 0; mask >>= 1 {
|
||||
c++
|
||||
if c > 16 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
if c < 7 {
|
||||
h.r.skip(3)
|
||||
} else {
|
||||
h.r.skip(uint(c - 3))
|
||||
}
|
||||
h.ptLen[i] = byte(c)
|
||||
i++
|
||||
if i == special {
|
||||
for z := int(h.r.bits(2)); z > 0 && i < nn; z-- {
|
||||
h.ptLen[i] = 0
|
||||
i++
|
||||
}
|
||||
}
|
||||
}
|
||||
for ; i < nn; i++ {
|
||||
h.ptLen[i] = 0
|
||||
}
|
||||
return h.makeTable(nn, h.ptLen[:], 8, h.ptTable[:])
|
||||
}
|
||||
|
||||
// readCLen reads the literals' and lengths' code lengths.
|
||||
func (h *huf) readCLen() bool {
|
||||
n := int(h.r.bits(hufCBit))
|
||||
if n == 0 {
|
||||
c := h.r.bits(hufCBit)
|
||||
for i := range h.cLen {
|
||||
h.cLen[i] = 0
|
||||
}
|
||||
for i := range h.cTable {
|
||||
h.cTable[i] = c
|
||||
}
|
||||
return true
|
||||
}
|
||||
if n > hufNC {
|
||||
return false
|
||||
}
|
||||
i := 0
|
||||
for i < n {
|
||||
c := int(h.ptTable[h.r.peek()>>8])
|
||||
if c >= hufNT {
|
||||
for mask := uint16(1) << 7; c >= hufNT; mask >>= 1 {
|
||||
if mask == 0 || c >= len(h.left) {
|
||||
return false
|
||||
}
|
||||
if h.r.peek()&mask != 0 {
|
||||
c = int(h.right[c])
|
||||
} else {
|
||||
c = int(h.left[c])
|
||||
}
|
||||
}
|
||||
}
|
||||
h.r.skip(uint(h.ptLen[c]))
|
||||
if c <= 2 {
|
||||
switch c {
|
||||
case 0:
|
||||
c = 1
|
||||
case 1:
|
||||
c = int(h.r.bits(4)) + 3
|
||||
default:
|
||||
c = int(h.r.bits(hufCBit)) + 20
|
||||
}
|
||||
for ; c > 0 && i < hufNC; c-- {
|
||||
h.cLen[i] = 0
|
||||
i++
|
||||
}
|
||||
} else {
|
||||
h.cLen[i] = byte(c - 2)
|
||||
i++
|
||||
}
|
||||
}
|
||||
for ; i < hufNC; i++ {
|
||||
h.cLen[i] = 0
|
||||
}
|
||||
return h.makeTable(hufNC, h.cLen[:], 12, h.cTable[:])
|
||||
}
|
||||
|
||||
// decodeC is the next literal (below 256) or length code; -1 if the
|
||||
// stream is broken.
|
||||
func (h *huf) decodeC() int {
|
||||
if h.blocksize == 0 {
|
||||
h.blocksize = int(h.r.bits(16))
|
||||
if !h.readPtLen(hufNT, hufTBit, 3) || !h.readCLen() || !h.readPtLen(h.np, h.pbit, -1) {
|
||||
return -1
|
||||
}
|
||||
}
|
||||
h.blocksize--
|
||||
j := int(h.cTable[h.r.peek()>>4])
|
||||
if j >= hufNC {
|
||||
for mask := uint16(1) << 3; j >= hufNC; mask >>= 1 {
|
||||
if mask == 0 || j >= len(h.left) {
|
||||
return -1
|
||||
}
|
||||
if h.r.peek()&mask != 0 {
|
||||
j = int(h.right[j])
|
||||
} else {
|
||||
j = int(h.left[j])
|
||||
}
|
||||
}
|
||||
}
|
||||
h.r.skip(uint(h.cLen[j]))
|
||||
return j
|
||||
}
|
||||
|
||||
// decodeP is the next distance (less one); -1 if the stream is broken.
|
||||
func (h *huf) decodeP() int {
|
||||
j := int(h.ptTable[h.r.peek()>>8])
|
||||
if j >= h.np {
|
||||
for mask := uint16(1) << 7; j >= h.np; mask >>= 1 {
|
||||
if mask == 0 || j >= len(h.left) {
|
||||
return -1
|
||||
}
|
||||
if h.r.peek()&mask != 0 {
|
||||
j = int(h.right[j])
|
||||
} else {
|
||||
j = int(h.left[j])
|
||||
}
|
||||
}
|
||||
}
|
||||
h.r.skip(uint(h.ptLen[j]))
|
||||
if j != 0 {
|
||||
j = 1<<(j-1) + int(h.r.bits(uint(j-1)))
|
||||
}
|
||||
return j
|
||||
}
|
||||
|
||||
// unhuf unpacks size bytes coded so, with distances of up to dicbit bits.
|
||||
// Before the start the dictionary is spaces, as LHA's is.
|
||||
func unhuf(src []byte, size int64, dicbit uint) ([]byte, error) {
|
||||
h := &huf{r: bitReader{b: src}, np: int(dicbit) + 1, pbit: 4}
|
||||
if dicbit > 13 {
|
||||
h.pbit = 5
|
||||
}
|
||||
out := make([]byte, 0, size)
|
||||
for int64(len(out)) < size {
|
||||
if h.r.overrun() {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
c := h.decodeC()
|
||||
switch {
|
||||
case c < 0:
|
||||
return nil, ErrCorrupt
|
||||
case c < 256:
|
||||
out = append(out, byte(c))
|
||||
default:
|
||||
n := c - 256 + hufThreshold
|
||||
p := h.decodeP()
|
||||
if p < 0 {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
from := len(out) - p - 1
|
||||
for ; n > 0 && int64(len(out)) < size; n-- {
|
||||
if from < 0 {
|
||||
out = append(out, ' ')
|
||||
} else {
|
||||
out = append(out, out[from])
|
||||
}
|
||||
from++
|
||||
}
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package archive
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// lhaDicbit is each LHA method's dictionary's bits (0: stored).
|
||||
var lhaDicbit = map[string]uint{"-lh0-": 0, "-lz4-": 0, "-lhd-": 0, "-lh4-": 12, "-lh5-": 13, "-lh6-": 15, "-lh7-": 16}
|
||||
|
||||
// walkLHA reads an LHA (LZH) archive: headers of levels 0, 1 and 2.
|
||||
func walkLHA(r io.ReaderAt, size int64, fn func(e Entry, open Opener) bool) error {
|
||||
off := int64(0)
|
||||
for off < size {
|
||||
first, err := readAt(r, size, off, 1)
|
||||
if err != nil || first[0] == 0 {
|
||||
return nil // the end (a 0, or the file ends)
|
||||
}
|
||||
base, err := readAt(r, size, off, 22)
|
||||
if err != nil {
|
||||
return ErrCorrupt
|
||||
}
|
||||
method := string(base[2:7])
|
||||
packed := int64(le32(base[7:]))
|
||||
orig := int64(le32(base[11:]))
|
||||
level := base[20]
|
||||
var name, dir string
|
||||
var mod time.Time
|
||||
var headerLen int64 // to the data
|
||||
var want uint16
|
||||
switch level {
|
||||
case 0, 1:
|
||||
hsize := int64(base[0])
|
||||
h, err := readAt(r, size, off, hsize+2)
|
||||
if err != nil || hsize < 22 {
|
||||
return ErrCorrupt
|
||||
}
|
||||
var sum byte
|
||||
for _, c := range h[2:] {
|
||||
sum += c
|
||||
}
|
||||
if sum != h[1] {
|
||||
return ErrCorrupt
|
||||
}
|
||||
mod = dosTime(le16(h[17:]), le16(h[15:]))
|
||||
nl := int64(h[21])
|
||||
if 22+nl+2 > hsize+2 {
|
||||
return ErrCorrupt
|
||||
}
|
||||
name = string(h[22 : 22+nl])
|
||||
want = le16(h[22+nl:])
|
||||
headerLen = hsize + 2
|
||||
if level == 1 {
|
||||
// the extended headers, whose size the packed size counts
|
||||
next := int64(le16(h[hsize:]))
|
||||
for next != 0 {
|
||||
x, err := readAt(r, size, off+headerLen, next)
|
||||
if err != nil || next < 3 {
|
||||
return ErrCorrupt
|
||||
}
|
||||
name, dir = lhaExt(x[:next-2], name, dir)
|
||||
headerLen += next
|
||||
packed -= next
|
||||
next = int64(le16(x[next-2:]))
|
||||
}
|
||||
}
|
||||
case 2:
|
||||
total := int64(le16(base[0:]))
|
||||
h, err := readAt(r, size, off, total)
|
||||
if err != nil || total < 26 {
|
||||
return ErrCorrupt
|
||||
}
|
||||
mod = time.Unix(int64(le32(h[15:])), 0)
|
||||
want = le16(h[21:])
|
||||
pos := int64(24)
|
||||
next := int64(le16(h[pos:]))
|
||||
pos += 2
|
||||
for next != 0 {
|
||||
if next < 3 || pos+next > total {
|
||||
return ErrCorrupt
|
||||
}
|
||||
x := h[pos : pos+next]
|
||||
name, dir = lhaExt(x[:next-2], name, dir)
|
||||
pos += next
|
||||
next = int64(le16(x[next-2:]))
|
||||
}
|
||||
headerLen = total
|
||||
default:
|
||||
return ErrMethod
|
||||
}
|
||||
if packed < 0 || orig < 0 {
|
||||
return ErrCorrupt
|
||||
}
|
||||
if dir != "" {
|
||||
name = dir + "/" + name
|
||||
}
|
||||
name = strings.ReplaceAll(name, "\\", "/")
|
||||
dataOff := off + headerLen
|
||||
dicbit, known := lhaDicbit[method]
|
||||
e := Entry{Name: name, Size: orig, Packed: packed, Method: method, Modified: mod, Dir: method == "-lhd-"}
|
||||
open := func(max int64) ([]byte, error) {
|
||||
if err := sized(orig, max); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !known {
|
||||
return nil, ErrMethod
|
||||
}
|
||||
src, err := readAt(r, size, dataOff, packed)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []byte
|
||||
if dicbit == 0 {
|
||||
if packed != orig {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
out = src
|
||||
} else if out, err = unhuf(src, orig, dicbit); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if crc16(out) != want {
|
||||
return nil, ErrChecksum
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
if !fn(e, open) {
|
||||
return nil
|
||||
}
|
||||
off = dataOff + packed
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// lhaExt reads an extended header: the file's name, its directory.
|
||||
func lhaExt(x []byte, name, dir string) (string, string) {
|
||||
if len(x) == 0 {
|
||||
return name, dir
|
||||
}
|
||||
switch x[0] {
|
||||
case 0x01:
|
||||
name = string(x[1:])
|
||||
case 0x02:
|
||||
dir = strings.Trim(strings.ReplaceAll(string(x[1:]), "\xff", "/"), "/")
|
||||
}
|
||||
return name, dir
|
||||
}
|
||||
|
||||
// writeLHA writes files stored (-lh0-), with level 0 headers.
|
||||
func writeLHA(w io.Writer, files []File) error {
|
||||
var b bytes.Buffer
|
||||
for _, f := range files {
|
||||
name := []byte(f.Name)
|
||||
if len(name) > 200 {
|
||||
name = name[:200]
|
||||
}
|
||||
hsize := 22 + len(name)
|
||||
h := make([]byte, hsize+2)
|
||||
h[0] = byte(hsize)
|
||||
copy(h[2:], "-lh0-")
|
||||
put32(h[7:], uint32(len(f.Data)))
|
||||
put32(h[11:], uint32(len(f.Data)))
|
||||
date, tm := dosStamp(f.Modified)
|
||||
put16(h[15:], tm)
|
||||
put16(h[17:], date)
|
||||
h[19] = 0x20 // archive
|
||||
h[20] = 0 // level 0
|
||||
h[21] = byte(len(name))
|
||||
copy(h[22:], name)
|
||||
put16(h[22+len(name):], crc16(f.Data))
|
||||
var sum byte
|
||||
for _, c := range h[2:] {
|
||||
sum += c
|
||||
}
|
||||
h[1] = sum
|
||||
b.Write(h)
|
||||
b.Write(f.Data)
|
||||
}
|
||||
b.WriteByte(0)
|
||||
_, err := w.Write(b.Bytes())
|
||||
return err
|
||||
}
|
||||
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
+16
@@ -0,0 +1,16 @@
|
||||
AREA:FSX_GEN
MSGID: 21:1/100 00000000
Line 0 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000001
Line 1 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000002
Line 2 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000003
Line 3 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000004
Line 4 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000005
Line 5 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000006
Line 6 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000007
Line 7 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000008
Line 8 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000009
Line 9 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 0000000a
Line 10 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 0000000b
Line 11 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 0000000c
Line 12 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 0000000d
Line 13 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 0000000e
Line 14 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 0000000f
Line 15 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000010
Line 16 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000011
Line 17 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000012
Line 18 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000013
Line 19 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000014
Line 20 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000015
Line 21 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000016
Line 22 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000017
Line 23 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000018
Line 24 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000019
Line 25 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 0000001a
Line 26 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 0000001b
Line 27 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 0000001c
Line 28 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 0000001d
Line 29 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 0000001e
Line 30 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 0000001f
Line 31 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000020
Line 32 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000021
Line 33 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000022
Line 34 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000023
Line 35 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000024
Line 36 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000025
Line 37 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000026
Line 38 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000027
Line 39 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000028
Line 40 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000029
Line 41 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 0000002a
Line 42 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 0000002b
Line 43 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 0000002c
Line 44 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 0000002d
Line 45 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 0000002e
Line 46 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 0000002f
Line 47 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000030
Line 48 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000031
Line 49 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000032
Line 50 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000033
Line 51 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000034
Line 52 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000035
Line 53 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000036
Line 54 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000037
Line 55 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000038
Line 56 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: 21:1/100 00000039
Line 57 of a message, hello hello hello world.
AREA:FSX_GEN
MSGID: Line truncated
|
||||
4GÞcl€l•{¦„ÖCµê×BM á]LXHò=¦÷6a�2ç â¦f�çô~„gåFÕ>Èâ¡%{Û%l›>O»I�Fïp0ËùSrRÜÎ×d¶£/» êá Ä©— 9u5+‡‹\ŠBØ„ÏLý§-Ž]Ù%‰-…*q"‡>èÕ‰Bz8R†\gŸœi”ä[б € aó}ä6ÝýÉ�nu¯eGϱB$‚ÜS+Ã�|–ë^P‰ä†º¨¥}žo¶] | ||||