fixes
This commit is contained in:
1 parent
c347d2418f
commit
1ad180a052
49 files changed
+6339
-89
No files matched your search
+363
@@ -0,0 +1,363 @@
|
||||
// Package cfb implements the Microsoft Compound File Binary File Format.
|
||||
package cfb
|
||||
|
||||
// https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-cfb/53989ce4-7b05-4f8d-829b-d08d6148375b
|
||||
// Note for myself:
|
||||
// Storage = Directory
|
||||
// Stream = File
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"unicode/utf16"
|
||||
|
||||
"github.com/pbnjay/grate"
|
||||
)
|
||||
|
||||
const fullAssertions = true
|
||||
|
||||
const (
|
||||
secFree uint32 = 0xFFFFFFFF // FREESECT
|
||||
secEndOfChain uint32 = 0xFFFFFFFE // ENDOFCHAIN
|
||||
secFAT uint32 = 0xFFFFFFFD // FATSECT
|
||||
secDIFAT uint32 = 0xFFFFFFFC // DIFSECT
|
||||
secReserved uint32 = 0xFFFFFFFB
|
||||
secMaxRegular uint32 = 0xFFFFFFFA // MAXREGSECT
|
||||
)
|
||||
|
||||
// Header of the Compound File MUST be at the beginning of the file (offset 0).
|
||||
type header struct {
|
||||
Signature uint64 // Identification signature for the compound file structure, and MUST be set to the value 0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1.
|
||||
ClassID [2]uint64 // Reserved and unused class ID that MUST be set to all zeroes (CLSID_NULL).
|
||||
MinorVersion uint16 // Version number for nonbreaking changes. This field SHOULD be set to 0x003E if the major version field is either 0x0003 or 0x0004.
|
||||
MajorVersion uint16 // Version number for breaking changes. This field MUST be set to either 0x0003 (version 3) or 0x0004 (version 4).
|
||||
ByteOrder uint16 // This field MUST be set to 0xFFFE. This field is a byte order mark for all integer fields, specifying little-endian byte order.
|
||||
SectorShift uint16 // This field MUST be set to 0x0009, or 0x000c, depending on the Major Version field. This field specifies the sector size of the compound file as a power of 2.
|
||||
MiniSectorShift uint16 // This field MUST be set to 0x0006. This field specifies the sector size of the Mini Stream as a power of 2. The sector size of the Mini Stream MUST be 64 bytes.
|
||||
Reserved1 [6]byte // This field MUST be set to all zeroes.
|
||||
NumDirectorySectors int32 // This integer field contains the count of the number of directory sectors in the compound file.
|
||||
NumFATSectors int32 // This integer field contains the count of the number of FAT sectors in the compound file.
|
||||
FirstDirectorySectorLocation uint32 // This integer field contains the starting sector number for the directory stream.
|
||||
TransactionSignature int32 // This integer field MAY contain a sequence number that is incremented every time the compound file is saved by an implementation that supports file transactions. This is the field that MUST be set to all zeroes if file transactions are not implemented.<1>
|
||||
MiniStreamCutoffSize int32 // This integer field MUST be set to 0x00001000. This field specifies the maximum size of a user-defined data stream that is allocated from the mini FAT and mini stream, and that cutoff is 4,096 bytes. Any user-defined data stream that is greater than or equal to this cutoff size must be allocated as normal sectors from the FAT.
|
||||
FirstMiniFATSectorLocation uint32 // This integer field contains the starting sector number for the mini FAT.
|
||||
NumMiniFATSectors int32 // This integer field contains the count of the number of mini FAT sectors in the compound file.
|
||||
FirstDIFATSectorLocation uint32 // This integer field contains the starting sector number for the DIFAT.
|
||||
NumDIFATSectors int32 // This integer field contains the count of the number of DIFAT sectors in the compound file.
|
||||
DIFAT [109]uint32 // This array of 32-bit integer fields contains the first 109 FAT sector locations of the compound file.
|
||||
}
|
||||
|
||||
type objectType byte
|
||||
|
||||
const (
|
||||
typeUnknown objectType = 0x00
|
||||
typeStorage objectType = 0x01
|
||||
typeStream objectType = 0x02
|
||||
typeRootStorage objectType = 0x05
|
||||
)
|
||||
|
||||
type directory struct {
|
||||
Name [32]uint16 // 32 utf16 characters
|
||||
NameByteLen int16 // length of Name in bytes
|
||||
ObjectType objectType
|
||||
ColorFlag byte // 0=red, 1=black
|
||||
LeftSiblingID uint32 // stream ids
|
||||
RightSiblingID uint32
|
||||
ChildID uint32
|
||||
ClassID [2]uint64 // GUID
|
||||
StateBits uint32
|
||||
CreationTime int64
|
||||
ModifiedTime int64
|
||||
StartingSectorLocation int32
|
||||
StreamSize uint64
|
||||
}
|
||||
|
||||
func (d *directory) String() string {
|
||||
if (d.NameByteLen&1) == 1 || d.NameByteLen > 64 {
|
||||
return "<invalid utf16 string>"
|
||||
}
|
||||
r16 := utf16.Decode(d.Name[:int(d.NameByteLen)/2])
|
||||
// trim off null terminator
|
||||
return string(r16[:len(r16)-1])
|
||||
}
|
||||
|
||||
// Document represents a Compound File Binary Format document.
|
||||
type Document struct {
|
||||
// the entire file, loaded into memory
|
||||
data []byte
|
||||
|
||||
// pre-parsed info
|
||||
header *header
|
||||
dir []*directory
|
||||
|
||||
// lookup tables for all the sectors
|
||||
fat []uint32
|
||||
minifat []uint32
|
||||
|
||||
ministreamstart uint32
|
||||
ministreamsize uint32
|
||||
}
|
||||
|
||||
func (d *Document) load(rx io.ReadSeeker) error {
|
||||
var err error
|
||||
d.data, err = ioutil.ReadAll(rx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
br := bytes.NewReader(d.data)
|
||||
|
||||
h := &header{}
|
||||
err = binary.Read(br, binary.LittleEndian, h)
|
||||
if h.Signature != 0xe11ab1a1e011cfd0 {
|
||||
return grate.ErrNotInFormat // errors.New("ole2: invalid format")
|
||||
}
|
||||
if h.ByteOrder != 0xFFFE {
|
||||
return grate.ErrNotInFormat //errors.New("ole2: invalid format")
|
||||
}
|
||||
if fullAssertions {
|
||||
if h.ClassID[0] != 0 || h.ClassID[1] != 0 {
|
||||
return grate.ErrNotInFormat //errors.New("ole2: invalid CLSID")
|
||||
}
|
||||
if h.MajorVersion != 3 && h.MajorVersion != 4 {
|
||||
return errors.New("ole2: unknown major version")
|
||||
}
|
||||
if h.MinorVersion != 0x3B && h.MinorVersion != 0x3E {
|
||||
log.Printf("WARNING MinorVersion = 0x%02x NOT 0x3E", h.MinorVersion)
|
||||
//return errors.New("ole2: unknown minor version")
|
||||
}
|
||||
|
||||
for _, v := range h.Reserved1 {
|
||||
if v != 0 {
|
||||
return errors.New("ole2: reserved section is non-zero")
|
||||
}
|
||||
}
|
||||
if h.MajorVersion == 3 {
|
||||
if h.SectorShift != 9 {
|
||||
return errors.New("ole2: invalid sector size")
|
||||
}
|
||||
if h.NumDirectorySectors != 0 {
|
||||
return errors.New("ole2: version 3 does not support directory sectors")
|
||||
}
|
||||
}
|
||||
if h.MajorVersion == 4 {
|
||||
if h.SectorShift != 12 {
|
||||
return errors.New("ole2: invalid sector size")
|
||||
}
|
||||
}
|
||||
if h.MiniSectorShift != 6 {
|
||||
return errors.New("ole2: invalid mini sector size")
|
||||
}
|
||||
if h.MiniStreamCutoffSize != 0x00001000 {
|
||||
return errors.New("ole2: invalid mini sector cutoff")
|
||||
}
|
||||
}
|
||||
d.header = h
|
||||
|
||||
numFATentries := (1 << (h.SectorShift - 2))
|
||||
le := binary.LittleEndian
|
||||
d.fat = make([]uint32, 0, numFATentries*int(1+d.header.NumFATSectors))
|
||||
d.minifat = make([]uint32, 0, numFATentries*int(1+h.NumMiniFATSectors))
|
||||
|
||||
// step 1: read the DIFAT sector list
|
||||
for i := 0; i < 109; i++ {
|
||||
sid := h.DIFAT[i]
|
||||
if sid == secFree {
|
||||
break
|
||||
}
|
||||
offs := int64(1+sid) << int32(h.SectorShift)
|
||||
if offs >= int64(len(d.data)) {
|
||||
return errors.New("xls/cfb: unable to load file")
|
||||
}
|
||||
sector := d.data[offs:]
|
||||
for j := 0; j < numFATentries; j++ {
|
||||
sid2 := le.Uint32(sector)
|
||||
d.fat = append(d.fat, sid2)
|
||||
sector = sector[4:]
|
||||
}
|
||||
}
|
||||
if h.NumDIFATSectors > 0 {
|
||||
sid1 := h.FirstDIFATSectorLocation
|
||||
|
||||
for sid1 != secEndOfChain {
|
||||
offs := int64(1+sid1) << int32(h.SectorShift)
|
||||
difatSector := d.data[offs:]
|
||||
|
||||
for i := 0; i < numFATentries-1; i++ {
|
||||
sid2 := le.Uint32(difatSector)
|
||||
if sid2 == secFree || sid2 == secEndOfChain {
|
||||
difatSector = difatSector[4:]
|
||||
continue
|
||||
}
|
||||
|
||||
offs := int64(1+sid2) << int32(h.SectorShift)
|
||||
if offs >= int64(len(d.data)) {
|
||||
return errors.New("xls/cfb: unable to load file")
|
||||
}
|
||||
sector := d.data[offs:]
|
||||
for j := 0; j < numFATentries; j++ {
|
||||
sid3 := le.Uint32(sector)
|
||||
d.fat = append(d.fat, sid3)
|
||||
sector = sector[4:]
|
||||
}
|
||||
|
||||
difatSector = difatSector[4:]
|
||||
}
|
||||
// chain the next DIFAT sector
|
||||
sid1 = le.Uint32(difatSector)
|
||||
}
|
||||
}
|
||||
|
||||
// step 2: read the mini FAT
|
||||
sid := h.FirstMiniFATSectorLocation
|
||||
for sid != secEndOfChain {
|
||||
offs := int64(1+sid) << int32(h.SectorShift)
|
||||
if offs >= int64(len(d.data)) {
|
||||
return errors.New("xls/cfb: unable to load file")
|
||||
}
|
||||
sector := d.data[offs:]
|
||||
for j := 0; j < numFATentries; j++ {
|
||||
sid = le.Uint32(sector)
|
||||
d.minifat = append(d.minifat, sid)
|
||||
sector = sector[4:]
|
||||
}
|
||||
|
||||
if len(d.minifat) >= int(h.NumMiniFATSectors) {
|
||||
break
|
||||
}
|
||||
|
||||
// chain the next mini FAT sector
|
||||
sid = le.Uint32(sector)
|
||||
}
|
||||
|
||||
// step 3: read the Directory Entries
|
||||
err = d.buildDirs(br)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *Document) buildDirs(br *bytes.Reader) error {
|
||||
h := d.header
|
||||
le := binary.LittleEndian
|
||||
|
||||
// step 2: read the Directory
|
||||
sid := h.FirstDirectorySectorLocation
|
||||
offs := int64(1+sid) << int64(h.SectorShift)
|
||||
br.Seek(offs, io.SeekStart)
|
||||
|
||||
for j := 0; j < 4; j++ {
|
||||
dirent := &directory{}
|
||||
binary.Read(br, le, dirent)
|
||||
if d.header.MajorVersion == 3 {
|
||||
// mask out upper 32bits
|
||||
dirent.StreamSize = dirent.StreamSize & 0xFFFFFFFF
|
||||
}
|
||||
|
||||
switch dirent.ObjectType {
|
||||
case typeRootStorage:
|
||||
d.ministreamstart = uint32(dirent.StartingSectorLocation)
|
||||
d.ministreamsize = uint32(dirent.StreamSize)
|
||||
case typeStorage:
|
||||
//log.Println("got a storage? what to do now?")
|
||||
case typeStream:
|
||||
/*
|
||||
var freader io.Reader
|
||||
if dirent.StreamSize < uint64(d.header.MiniStreamCutoffSize) {
|
||||
freader = d.getMiniStreamReader(uint32(dirent.StartingSectorLocation), dirent.StreamSize)
|
||||
} else if dirent.StreamSize != 0 {
|
||||
freader = d.getStreamReader(uint32(dirent.StartingSectorLocation), dirent.StreamSize)
|
||||
}
|
||||
*/
|
||||
case typeUnknown:
|
||||
return nil
|
||||
}
|
||||
d.dir = append(d.dir, dirent)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Document) getStreamReader(sid uint32, size uint64) (io.ReadSeeker, error) {
|
||||
// NB streamData is a slice of slices of the raw data, so this is the
|
||||
// only allocation - for the (much smaller) list of sector slices
|
||||
streamData := make([][]byte, 1+(size>>d.header.SectorShift))
|
||||
|
||||
x := 0
|
||||
secSize := int64(1) << int32(d.header.SectorShift)
|
||||
for sid != secEndOfChain && sid != secFree {
|
||||
offs := int64(1+sid) << int64(d.header.SectorShift)
|
||||
if offs > int64(len(d.data)) {
|
||||
return nil, errors.New("ole2: corrupt data format")
|
||||
}
|
||||
slice := d.data[offs : offs+secSize]
|
||||
if size < uint64(len(slice)) {
|
||||
slice = slice[:size]
|
||||
size = 0
|
||||
} else {
|
||||
size -= uint64(len(slice))
|
||||
}
|
||||
streamData[x] = slice
|
||||
if size == 0 {
|
||||
break
|
||||
}
|
||||
sid = d.fat[sid]
|
||||
x++
|
||||
}
|
||||
if size != 0 {
|
||||
return nil, errors.New("ole2: incomplete read")
|
||||
}
|
||||
|
||||
return &SliceReader{Data: streamData}, nil
|
||||
}
|
||||
|
||||
func (d *Document) getMiniStreamReader(sid uint32, size uint64) (io.ReadSeeker, error) {
|
||||
// TODO: move into a separate cache so we don't recalculate it each time
|
||||
fatStreamData := make([][]byte, 1+(d.ministreamsize>>d.header.SectorShift))
|
||||
|
||||
// NB streamData is a slice of slices of the raw data, so this is the
|
||||
// only allocation - for the (much smaller) list of sector slices
|
||||
streamData := make([][]byte, 1+(size>>d.header.MiniSectorShift))
|
||||
|
||||
x := 0
|
||||
fsid := d.ministreamstart
|
||||
fsize := uint64(d.ministreamsize)
|
||||
secSize := int64(1) << int64(d.header.SectorShift)
|
||||
for fsid != secEndOfChain && fsid != secFree {
|
||||
offs := int64(1+fsid) << int64(d.header.SectorShift)
|
||||
slice := d.data[offs : offs+secSize]
|
||||
if fsize < uint64(len(slice)) {
|
||||
slice = slice[:fsize]
|
||||
fsize = 0
|
||||
} else {
|
||||
fsize -= uint64(len(slice))
|
||||
}
|
||||
fatStreamData[x] = slice
|
||||
x++
|
||||
fsid = d.fat[fsid]
|
||||
}
|
||||
|
||||
x = 0
|
||||
miniSecSize := int64(1) << int64(d.header.MiniSectorShift)
|
||||
for sid != secEndOfChain && sid != secFree {
|
||||
offs := int64(sid) << int64(d.header.MiniSectorShift)
|
||||
|
||||
so, si := offs/secSize, offs%secSize
|
||||
data := fatStreamData[so]
|
||||
|
||||
slice := data[si : si+miniSecSize]
|
||||
if size < uint64(len(slice)) {
|
||||
slice = slice[:size]
|
||||
size = 0
|
||||
} else {
|
||||
size -= uint64(len(slice))
|
||||
}
|
||||
streamData[x] = slice
|
||||
x++
|
||||
sid = d.minifat[sid]
|
||||
}
|
||||
|
||||
return &SliceReader{Data: streamData}, nil
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package cfb
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
// Open a Compound File Binary Format document.
|
||||
func Open(filename string) (*Document, error) {
|
||||
d := &Document{}
|
||||
f, err := os.Open(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = d.load(f)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// List the streams contained in the document.
|
||||
func (d *Document) List() ([]string, error) {
|
||||
var res []string
|
||||
for _, e := range d.dir {
|
||||
if e.ObjectType == typeStream {
|
||||
res = append(res, e.String())
|
||||
}
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// Open the named stream contained in the document.
|
||||
func (d *Document) Open(name string) (io.ReadSeeker, error) {
|
||||
for _, e := range d.dir {
|
||||
if e.String() == name && e.ObjectType == typeStream {
|
||||
if e.StreamSize < uint64(d.header.MiniStreamCutoffSize) {
|
||||
return d.getMiniStreamReader(uint32(e.StartingSectorLocation), e.StreamSize)
|
||||
} else if e.StreamSize != 0 {
|
||||
return d.getStreamReader(uint32(e.StartingSectorLocation), e.StreamSize)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("cfb: stream '%s' not found", name)
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package cfb
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
)
|
||||
|
||||
// SliceReader wraps a list of slices as a io.ReadSeeker that
|
||||
// can transparently merge them into a single coherent stream.
|
||||
type SliceReader struct {
|
||||
CSize []int64
|
||||
Data [][]byte
|
||||
Index uint
|
||||
Offset uint
|
||||
}
|
||||
|
||||
// Read implements the io.Reader interface.
|
||||
func (s *SliceReader) Read(b []byte) (int, error) {
|
||||
if s.Index >= uint(len(s.Data)) {
|
||||
return 0, io.EOF
|
||||
}
|
||||
n := copy(b, s.Data[s.Index][s.Offset:])
|
||||
if n > 0 {
|
||||
s.Offset += uint(n)
|
||||
if s.Offset == uint(len(s.Data[s.Index])) {
|
||||
s.Offset = 0
|
||||
s.Index++
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
var x io.Seeker
|
||||
|
||||
// Seek implements the io.Seeker interface.
|
||||
func (s *SliceReader) Seek(offset int64, whence int) (int64, error) {
|
||||
if len(s.CSize) != len(s.Data) {
|
||||
// calculate the cumulative block size cache
|
||||
s.CSize = make([]int64, len(s.Data))
|
||||
sz := int64(0)
|
||||
for i, d := range s.Data {
|
||||
s.CSize[i] = sz
|
||||
sz += int64(len(d))
|
||||
}
|
||||
}
|
||||
if s.Index >= uint(len(s.CSize)) {
|
||||
s.Index = uint(len(s.CSize) - 1)
|
||||
s.Offset = uint(len(s.Data[s.Index]))
|
||||
}
|
||||
// current offset in stream
|
||||
trueOffset := int64(s.Offset) + s.CSize[int(s.Index)]
|
||||
if offset == 0 && whence == io.SeekCurrent {
|
||||
// just asking for current position
|
||||
return trueOffset, nil
|
||||
}
|
||||
|
||||
switch whence {
|
||||
case io.SeekStart:
|
||||
if offset < 0 {
|
||||
return -1, errors.New("xls: invalid seek offset")
|
||||
}
|
||||
s.Index = 0
|
||||
s.Offset = 0
|
||||
trueOffset = 0
|
||||
|
||||
case io.SeekEnd:
|
||||
if offset > 0 {
|
||||
return -1, errors.New("xls: invalid seek offset")
|
||||
}
|
||||
|
||||
s.Index = uint(len(s.Data) - 1)
|
||||
s.Offset = uint(len(s.Data[s.Index]))
|
||||
trueOffset = int64(s.Offset) + s.CSize[s.Index]
|
||||
|
||||
default:
|
||||
// current position already defined
|
||||
}
|
||||
|
||||
wantOffset := offset + trueOffset
|
||||
for trueOffset != wantOffset {
|
||||
loOffset := s.CSize[int(s.Index)]
|
||||
hiOffset := s.CSize[int(s.Index)] + int64(len(s.Data[s.Index]))
|
||||
if wantOffset > loOffset && wantOffset < hiOffset {
|
||||
s.Offset = uint(wantOffset - loOffset)
|
||||
return wantOffset, nil
|
||||
}
|
||||
|
||||
if trueOffset > wantOffset {
|
||||
s.Index--
|
||||
s.Offset = 0
|
||||
trueOffset = s.CSize[int(s.Index)]
|
||||
} else if trueOffset < wantOffset {
|
||||
s.Index++
|
||||
s.Offset = 0
|
||||
trueOffset = s.CSize[int(s.Index)]
|
||||
}
|
||||
}
|
||||
return wantOffset, nil
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
// Package crypto implements excel encryption algorithms from the
|
||||
// MS-OFFCRYPTO design specs. Currently only standard/basic RC4
|
||||
// "obfuscation" is supported.
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// Decryptor describes methods to decrypt an excel sheet.
|
||||
type Decryptor interface {
|
||||
// SetPassword for the decryption.
|
||||
SetPassword(password []byte)
|
||||
|
||||
// Read implements the io.Reader interface.
|
||||
Read(p []byte) (n int, err error)
|
||||
|
||||
// Write implements the io.Writer interface.
|
||||
Write(p []byte) (n int, err error)
|
||||
|
||||
// Bytes returns the decrypted data.
|
||||
Bytes() []byte
|
||||
|
||||
// Flush tells the decryptor to decrypt the latest block.
|
||||
Flush()
|
||||
|
||||
// Reset the decryptor, and clear all written and readable data.
|
||||
Reset()
|
||||
}
|
||||
|
||||
// Algorithms designed based on specs in MS-OFFCRYPTO:
|
||||
// https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-offcrypto/3c34d72a-1a61-4b52-a893-196f9157f083
|
||||
|
||||
// Important notes from MS-XLS section 2.2.10:
|
||||
// https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-xls/cd03cb5f-ca02-4934-a391-bb674cb8aa06
|
||||
|
||||
// When obfuscating or encrypting BIFF records in these streams the record type and
|
||||
// record size components MUST NOT be obfuscated or encrypted.
|
||||
// In addition the following records MUST NOT be obfuscated or encrypted:
|
||||
// BOF (section 2.4.21), FilePass (section 2.4.117), UsrExcl (section 2.4.339),
|
||||
// FileLock (section 2.4.116), InterfaceHdr (section 2.4.146), RRDInfo (section 2.4.227),
|
||||
// and RRDHead (section 2.4.226). Additionally, the lbPlyPos field of the BoundSheet8
|
||||
// record (section 2.4.28) MUST NOT be encrypted.
|
||||
|
||||
// For RC4 encryption and RC4 CryptoAPI encryption, the Unicode password string is used
|
||||
// to generate the encryption key as specified in [MS-OFFCRYPTO] section 2.3.6.2 or
|
||||
// [MS-OFFCRYPTO] section 2.3.5.2 depending on the RC4 algorithm used. The record data
|
||||
// is then encrypted by the specific RC4 algorithm in 1024-byte blocks. The block number
|
||||
// is set to zero at the beginning of every BIFF record stream, and incremented by one
|
||||
// at each 1024-byte boundary. Bytes to be encrypted are passed into the RC4 encryption
|
||||
// function and then written to the stream. For unencrypted records and the record
|
||||
// headers consisting of the record type and record size, a byte buffer of all zeros,
|
||||
// of the same size as the section of unencrypted bytes, is passed into the RC4
|
||||
// encryption function. The results are then ignored and the unencrypted bytes are
|
||||
// written to the stream.
|
||||
|
||||
// DefaultXLSPassword is the default encryption password defined by note
|
||||
// <100> Section 2.4.191: If the value of the wPassword field of the Password record in
|
||||
// the Globals Substream is not 0x0000, Excel 97, Excel 2000, Excel 2002, Office Excel
|
||||
// 2003, Office Excel 2007, and Excel 2010 encrypt the document as specified in [MS-OFFCRYPTO],
|
||||
// section 2.3. If an encryption password is not specified or the workbook or sheet is only
|
||||
// protected, the document is encrypted with the default password of:
|
||||
|
||||
// DefaultXLSPassword is the default Excel encryption password.
|
||||
var DefaultXLSPassword = "VelvetSweatshop"
|
||||
|
||||
/////////////
|
||||
|
||||
// 2.3.6.1
|
||||
type basicRC4Encryption struct {
|
||||
MajorVersion uint16
|
||||
MinorVersion uint16
|
||||
Salt [16]byte
|
||||
Verifier [16]byte
|
||||
VerifierHash [16]byte
|
||||
}
|
||||
|
||||
// NewBasicRC4 implements the standard RC4 decryption.
|
||||
func NewBasicRC4(data []byte) (Decryptor, error) {
|
||||
h := basicRC4Encryption{}
|
||||
b := bytes.NewReader(data)
|
||||
err := binary.Read(b, binary.LittleEndian, &h)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if h.MinorVersion != 1 {
|
||||
return nil, fmt.Errorf("xls: unknown basic-RC4 minor version %d (%d byte record)",
|
||||
h.MinorVersion, len(data))
|
||||
}
|
||||
if len(data) != 52 {
|
||||
return nil, fmt.Errorf("xls: data length is invalid (expected 52 bytes, got %d)",
|
||||
len(data))
|
||||
}
|
||||
|
||||
d := &rc4Writer{
|
||||
Salt: make([]byte, len(h.Salt)),
|
||||
}
|
||||
copy(d.Salt, h.Salt[:])
|
||||
|
||||
return d, d.Verify(h.Verifier[:], h.VerifierHash[:])
|
||||
}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/md5"
|
||||
"crypto/rc4"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
var _ Decryptor = &rc4Writer{}
|
||||
|
||||
func (d *rc4Writer) Write(data []byte) (n int, err error) {
|
||||
x := len(data)
|
||||
for len(data) > 0 {
|
||||
n := copy(d.bytes[d.offset:], data)
|
||||
d.offset += n
|
||||
if d.offset >= 1024 {
|
||||
if d.offset != 1024 {
|
||||
panic("invalid offset from write")
|
||||
}
|
||||
d.Flush()
|
||||
}
|
||||
data = data[n:]
|
||||
}
|
||||
return x, nil
|
||||
}
|
||||
|
||||
func (d *rc4Writer) Read(data []byte) (n int, err error) {
|
||||
return d.buf.Read(data)
|
||||
}
|
||||
|
||||
// Reset to block 0, and clear all written and readable data.
|
||||
func (d *rc4Writer) Reset() {
|
||||
d.block = 0
|
||||
d.offset = 0
|
||||
d.buf.Reset()
|
||||
}
|
||||
|
||||
// Flush tells the decryptor to decrypt the latest block.
|
||||
func (d *rc4Writer) Flush() {
|
||||
var zeros [1024]byte
|
||||
|
||||
endpad := 0
|
||||
if d.offset < 1024 {
|
||||
endpad = copy(d.bytes[d.offset:], zeros[:])
|
||||
d.offset += endpad
|
||||
}
|
||||
if d.offset != 1024 {
|
||||
panic("invalid offset fill")
|
||||
}
|
||||
|
||||
// decrypt and write results to output buffer
|
||||
d.startBlock()
|
||||
d.dec.XORKeyStream(d.bytes[:], d.bytes[:])
|
||||
d.buf.Write(d.bytes[:1024-endpad])
|
||||
|
||||
d.offset = 0
|
||||
d.block++
|
||||
}
|
||||
|
||||
// SetPassword for the decryption.
|
||||
func (d *rc4Writer) SetPassword(password []byte) {
|
||||
d.Password = make([]rune, len(password))
|
||||
for i, p := range password {
|
||||
d.Password[i] = rune(p)
|
||||
}
|
||||
|
||||
/// compute the first part of the encryption key
|
||||
result := generateStd97Key(d.Password, d.Salt)
|
||||
d.encKey = make([]byte, len(result))
|
||||
copy(d.encKey, result)
|
||||
}
|
||||
|
||||
type rc4Writer struct {
|
||||
block uint32
|
||||
offset int
|
||||
bytes [1024]byte
|
||||
|
||||
// records the decrypted data
|
||||
buf bytes.Buffer
|
||||
|
||||
///////
|
||||
|
||||
// decrypter for RC4 content streams
|
||||
dec *rc4.Cipher
|
||||
|
||||
cipherKey []byte // H1 per 2.3.6.2
|
||||
encKey []byte // Hfinal per 2.3.6.2
|
||||
|
||||
Salt []byte
|
||||
Password []rune
|
||||
}
|
||||
|
||||
func (d *rc4Writer) Bytes() []byte {
|
||||
return d.buf.Bytes()
|
||||
}
|
||||
|
||||
func (d *rc4Writer) Verify(everifier, everifierHash []byte) error {
|
||||
d.Reset()
|
||||
d.startBlock()
|
||||
|
||||
var temp1 [16]byte
|
||||
var temp2 [16]byte
|
||||
d.dec.XORKeyStream(temp1[:], everifier)
|
||||
d.dec.XORKeyStream(temp2[:], everifierHash)
|
||||
|
||||
newhash := md5.Sum(temp1[:])
|
||||
for i, c := range newhash {
|
||||
if temp2[i] != c {
|
||||
return fmt.Errorf("verification failed")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/////////////////////
|
||||
|
||||
func (d *rc4Writer) startBlock() {
|
||||
if d.encKey == nil {
|
||||
d.SetPassword([]byte(DefaultXLSPassword))
|
||||
}
|
||||
|
||||
d.cipherKey = make([]byte, 16)
|
||||
copy(d.cipherKey, d.encKey[:5])
|
||||
binary.LittleEndian.PutUint32(d.cipherKey[5:], d.block)
|
||||
mhash := md5.Sum(d.cipherKey[:9])
|
||||
d.dec, _ = rc4.NewCipher(mhash[:])
|
||||
}
|
||||
|
||||
func generateStd97Key(passData []rune, salt []byte) []byte {
|
||||
if len(passData) == 0 || len(salt) != 16 {
|
||||
panic("invalid keygen material")
|
||||
}
|
||||
|
||||
passBytes := make([]byte, len(passData)*2)
|
||||
|
||||
for i, c := range passData {
|
||||
binary.LittleEndian.PutUint16(passBytes[2*i:], uint16(c))
|
||||
}
|
||||
|
||||
// digest the IV then copy back into pKeyData
|
||||
h0 := md5.Sum(passBytes)
|
||||
|
||||
// now do the final set of keygen ops
|
||||
msum := md5.New()
|
||||
for i := 0; i < 16; i++ {
|
||||
msum.Write(h0[:5])
|
||||
msum.Write(salt)
|
||||
}
|
||||
// return H1
|
||||
temp := make([]byte, 0, 16)
|
||||
temp = msum.Sum(temp)
|
||||
return temp
|
||||
}
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
package xls
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode/utf16"
|
||||
)
|
||||
|
||||
func decodeHyperlinks(raw []byte) (displayText, linkText string, err error) {
|
||||
raw = raw[16:] // skip classid
|
||||
slen := binary.LittleEndian.Uint32(raw[:4])
|
||||
if slen != 2 {
|
||||
return "", "", errors.New("xls: unknown hyperlink version")
|
||||
}
|
||||
|
||||
flags := binary.LittleEndian.Uint32(raw[4:8])
|
||||
raw = raw[8:]
|
||||
if (flags & hlstmfHasDisplayName) != 0 {
|
||||
slen = binary.LittleEndian.Uint32(raw[:4])
|
||||
raw = raw[4:]
|
||||
us := make([]uint16, slen)
|
||||
for i := 0; i < int(slen); i++ {
|
||||
us[i] = binary.LittleEndian.Uint16(raw)
|
||||
raw = raw[2:]
|
||||
}
|
||||
displayText = string(utf16.Decode(us))
|
||||
}
|
||||
|
||||
if (flags & hlstmfHasFrameName) != 0 {
|
||||
// skip a HyperlinkString containing target Frame
|
||||
slen = binary.LittleEndian.Uint32(raw[:4])
|
||||
raw = raw[4+(slen*2):]
|
||||
}
|
||||
|
||||
if (flags & hlstmfHasMoniker) != 0 {
|
||||
if (flags & hlstmfMonikerSavedAsStr) != 0 {
|
||||
// read HyperlinkString containing the URL
|
||||
slen = binary.LittleEndian.Uint32(raw[:4])
|
||||
raw = raw[4:]
|
||||
us := make([]uint16, slen)
|
||||
for i := 0; i < int(slen); i++ {
|
||||
us[i] = binary.LittleEndian.Uint16(raw)
|
||||
raw = raw[2:]
|
||||
}
|
||||
linkText = string(utf16.Decode(us))
|
||||
|
||||
} else {
|
||||
n := 0
|
||||
var err error
|
||||
linkText, n, err = parseHyperlinkMoniker(raw)
|
||||
raw = raw[n:]
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (flags & hlstmfHasLocationStr) != 0 {
|
||||
slen = binary.LittleEndian.Uint32(raw[:4])
|
||||
raw = raw[4:]
|
||||
us := make([]uint16, slen)
|
||||
for i := 0; i < int(slen); i++ {
|
||||
us[i] = binary.LittleEndian.Uint16(raw)
|
||||
raw = raw[2:]
|
||||
}
|
||||
linkText = string(utf16.Decode(us))
|
||||
}
|
||||
|
||||
linkText = strings.Trim(linkText, " \v\f\t\r\n\x00")
|
||||
displayText = strings.Trim(displayText, " \v\f\t\r\n\x00")
|
||||
return
|
||||
}
|
||||
|
||||
func parseHyperlinkMoniker(raw []byte) (string, int, error) {
|
||||
classid := raw[:16]
|
||||
no := 16
|
||||
|
||||
isURLMoniker := true
|
||||
isFileMoniker := true
|
||||
urlMonikerClassID := [16]byte{0xE0, 0xC9, 0xEA, 0x79, 0xF9, 0xBA, 0xCE, 0x11, 0x8C, 0x82, 0x00, 0xAA, 0x00, 0x4B, 0xA9, 0x0B}
|
||||
fileMonikerClassID := [16]byte{0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}
|
||||
for i, b := range classid {
|
||||
if urlMonikerClassID[i] != b {
|
||||
isURLMoniker = false
|
||||
}
|
||||
if fileMonikerClassID[i] != b {
|
||||
isFileMoniker = false
|
||||
}
|
||||
}
|
||||
if isURLMoniker {
|
||||
length := binary.LittleEndian.Uint32(raw[no:])
|
||||
no += 4
|
||||
length /= 2
|
||||
buf := make([]uint16, length)
|
||||
for i := 0; i < int(length); i++ {
|
||||
buf[i] = binary.LittleEndian.Uint16(raw[no:])
|
||||
no += 2
|
||||
}
|
||||
if length > 12 && buf[length-13] == 0 {
|
||||
buf = buf[:length-12]
|
||||
}
|
||||
return string(utf16.Decode(buf)), no, nil
|
||||
}
|
||||
if isFileMoniker {
|
||||
//x := binary.LittleEndian.Uint16(raw[no:]) //cAnti
|
||||
length := binary.LittleEndian.Uint32(raw[no+2:]) //ansiLength
|
||||
no += 6
|
||||
buf := raw[no : no+int(length)]
|
||||
|
||||
// skip 24 more bytes for misc fixed properties
|
||||
no += int(length) + 24
|
||||
|
||||
length = binary.LittleEndian.Uint32(raw[no:]) // cbUnicodePathSize
|
||||
no += 4
|
||||
if length > 0 {
|
||||
no += 6
|
||||
length -= 6
|
||||
buf2 := make([]uint16, length/2)
|
||||
for i := 0; i < int(length/2); i++ {
|
||||
buf2[i] = binary.LittleEndian.Uint16(raw[no:])
|
||||
no += 2
|
||||
}
|
||||
return string(utf16.Decode(buf2)), no, nil
|
||||
}
|
||||
|
||||
return string(buf), no, nil
|
||||
}
|
||||
|
||||
return "", 0, fmt.Errorf("xls: unknown moniker classid")
|
||||
}
|
||||
|
||||
// HLink flags
|
||||
const (
|
||||
hlstmfHasMoniker = uint32(0x001)
|
||||
hlstmfIsAbsolute = uint32(0x002)
|
||||
hlstmfSiteGaveDisplayName = uint32(0x004)
|
||||
hlstmfHasLocationStr = uint32(0x008)
|
||||
hlstmfHasDisplayName = uint32(0x010)
|
||||
hlstmfHasGUID = uint32(0x020)
|
||||
hlstmfHasCreationTime = uint32(0x040)
|
||||
hlstmfHasFrameName = uint32(0x080)
|
||||
hlstmfMonikerSavedAsStr = uint32(0x100)
|
||||
hlstmfAbsFromGetdataRel = uint32(0x200)
|
||||
)
|
||||
+1076
File diff suppressed because it is too large.
Load diff
+463
@@ -0,0 +1,463 @@
|
||||
package xls
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"log"
|
||||
"math"
|
||||
"unicode/utf16"
|
||||
|
||||
"github.com/pbnjay/grate"
|
||||
"github.com/pbnjay/grate/commonxl"
|
||||
)
|
||||
|
||||
// List (visible) sheet names from the workbook.
|
||||
func (b *WorkBook) List() ([]string, error) {
|
||||
res := make([]string, 0, len(b.sheets))
|
||||
for _, s := range b.sheets {
|
||||
if (s.HiddenState & 0x03) == 0 {
|
||||
res = append(res, s.Name)
|
||||
}
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// ListHidden sheet names in the workbook.
|
||||
func (b *WorkBook) ListHidden() ([]string, error) {
|
||||
res := make([]string, 0, len(b.sheets))
|
||||
for _, s := range b.sheets {
|
||||
if (s.HiddenState & 0x03) != 0 {
|
||||
res = append(res, s.Name)
|
||||
}
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// Get opens the named worksheet and return an iterator for its contents.
|
||||
func (b *WorkBook) Get(sheetName string) (grate.Collection, error) {
|
||||
for _, s := range b.sheets {
|
||||
if s.Name == sheetName {
|
||||
ss := b.pos2substream[int64(s.Position)]
|
||||
return b.parseSheet(s, ss)
|
||||
}
|
||||
}
|
||||
return nil, errors.New("xls: sheet not found")
|
||||
}
|
||||
|
||||
func (b *WorkBook) parseSheet(s *boundSheet, ss int) (*commonxl.Sheet, error) {
|
||||
res := &commonxl.Sheet{
|
||||
Formatter: &b.nfmt,
|
||||
}
|
||||
var minRow, maxRow uint32
|
||||
var minCol, maxCol uint16
|
||||
|
||||
// temporary string buffer
|
||||
us := make([]uint16, 8224)
|
||||
|
||||
inSubstream := 0
|
||||
for idx, r := range b.substreams[ss] {
|
||||
if inSubstream > 0 {
|
||||
if r.RecType == RecTypeEOF {
|
||||
inSubstream--
|
||||
}
|
||||
continue
|
||||
}
|
||||
switch r.RecType {
|
||||
case RecTypeBOF:
|
||||
// a BOF inside a sheet usually means embedded content like a chart
|
||||
// (which we aren't interested in). So we we set a flag and wait
|
||||
// for the EOF for that content block.
|
||||
if idx > 0 {
|
||||
inSubstream++
|
||||
continue
|
||||
}
|
||||
case RecTypeWsBool:
|
||||
if (r.Data[1] & 0x10) != 0 {
|
||||
// it's a dialog
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
case RecTypeDimensions:
|
||||
// max = 0-based index of the row AFTER the last valid index
|
||||
minRow = binary.LittleEndian.Uint32(r.Data[:4])
|
||||
maxRow = binary.LittleEndian.Uint32(r.Data[4:8]) // max = 0x010000
|
||||
minCol = binary.LittleEndian.Uint16(r.Data[8:10])
|
||||
maxCol = binary.LittleEndian.Uint16(r.Data[10:12]) // max = 0x000100
|
||||
if grate.Debug {
|
||||
log.Printf(" Sheet dimensions (%d, %d) - (%d,%d)",
|
||||
minCol, minRow, maxCol, maxRow)
|
||||
}
|
||||
if minRow > 0x0000FFFF || maxRow > 0x00010000 {
|
||||
log.Println("invalid dimensions")
|
||||
}
|
||||
if minCol > 0x00FF || maxCol > 0x0100 {
|
||||
log.Println("invalid dimensions")
|
||||
}
|
||||
|
||||
// pre-allocate cells
|
||||
res.Resize(int(maxRow), int(maxCol))
|
||||
}
|
||||
}
|
||||
inSubstream = 0
|
||||
|
||||
var formulaRow, formulaCol uint16
|
||||
for ridx, r := range b.substreams[ss] {
|
||||
if inSubstream > 0 {
|
||||
if r.RecType == RecTypeEOF {
|
||||
inSubstream--
|
||||
} else if grate.Debug {
|
||||
log.Println(" Unhandled sheet substream record type:", r.RecType, ridx)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// sec 2.1.7.20.6 Common Productions ABNF:
|
||||
/*
|
||||
CELLTABLE = 1*(1*Row *CELL 1*DBCell) *EntExU2
|
||||
CELL = FORMULA / Blank / MulBlank / RK / MulRk / BoolErr / Number / LabelSst
|
||||
FORMULA = [Uncalced] Formula [Array / Table / ShrFmla / SUB] [String *Continue]
|
||||
|
||||
Not parsed form the list above:
|
||||
DBCell, EntExU2, Uncalced, Array, Table,ShrFmla
|
||||
NB: no idea what "SUB" is
|
||||
*/
|
||||
|
||||
switch r.RecType {
|
||||
case RecTypeBOF:
|
||||
if ridx > 0 {
|
||||
inSubstream++
|
||||
continue
|
||||
}
|
||||
|
||||
case RecTypeBoolErr:
|
||||
rowIndex := int(binary.LittleEndian.Uint16(r.Data[:2]))
|
||||
colIndex := int(binary.LittleEndian.Uint16(r.Data[2:4]))
|
||||
ixfe := int(binary.LittleEndian.Uint16(r.Data[4:6]))
|
||||
if r.Data[7] == 0 {
|
||||
// Boolean value
|
||||
bv := false
|
||||
if r.Data[6] == 1 {
|
||||
bv = true
|
||||
}
|
||||
var fno uint16
|
||||
if ixfe < len(b.xfs) {
|
||||
fno = b.xfs[ixfe]
|
||||
}
|
||||
res.Put(rowIndex, colIndex, bv, fno)
|
||||
//log.Printf("bool/error spec: %d %d %+v", rowIndex, colIndex, bv)
|
||||
} else {
|
||||
// it's an error, load the label
|
||||
be, ok := berrLookup[r.Data[6]]
|
||||
if !ok {
|
||||
be = "<unknown error>"
|
||||
}
|
||||
res.Put(rowIndex, colIndex, be, 0)
|
||||
//log.Printf("bool/error spec: %d %d %s", rowIndex, colIndex, be)
|
||||
}
|
||||
|
||||
case RecTypeMulRk:
|
||||
// MulRk encodes multiple RK values in a row
|
||||
nrk := int((r.RecSize - 6) / 6)
|
||||
rowIndex := int(binary.LittleEndian.Uint16(r.Data[:2]))
|
||||
colIndex := int(binary.LittleEndian.Uint16(r.Data[2:4]))
|
||||
for i := 0; i < nrk; i++ {
|
||||
off := 4 + i*6
|
||||
ixfe := int(binary.LittleEndian.Uint16(r.Data[off:]))
|
||||
value := RKNumber(binary.LittleEndian.Uint32(r.Data[off+2:]))
|
||||
|
||||
var rval interface{}
|
||||
if value.IsInteger() {
|
||||
rval = value.Int()
|
||||
} else {
|
||||
rval = value.Float64()
|
||||
}
|
||||
var fno uint16
|
||||
if ixfe < len(b.xfs) {
|
||||
fno = b.xfs[ixfe]
|
||||
}
|
||||
res.Put(rowIndex, colIndex+i, rval, fno)
|
||||
}
|
||||
//log.Printf("mulrow spec: %+v", *mr)
|
||||
|
||||
case RecTypeNumber:
|
||||
rowIndex := int(binary.LittleEndian.Uint16(r.Data[:2]))
|
||||
colIndex := int(binary.LittleEndian.Uint16(r.Data[2:4]))
|
||||
ixfe := int(binary.LittleEndian.Uint16(r.Data[4:6]))
|
||||
xnum := binary.LittleEndian.Uint64(r.Data[6:])
|
||||
|
||||
value := math.Float64frombits(xnum)
|
||||
var fno uint16
|
||||
if ixfe < len(b.xfs) {
|
||||
fno = b.xfs[ixfe]
|
||||
}
|
||||
res.Put(rowIndex, colIndex, value, fno)
|
||||
//log.Printf("Number spec: %d %d = %f", rowIndex, colIndex, value)
|
||||
|
||||
case RecTypeRK:
|
||||
rowIndex := int(binary.LittleEndian.Uint16(r.Data[:2]))
|
||||
colIndex := int(binary.LittleEndian.Uint16(r.Data[2:4]))
|
||||
ixfe := int(binary.LittleEndian.Uint16(r.Data[4:]))
|
||||
value := RKNumber(binary.LittleEndian.Uint32(r.Data[6:]))
|
||||
|
||||
var rval interface{}
|
||||
if value.IsInteger() {
|
||||
rval = value.Int()
|
||||
} else {
|
||||
rval = value.Float64()
|
||||
}
|
||||
var fno uint16
|
||||
if ixfe < len(b.xfs) {
|
||||
fno = b.xfs[ixfe]
|
||||
}
|
||||
res.Put(rowIndex, colIndex, rval, fno)
|
||||
//log.Printf("RK spec: %d %d = %+v", rowIndex, colIndex, rval)
|
||||
|
||||
case RecTypeFormula:
|
||||
formulaRow = binary.LittleEndian.Uint16(r.Data[:2])
|
||||
formulaCol = binary.LittleEndian.Uint16(r.Data[2:4])
|
||||
ixfe := int(binary.LittleEndian.Uint16(r.Data[4:6]))
|
||||
fdata := r.Data[6:]
|
||||
var fno uint16
|
||||
if ixfe < len(b.xfs) {
|
||||
fno = b.xfs[ixfe]
|
||||
}
|
||||
if fdata[6] == 0xFF && fdata[7] == 0xFF {
|
||||
switch fdata[0] {
|
||||
case 0:
|
||||
// string in next record
|
||||
// put placeholder now to record the numFmt
|
||||
res.Put(int(formulaRow), int(formulaCol), "", fno)
|
||||
case 1:
|
||||
// boolean
|
||||
bv := false
|
||||
if fdata[2] != 0 {
|
||||
bv = true
|
||||
}
|
||||
res.Put(int(formulaRow), int(formulaCol), bv, fno)
|
||||
case 2:
|
||||
// error value
|
||||
be, ok := berrLookup[fdata[2]]
|
||||
if !ok {
|
||||
be = "<unknown error>"
|
||||
}
|
||||
res.Put(int(formulaRow), int(formulaCol), be, 0)
|
||||
case 3:
|
||||
// blank string
|
||||
default:
|
||||
log.Printf("unknown formula value type %d", fdata[0])
|
||||
}
|
||||
} else {
|
||||
xnum := binary.LittleEndian.Uint64(fdata)
|
||||
value := math.Float64frombits(xnum)
|
||||
res.Put(int(formulaRow), int(formulaCol), value, fno)
|
||||
}
|
||||
//log.Printf("formula spec: %d %d ~~ %+v", formulaRow, formulaCol, r.Data)
|
||||
|
||||
case RecTypeString:
|
||||
// String is the previously rendered value of a formula
|
||||
// NB similar to the workbook SST, this can continue over
|
||||
// addition records up to 32k characters. A 1-byte flag
|
||||
// at each gap indicates if the encoding switches
|
||||
// to/from 8/16-bit characters.
|
||||
|
||||
charCount := binary.LittleEndian.Uint16(r.Data[:2])
|
||||
flags := r.Data[2]
|
||||
fstr := ""
|
||||
if (flags & 1) == 0 {
|
||||
fstr = latin1String(r.Data[3:]) // descrybe patch: compressed chars are Latin-1, not UTF-8
|
||||
} else {
|
||||
raw := r.Data[3:]
|
||||
if int(charCount) > cap(us) {
|
||||
us = make([]uint16, charCount)
|
||||
}
|
||||
us = us[:charCount]
|
||||
for i := 0; i < int(charCount); i++ {
|
||||
us[i] = binary.LittleEndian.Uint16(raw)
|
||||
raw = raw[2:]
|
||||
}
|
||||
fstr = string(utf16.Decode(us))
|
||||
}
|
||||
|
||||
if (ridx + 1) < len(b.substreams[ss]) {
|
||||
ridx2 := ridx + 1
|
||||
nrecs := len(b.substreams[ss])
|
||||
for ridx2 < nrecs {
|
||||
r2 := b.substreams[ss][ridx2]
|
||||
if r2.RecType != RecTypeContinue {
|
||||
break
|
||||
}
|
||||
if (r2.Data[0] & 1) == 0 {
|
||||
fstr += latin1String(r2.Data[1:])
|
||||
} else {
|
||||
raw := r2.Data[1:]
|
||||
slen := len(raw) / 2
|
||||
us = us[:slen]
|
||||
for i := 0; i < slen; i++ {
|
||||
us[i] = binary.LittleEndian.Uint16(raw)
|
||||
raw = raw[2:]
|
||||
}
|
||||
fstr += string(utf16.Decode(us))
|
||||
}
|
||||
ridx2++
|
||||
}
|
||||
}
|
||||
res.Set(int(formulaRow), int(formulaCol), fstr)
|
||||
//log.Printf("String direct: %d %d '%s'", int(formulaRow), int(formulaCol), fstr)
|
||||
|
||||
case RecTypeLabelSst:
|
||||
rowIndex := int(binary.LittleEndian.Uint16(r.Data[:2]))
|
||||
colIndex := int(binary.LittleEndian.Uint16(r.Data[2:4]))
|
||||
ixfe := int(binary.LittleEndian.Uint16(r.Data[4:6]))
|
||||
sstIndex := int(binary.LittleEndian.Uint32(r.Data[6:]))
|
||||
if sstIndex > len(b.strings) {
|
||||
return nil, errors.New("xls: invalid sst index")
|
||||
}
|
||||
var fno uint16
|
||||
if ixfe < len(b.xfs) {
|
||||
fno = b.xfs[ixfe]
|
||||
}
|
||||
if b.strings[sstIndex] != "" {
|
||||
res.Put(rowIndex, colIndex, b.strings[sstIndex], fno)
|
||||
}
|
||||
//log.Printf("SST spec: %d %d = [%d] '%s' %d", rowIndex, colIndex, sstIndex, b.strings[sstIndex], fno)
|
||||
|
||||
case RecTypeHLink:
|
||||
firstRow := binary.LittleEndian.Uint16(r.Data[:2])
|
||||
lastRow := binary.LittleEndian.Uint16(r.Data[2:4])
|
||||
firstCol := binary.LittleEndian.Uint16(r.Data[4:6])
|
||||
lastCol := binary.LittleEndian.Uint16(r.Data[6:])
|
||||
if int(firstCol) > int(maxCol) {
|
||||
//log.Println("invalid hyperlink column")
|
||||
continue
|
||||
}
|
||||
if int(firstRow) > int(maxRow) {
|
||||
//log.Println("invalid hyperlink row")
|
||||
continue
|
||||
}
|
||||
if lastRow == 0xFFFF { // placeholder value indicate "last"
|
||||
lastRow = uint16(maxRow) - 1
|
||||
}
|
||||
if lastCol == 0xFF { // placeholder value indicate "last"
|
||||
lastCol = uint16(maxCol) - 1
|
||||
}
|
||||
|
||||
// decode the hyperlink datastructure and try to find the
|
||||
// display text and separate the URL itself.
|
||||
displayText, linkText, err := decodeHyperlinks(r.Data[8:])
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
continue
|
||||
}
|
||||
|
||||
// apply merge cell rules (see RecTypeMergeCells below)
|
||||
for rn := int(firstRow); rn <= int(lastRow); rn++ {
|
||||
for cn := int(firstCol); cn <= int(lastCol); cn++ {
|
||||
if rn == int(firstRow) && cn == int(firstCol) {
|
||||
// TODO: provide custom hooks for how to handle links in output
|
||||
// descrybe patch: keep the URL itself (upstream wrote "text <url>").
|
||||
if linkText == "" {
|
||||
linkText = displayText
|
||||
}
|
||||
res.Put(rn, cn, linkText, 0)
|
||||
} else if cn == int(firstCol) {
|
||||
// first and last column MAY be the same
|
||||
if rn == int(lastRow) {
|
||||
res.Put(rn, cn, grate.EndRowMerged, 0)
|
||||
} else {
|
||||
res.Put(rn, cn, grate.ContinueRowMerged, 0)
|
||||
}
|
||||
} else if cn == int(lastCol) {
|
||||
// first and last column are NOT the same
|
||||
res.Put(rn, cn, grate.EndColumnMerged, 0)
|
||||
} else {
|
||||
res.Put(rn, cn, grate.ContinueColumnMerged, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
case RecTypeMergeCells:
|
||||
// To keep cells aligned, Merged cells are handled by placing
|
||||
// special characters in each cell covered by the merge block.
|
||||
//
|
||||
// The contents of the cell are always in the top left position.
|
||||
// A "down arrow" (↓) indicates the left side of the merge block, and a
|
||||
// "down arrow with stop line" (⤓) indicates the last row of the merge.
|
||||
// A "right arrow" (→) indicates that the columns span horizontally,
|
||||
// and a "right arrow with stop line" (⇥) indicates the rightmost
|
||||
// column of the merge.
|
||||
//
|
||||
|
||||
cmcs := binary.LittleEndian.Uint16(r.Data[:2])
|
||||
raw := r.Data[2:]
|
||||
for i := 0; i < int(cmcs); i++ {
|
||||
firstRow := binary.LittleEndian.Uint16(raw[:2])
|
||||
lastRow := binary.LittleEndian.Uint16(raw[2:4])
|
||||
firstCol := binary.LittleEndian.Uint16(raw[4:6])
|
||||
lastCol := binary.LittleEndian.Uint16(raw[6:])
|
||||
raw = raw[8:]
|
||||
|
||||
if lastRow == 0xFFFF { // placeholder value indicate "last"
|
||||
lastRow = uint16(maxRow) - 1
|
||||
}
|
||||
if lastCol == 0xFF { // placeholder value indicate "last"
|
||||
lastCol = uint16(maxCol) - 1
|
||||
}
|
||||
for rn := int(firstRow); rn <= int(lastRow); rn++ {
|
||||
for cn := int(firstCol); cn <= int(lastCol); cn++ {
|
||||
if rn == int(firstRow) && cn == int(firstCol) {
|
||||
// should be a value there already!
|
||||
} else if cn == int(firstCol) {
|
||||
// first and last column MAY be the same
|
||||
if rn == int(lastRow) {
|
||||
res.Put(rn, cn, grate.EndRowMerged, 0)
|
||||
} else {
|
||||
res.Put(rn, cn, grate.ContinueRowMerged, 0)
|
||||
}
|
||||
} else if cn == int(lastCol) {
|
||||
// first and last column are NOT the same
|
||||
res.Put(rn, cn, grate.EndColumnMerged, 0)
|
||||
} else {
|
||||
res.Put(rn, cn, grate.ContinueColumnMerged, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
case RecTypeBlank, RecTypeMulBlank:
|
||||
// cells default value is blank, no need for these
|
||||
|
||||
case RecTypeContinue:
|
||||
// the only situation so far is when used in RecTypeString above
|
||||
|
||||
case RecTypeRow, RecTypeDimensions, RecTypeEOF, RecTypeWsBool:
|
||||
// handled in initial pass
|
||||
|
||||
default:
|
||||
if grate.Debug {
|
||||
log.Println(" Unhandled sheet record type:", r.RecType, ridx)
|
||||
}
|
||||
*/
|
||||
}
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
var berrLookup = map[byte]string{
|
||||
0x00: "#NULL!",
|
||||
0x07: "#DIV/0!",
|
||||
0x0F: "#VALUE!",
|
||||
0x17: "#REF!",
|
||||
0x1D: "#NAME?",
|
||||
0x24: "#NUM!",
|
||||
0x2A: "#N/A",
|
||||
0x2B: "#GETTING_DATA",
|
||||
}
|
||||
|
||||
// latin1String decodes BIFF8 compressed (8-bit) characters. descrybe patch.
|
||||
func latin1String(b []byte) string {
|
||||
r := make([]rune, len(b))
|
||||
for i, c := range b {
|
||||
r[i] = rune(c)
|
||||
}
|
||||
return string(r)
|
||||
}
|
||||
+246
@@ -0,0 +1,246 @@
|
||||
package xls
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"unicode/utf16"
|
||||
)
|
||||
|
||||
// 2.5.240
|
||||
func decodeShortXLUnicodeString(raw []byte) (string, int, error) {
|
||||
// identical to decodeXLUnicodeString except for cch=8bits instead of 16
|
||||
cch := int(raw[0])
|
||||
flags := raw[1]
|
||||
raw = raw[2:]
|
||||
|
||||
content := make([]uint16, cch)
|
||||
if (flags & 0x1) == 0 {
|
||||
// 16-bit characters but only the bottom 8bits
|
||||
contentBytes := raw[:cch]
|
||||
for i, x := range contentBytes {
|
||||
content[i] = uint16(x)
|
||||
}
|
||||
cch += 2 // to return the offset
|
||||
} else {
|
||||
// 16-bit characters
|
||||
for i := 0; i < cch; i++ {
|
||||
content[i] = binary.LittleEndian.Uint16(raw[:2])
|
||||
raw = raw[2:]
|
||||
}
|
||||
cch += cch + 2 // to return the offset
|
||||
}
|
||||
return string(utf16.Decode(content)), cch, nil
|
||||
}
|
||||
|
||||
// 2.5.294
|
||||
func decodeXLUnicodeString(raw []byte) (string, int, error) {
|
||||
// identical to decodeShortXLUnicodeString except for cch=16bits instead of 8
|
||||
cch := int(binary.LittleEndian.Uint16(raw[:2]))
|
||||
flags := raw[2]
|
||||
raw = raw[3:]
|
||||
|
||||
content := make([]uint16, cch)
|
||||
if (flags & 0x1) == 0 {
|
||||
// 16-bit characters but only the bottom 8bits
|
||||
contentBytes := raw[:cch]
|
||||
for i, x := range contentBytes {
|
||||
content[i] = uint16(x)
|
||||
}
|
||||
cch += 3 // to return the offset
|
||||
} else {
|
||||
// 16-bit characters
|
||||
for i := 0; i < cch; i++ {
|
||||
content[i] = binary.LittleEndian.Uint16(raw[:2])
|
||||
raw = raw[2:]
|
||||
}
|
||||
cch += cch + 3 // to return the offset
|
||||
}
|
||||
return string(utf16.Decode(content)), cch, nil
|
||||
}
|
||||
|
||||
// 2.5.293
|
||||
func decodeXLUnicodeRichExtendedString(r io.Reader) (string, error) {
|
||||
var cch, cRun uint16
|
||||
var flags uint8
|
||||
var cbExtRs int32
|
||||
err := binary.Read(r, binary.LittleEndian, &cch)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
err = binary.Read(r, binary.LittleEndian, &flags)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if (flags & 0x8) != 0 {
|
||||
// rich formating data is present
|
||||
err = binary.Read(r, binary.LittleEndian, &cRun)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
if (flags & 0x4) != 0 {
|
||||
// phonetic string data is present
|
||||
err = binary.Read(r, binary.LittleEndian, &cbExtRs)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
content := make([]uint16, cch)
|
||||
if (flags & 0x1) == 0 {
|
||||
// 16-bit characters but only the bottom 8bits
|
||||
contentBytes := make([]byte, cch)
|
||||
n, err2 := io.ReadFull(r, contentBytes)
|
||||
if n == 0 && err2 != io.ErrUnexpectedEOF {
|
||||
err = err2
|
||||
}
|
||||
if uint16(n) < cch {
|
||||
contentBytes = contentBytes[:n]
|
||||
content = content[:n]
|
||||
}
|
||||
|
||||
for i, x := range contentBytes {
|
||||
content[i] = uint16(x)
|
||||
}
|
||||
|
||||
} else {
|
||||
// 16-bit characters
|
||||
err = binary.Read(r, binary.LittleEndian, content)
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
//////
|
||||
|
||||
if cRun > 0 {
|
||||
// rich formating data is present
|
||||
_, err = io.CopyN(ioutil.Discard, r, int64(cRun)*4)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
if cbExtRs > 0 {
|
||||
// phonetic string data is present
|
||||
_, err = io.CopyN(ioutil.Discard, r, int64(cbExtRs))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
//////
|
||||
|
||||
return string(utf16.Decode(content)), nil
|
||||
}
|
||||
|
||||
// read in an array of XLUnicodeRichExtendedString s
|
||||
func parseSST(recs []*rec) ([]string, error) {
|
||||
// The quirky thing about this code is that when strings cross a record
|
||||
// boundary, there's an intervening flags byte that MAY change the string
|
||||
// from an 8-bit encoding to 16-bit or vice versa.
|
||||
|
||||
//totalRefs := binary.LittleEndian.Uint32(recs[0].Data[0:4])
|
||||
numStrings := binary.LittleEndian.Uint32(recs[0].Data[4:8])
|
||||
|
||||
all := make([]string, 0, numStrings)
|
||||
current := make([]uint16, 32*1024)
|
||||
|
||||
buf := recs[0].Data[8:]
|
||||
for i := 0; i < len(recs); {
|
||||
var cRunBytes int
|
||||
var flags byte
|
||||
var cbExtRs uint32
|
||||
|
||||
for len(buf) > 0 {
|
||||
slen := binary.LittleEndian.Uint16(buf)
|
||||
buf = buf[2:]
|
||||
flags = buf[0]
|
||||
buf = buf[1:]
|
||||
|
||||
if (flags & 0x8) != 0 {
|
||||
// rich formating data is present
|
||||
cRun := binary.LittleEndian.Uint16(buf)
|
||||
cRunBytes = int(cRun) * 4
|
||||
buf = buf[2:]
|
||||
}
|
||||
if (flags & 0x4) != 0 {
|
||||
// phonetic string data is present
|
||||
cbExtRs = binary.LittleEndian.Uint32(buf)
|
||||
buf = buf[4:]
|
||||
}
|
||||
|
||||
///////
|
||||
blx := len(buf)
|
||||
bly := len(buf) - 5
|
||||
if blx > 5 {
|
||||
blx = 5
|
||||
}
|
||||
if bly < 0 {
|
||||
bly = 0
|
||||
}
|
||||
|
||||
// this block will read the string data, but transparently
|
||||
// handle continuing across records
|
||||
if int(slen) > cap(current) {
|
||||
current = make([]uint16, slen)
|
||||
} else {
|
||||
current = current[:slen]
|
||||
}
|
||||
for j := 0; j < int(slen); j++ {
|
||||
if len(buf) == 0 {
|
||||
i++
|
||||
if (recs[i].Data[0] & 1) == 0 {
|
||||
flags &= 0xFE
|
||||
} else {
|
||||
flags |= 1
|
||||
}
|
||||
buf = recs[i].Data[1:]
|
||||
}
|
||||
|
||||
if (flags & 1) == 0 { //8-bit
|
||||
current[j] = uint16(buf[0])
|
||||
buf = buf[1:]
|
||||
} else { //16-bit
|
||||
current[j] = uint16(binary.LittleEndian.Uint16(buf[:2]))
|
||||
buf = buf[2:]
|
||||
if len(buf) == 1 {
|
||||
return nil, errors.New("xls: off by one")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
s := string(utf16.Decode(current))
|
||||
all = append(all, s)
|
||||
|
||||
///////
|
||||
|
||||
for cRunBytes > 0 {
|
||||
if len(buf) >= int(cRunBytes) {
|
||||
buf = buf[cRunBytes:]
|
||||
cRunBytes = 0
|
||||
} else {
|
||||
cRunBytes -= len(buf)
|
||||
i++
|
||||
buf = recs[i].Data
|
||||
}
|
||||
}
|
||||
|
||||
for cbExtRs > 0 {
|
||||
if len(buf) >= int(cbExtRs) {
|
||||
buf = buf[cbExtRs:]
|
||||
cbExtRs = 0
|
||||
} else {
|
||||
cbExtRs -= uint32(len(buf))
|
||||
i++
|
||||
buf = recs[i].Data
|
||||
}
|
||||
}
|
||||
}
|
||||
i++
|
||||
if i < len(recs) {
|
||||
buf = recs[i].Data
|
||||
}
|
||||
}
|
||||
|
||||
return all, nil
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
package xls
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
)
|
||||
|
||||
type header struct {
|
||||
Version uint16 // An unsigned integer that specifies the BIFF version of the file. The value MUST be 0x0600.
|
||||
DocType uint16 //An unsigned integer that specifies the document type of the substream of records following this record. For more information about the layout of the sub-streams in the workbook stream see File Structure.
|
||||
RupBuild uint16 // An unsigned integer that specifies the build identifier.
|
||||
RupYear uint16 // An unsigned integer that specifies the year when this BIFF version was first created. The value MUST be 0x07CC or 0x07CD.
|
||||
MiscBits uint64 // lots of miscellaneous bits and flags we're not going to check
|
||||
}
|
||||
|
||||
// 2.1.4
|
||||
type rec struct {
|
||||
RecType recordType //
|
||||
RecSize uint16 // must be between 0 and 8224
|
||||
Data []byte // len(rec.data) = rec.recsize
|
||||
}
|
||||
|
||||
type boundSheet struct {
|
||||
Position uint32 // A FilePointer as specified in [MS-OSHARED] section 2.2.1.5 that specifies the stream position of the start of the BOF record for the sheet.
|
||||
HiddenState byte // (2 bits) An unsigned integer that specifies the hidden state of the sheet. MUST be a value from the following table:
|
||||
SheetType byte // An unsigned integer that specifies the sheet type. 00=worksheet
|
||||
Name string
|
||||
}
|
||||
|
||||
///////
|
||||
type shRow struct {
|
||||
RowIndex uint16 // 0-based
|
||||
FirstCol uint16 // 0-based
|
||||
LastCol uint16 // 1-based!
|
||||
Height uint16
|
||||
Reserved uint32
|
||||
Flags uint32
|
||||
}
|
||||
|
||||
type shRef8 struct {
|
||||
FirstRow uint16 // 0-based
|
||||
LastRow uint16 // 0-based
|
||||
FirstCol uint16 // 0-based
|
||||
LastCol uint16 // 0-based
|
||||
}
|
||||
type shMulRK struct {
|
||||
RowIndex uint16 // 0-based
|
||||
FirstCol uint16 // 0-based
|
||||
Values []RkRec
|
||||
LastCol uint16 // 0-based?
|
||||
}
|
||||
type RkRec struct {
|
||||
IXFCell uint16
|
||||
Value RKNumber
|
||||
}
|
||||
|
||||
type shRK struct {
|
||||
RowIndex uint16 // 0-based
|
||||
Col uint16 // 0-based
|
||||
IXFCell uint16
|
||||
Value RKNumber
|
||||
}
|
||||
|
||||
type RKNumber uint32
|
||||
|
||||
func (r RKNumber) IsInteger() bool {
|
||||
if (r & 1) != 0 {
|
||||
// has 2 decimals
|
||||
return false
|
||||
}
|
||||
if (r & 2) == 0 {
|
||||
// is part of a float
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (r RKNumber) Int() int {
|
||||
val := int32(r) >> 2
|
||||
if (r&1) == 0 && (r&2) != 0 {
|
||||
return int(val)
|
||||
}
|
||||
if (r&1) != 0 && (r&2) != 0 {
|
||||
return int(val / 100)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (r RKNumber) Float64() float64 {
|
||||
val := int32(r) >> 2
|
||||
v2 := math.Float64frombits(uint64(val) << 34)
|
||||
|
||||
if (r&1) == 0 && (r&2) == 0 {
|
||||
return v2
|
||||
}
|
||||
if (r&1) != 0 && (r&2) == 0 {
|
||||
return v2 / 100.0
|
||||
}
|
||||
return 0.0
|
||||
}
|
||||
|
||||
func (r RKNumber) String() string {
|
||||
if r.IsInteger() {
|
||||
return fmt.Sprint(r.Int())
|
||||
}
|
||||
return fmt.Sprint(r.Float64())
|
||||
}
|
||||
+360
@@ -0,0 +1,360 @@
|
||||
// Package xls implements the Microsoft Excel Binary File Format (.xls) Structure.
|
||||
// More specifically, it contains just enough detail to extract cell contents,
|
||||
// data types, and last-calculated formula values. In particular, it does NOT
|
||||
// implement formatting or formula calculations.
|
||||
package xls
|
||||
|
||||
// https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-xls/cd03cb5f-ca02-4934-a391-bb674cb8aa06
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"sync"
|
||||
|
||||
"github.com/pbnjay/grate"
|
||||
"github.com/pbnjay/grate/commonxl"
|
||||
"github.com/pbnjay/grate/xls/cfb"
|
||||
"github.com/pbnjay/grate/xls/crypto"
|
||||
)
|
||||
|
||||
var _ = grate.Register("xls", 1, Open)
|
||||
|
||||
// WorkBook represents an Excel workbook containing 1 or more sheets.
|
||||
type WorkBook struct {
|
||||
filename string
|
||||
ctx context.Context
|
||||
doc *cfb.Document
|
||||
|
||||
prot bool
|
||||
h *header
|
||||
sheets []*boundSheet
|
||||
codepage uint16
|
||||
dateMode uint16
|
||||
strings []string
|
||||
|
||||
password string
|
||||
substreams [][]*rec
|
||||
|
||||
fpos int64
|
||||
pos2substream map[int64]int
|
||||
|
||||
nfmt commonxl.Formatter
|
||||
xfs []uint16
|
||||
}
|
||||
|
||||
func (b *WorkBook) IsProtected() bool {
|
||||
return b.prot
|
||||
}
|
||||
|
||||
func Open(filename string) (grate.Source, error) {
|
||||
doc, err := cfb.Open(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
b := &WorkBook{
|
||||
filename: filename,
|
||||
doc: doc,
|
||||
|
||||
pos2substream: make(map[int64]int, 16),
|
||||
xfs: make([]uint16, 0, 128),
|
||||
}
|
||||
|
||||
rdr, err := doc.Open("Workbook")
|
||||
if err != nil {
|
||||
return nil, grate.WrapErr(err, grate.ErrNotInFormat)
|
||||
}
|
||||
raw, err := io.ReadAll(rdr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = b.loadFromStream(raw)
|
||||
return b, err
|
||||
}
|
||||
|
||||
func (b *WorkBook) loadFromStream(raw []byte) error {
|
||||
return b.loadFromStream2(raw, false)
|
||||
}
|
||||
|
||||
func (b *WorkBook) loadFromStreamWithDecryptor(raw []byte, dec crypto.Decryptor) error {
|
||||
// interestingly (insecurely) BIFF8 keeps Record Types and sizes in the clear,
|
||||
// has a few records that are not encrypted, and has 1 record type that does
|
||||
// not encrypt the 32bit integer position at the beginning (while encrypting
|
||||
// the rest). It also resets the encryption block counter every 1024 bytes
|
||||
// (counting all the "skipped" bytes described above).
|
||||
//
|
||||
// So this code streams the records through the decryption, but also records
|
||||
// a set of overlays applied to the final result which restore the
|
||||
// "cleartext" contents in line with the decrypted content.
|
||||
|
||||
if grate.Debug {
|
||||
log.Println(" Decrypting xls stream with standard RC4")
|
||||
}
|
||||
|
||||
pos := 0
|
||||
zeros := [8224]byte{}
|
||||
|
||||
type overlay struct {
|
||||
Pos int
|
||||
|
||||
RecType recordType
|
||||
DataBytes uint16
|
||||
Data []byte // NB len() not necessarily = DataBytes
|
||||
}
|
||||
replaceBlocks := []overlay{}
|
||||
|
||||
var err error
|
||||
for err == nil && len(raw[pos:]) > 4 {
|
||||
o := overlay{}
|
||||
o.Pos = pos
|
||||
o.RecType = recordType(binary.LittleEndian.Uint16(raw[pos : pos+2]))
|
||||
o.DataBytes = binary.LittleEndian.Uint16(raw[pos+2 : pos+4])
|
||||
pos += 4
|
||||
|
||||
// copy to output and decryption stream
|
||||
binary.Write(dec, binary.LittleEndian, o.RecType)
|
||||
binary.Write(dec, binary.LittleEndian, o.DataBytes)
|
||||
tocopy := int(o.DataBytes)
|
||||
|
||||
switch o.RecType {
|
||||
case RecTypeBOF, RecTypeFilePass, RecTypeUsrExcl, RecTypeFileLock, RecTypeInterfaceHdr, RecTypeRRDInfo, RecTypeRRDHead:
|
||||
// untouched data goes directly into output
|
||||
o.Data = raw[pos : pos+int(o.DataBytes)]
|
||||
pos += int(o.DataBytes)
|
||||
dec.Write(zeros[:int(o.DataBytes)])
|
||||
tocopy = 0
|
||||
|
||||
case RecTypeBoundSheet8:
|
||||
// copy 32-bit position to output
|
||||
o.Data = raw[pos : pos+4]
|
||||
pos += 4
|
||||
dec.Write(zeros[:4])
|
||||
tocopy -= 4
|
||||
}
|
||||
|
||||
if tocopy > 0 {
|
||||
_, err = dec.Write(raw[pos : pos+tocopy])
|
||||
pos += tocopy
|
||||
}
|
||||
replaceBlocks = append(replaceBlocks, o)
|
||||
}
|
||||
dec.Flush()
|
||||
|
||||
alldata := dec.Bytes()
|
||||
for _, o := range replaceBlocks {
|
||||
offs := int(o.Pos)
|
||||
binary.LittleEndian.PutUint16(alldata[offs:], uint16(o.RecType))
|
||||
binary.LittleEndian.PutUint16(alldata[offs+2:], uint16(o.DataBytes))
|
||||
if len(o.Data) > 0 {
|
||||
offs += 4
|
||||
copy(alldata[offs:], o.Data)
|
||||
}
|
||||
}
|
||||
|
||||
// recurse into the stream parser now that things are decrypted
|
||||
return b.loadFromStream2(alldata, true)
|
||||
}
|
||||
|
||||
func (b *WorkBook) Close() error {
|
||||
// return records to the pool for reuse
|
||||
for i, sub := range b.substreams {
|
||||
for _, r := range sub {
|
||||
r.Data = nil // allow GC
|
||||
recPool.Put(r)
|
||||
}
|
||||
b.substreams[i] = b.substreams[i][:0]
|
||||
}
|
||||
b.substreams = b.substreams[:0]
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *WorkBook) loadFromStream2(raw []byte, isDecrypted bool) error {
|
||||
b.h = &header{}
|
||||
substr := -1
|
||||
nestedBOF := 0
|
||||
b.pos2substream = make(map[int64]int, 10)
|
||||
b.fpos = 0
|
||||
|
||||
// IMPORTANT: if there are any existing records, we need to return them to the pool
|
||||
for i, sub := range b.substreams {
|
||||
for _, r := range sub {
|
||||
recPool.Put(r)
|
||||
}
|
||||
b.substreams[i] = b.substreams[i][:0]
|
||||
}
|
||||
b.substreams = b.substreams[:0]
|
||||
|
||||
rawfull := raw
|
||||
nr, no, err := b.nextRecord(raw)
|
||||
for err == nil {
|
||||
raw = raw[no:]
|
||||
switch nr.RecType {
|
||||
case RecTypeEOF:
|
||||
nestedBOF--
|
||||
case RecTypeBOF:
|
||||
// when substreams are nested, keep them in the same grouping
|
||||
if nestedBOF == 0 {
|
||||
substr = len(b.substreams)
|
||||
b.substreams = append(b.substreams, []*rec{})
|
||||
b.pos2substream[b.fpos] = substr
|
||||
}
|
||||
nestedBOF++
|
||||
}
|
||||
b.fpos += int64(4 + len(nr.Data))
|
||||
|
||||
// if there's a FilePass record, the data is encrypted
|
||||
if nr.RecType == RecTypeFilePass && !isDecrypted {
|
||||
etype := binary.LittleEndian.Uint16(nr.Data)
|
||||
switch etype {
|
||||
case 1:
|
||||
dec, err := crypto.NewBasicRC4(nr.Data[2:])
|
||||
if err != nil {
|
||||
log.Println("xls: rc4 encryption failed to set up", err)
|
||||
return err
|
||||
}
|
||||
return b.loadFromStreamWithDecryptor(rawfull, dec)
|
||||
case 2, 3, 4:
|
||||
log.Println("need Crypto API RC4 decryptor")
|
||||
return errors.New("xls: unsupported Crypto API encryption method")
|
||||
default:
|
||||
return errors.New("xls: unsupported encryption method")
|
||||
}
|
||||
}
|
||||
|
||||
b.substreams[substr] = append(b.substreams[substr], nr)
|
||||
nr, no, err = b.nextRecord(raw)
|
||||
}
|
||||
if err == io.EOF {
|
||||
err = nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for ss, records := range b.substreams {
|
||||
if grate.Debug {
|
||||
log.Printf(" Processing substream %d/%d (%d records)", ss, len(b.substreams), len(records))
|
||||
}
|
||||
for i, nr := range records {
|
||||
if len(nr.Data) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
switch nr.RecType {
|
||||
case RecTypeSST:
|
||||
// Shared String Table is often continued across multiple records,
|
||||
// so we want to gather them all before starting to parse (some
|
||||
// strings may span the gap between records)
|
||||
recSet := []*rec{nr}
|
||||
|
||||
lastIndex := i
|
||||
for len(records) > (lastIndex+1) && records[lastIndex+1].RecType == RecTypeContinue {
|
||||
lastIndex++
|
||||
recSet = append(recSet, records[lastIndex])
|
||||
}
|
||||
|
||||
b.strings, err = parseSST(recSet)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
case RecTypeContinue:
|
||||
// no-op (used above)
|
||||
case RecTypeEOF:
|
||||
// done
|
||||
|
||||
case RecTypeBOF:
|
||||
b.h = &header{
|
||||
Version: binary.LittleEndian.Uint16(nr.Data[0:2]),
|
||||
DocType: binary.LittleEndian.Uint16(nr.Data[2:4]),
|
||||
RupBuild: binary.LittleEndian.Uint16(nr.Data[4:6]),
|
||||
RupYear: binary.LittleEndian.Uint16(nr.Data[6:8]),
|
||||
MiscBits: binary.LittleEndian.Uint64(nr.Data[8:16]),
|
||||
}
|
||||
|
||||
if b.h.Version != 0x0600 {
|
||||
return errors.New("xls: invalid file version")
|
||||
}
|
||||
if b.h.RupYear != 0x07CC && b.h.RupYear != 0x07CD {
|
||||
return errors.New("xls: unsupported biff version")
|
||||
}
|
||||
/*
|
||||
if b.h.DocType != 0x0005 && b.h.DocType != 0x0010 {
|
||||
// we only support the workbook or worksheet substreams
|
||||
log.Println("xls: unsupported document type")
|
||||
//break
|
||||
}
|
||||
*/
|
||||
|
||||
case RecTypeCodePage:
|
||||
// BIFF8 is entirely UTF-16LE so this is actually ignored
|
||||
b.codepage = binary.LittleEndian.Uint16(nr.Data)
|
||||
|
||||
case RecTypeDate1904:
|
||||
b.dateMode = binary.LittleEndian.Uint16(nr.Data)
|
||||
|
||||
case RecTypeFormat:
|
||||
// Format maps a format ID to a code string
|
||||
fmtNo := binary.LittleEndian.Uint16(nr.Data)
|
||||
formatStr, _, err := decodeXLUnicodeString(nr.Data[2:])
|
||||
if err != nil {
|
||||
log.Println("fail2", err)
|
||||
return err
|
||||
}
|
||||
b.nfmt.Add(fmtNo, formatStr)
|
||||
|
||||
case RecTypeXF:
|
||||
// XF records merge multiple style and format directives to one ID
|
||||
// ignore font id at nr.Data[0:2]
|
||||
fmtNo := binary.LittleEndian.Uint16(nr.Data[2:])
|
||||
b.xfs = append(b.xfs, fmtNo)
|
||||
|
||||
case RecTypeBoundSheet8:
|
||||
// Identifies the postition within the stream, visibility state,
|
||||
// and name of a worksheet
|
||||
bs := &boundSheet{}
|
||||
bs.Position = binary.LittleEndian.Uint32(nr.Data[:4])
|
||||
bs.HiddenState = nr.Data[4]
|
||||
bs.SheetType = nr.Data[5]
|
||||
|
||||
bs.Name, _, err = decodeShortXLUnicodeString(nr.Data[6:])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
b.sheets = append(b.sheets, bs)
|
||||
default:
|
||||
if grate.Debug && ss == 0 {
|
||||
log.Println(" Unhandled record type:", nr.RecType, i)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
var recPool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return &rec{}
|
||||
},
|
||||
}
|
||||
|
||||
func (b *WorkBook) nextRecord(raw []byte) (*rec, int, error) {
|
||||
if len(raw) < 4 {
|
||||
return nil, 0, io.EOF
|
||||
}
|
||||
rec := recPool.Get().(*rec)
|
||||
|
||||
rec.RecType = recordType(binary.LittleEndian.Uint16(raw[:2]))
|
||||
rec.RecSize = binary.LittleEndian.Uint16(raw[2:4])
|
||||
if len(raw[4:]) < int(rec.RecSize) {
|
||||
recPool.Put(rec)
|
||||
return nil, 4, io.ErrUnexpectedEOF
|
||||
}
|
||||
rec.Data = raw[4 : 4+rec.RecSize]
|
||||
return rec, int(4 + rec.RecSize), nil
|
||||
}
|
||||
Reference in new issue
Block a user