2016-02-06 19:20:54 +01:00
|
|
|
package contentenc
|
2015-11-01 01:32:33 +01:00
|
|
|
|
|
|
|
// Per-file header
|
|
|
|
//
|
|
|
|
// Format: [ "Version" uint16 big endian ] [ "Id" 16 random bytes ]
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/binary"
|
|
|
|
"fmt"
|
2016-02-06 19:20:54 +01:00
|
|
|
|
|
|
|
"github.com/rfjakob/gocryptfs/internal/cryptocore"
|
2015-11-01 01:32:33 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2016-10-02 06:14:18 +02:00
|
|
|
// CurrentVersion is the current On-Disk-Format version
|
2016-02-06 19:20:54 +01:00
|
|
|
CurrentVersion = 2
|
|
|
|
|
2016-10-02 06:14:18 +02:00
|
|
|
headerVersionLen = 2 // uint16
|
|
|
|
headerIDLen = 16 // 128 bit random file id
|
|
|
|
// HeaderLen is the total header length
|
|
|
|
HeaderLen = headerVersionLen + headerIDLen
|
2015-11-01 01:32:33 +01:00
|
|
|
)
|
|
|
|
|
2016-10-02 06:14:18 +02:00
|
|
|
// FileHeader represents the header stored on each non-empty file.
|
2015-11-01 01:32:33 +01:00
|
|
|
type FileHeader struct {
|
|
|
|
Version uint16
|
2016-10-02 06:14:18 +02:00
|
|
|
ID []byte
|
2015-11-01 01:32:33 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Pack - serialize fileHeader object
|
|
|
|
func (h *FileHeader) Pack() []byte {
|
2016-10-02 06:14:18 +02:00
|
|
|
if len(h.ID) != headerIDLen || h.Version != CurrentVersion {
|
2015-11-01 01:32:33 +01:00
|
|
|
panic("FileHeader object not properly initialized")
|
|
|
|
}
|
2016-10-02 06:14:18 +02:00
|
|
|
buf := make([]byte, HeaderLen)
|
|
|
|
binary.BigEndian.PutUint16(buf[0:headerVersionLen], h.Version)
|
|
|
|
copy(buf[headerVersionLen:], h.ID)
|
2015-11-01 01:32:33 +01:00
|
|
|
return buf
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
// ParseHeader - parse "buf" into fileHeader object
|
|
|
|
func ParseHeader(buf []byte) (*FileHeader, error) {
|
2016-10-02 06:14:18 +02:00
|
|
|
if len(buf) != HeaderLen {
|
|
|
|
return nil, fmt.Errorf("ParseHeader: invalid length: got %d, want %d", len(buf), HeaderLen)
|
2015-11-01 01:32:33 +01:00
|
|
|
}
|
|
|
|
var h FileHeader
|
2016-10-02 06:14:18 +02:00
|
|
|
h.Version = binary.BigEndian.Uint16(buf[0:headerVersionLen])
|
2016-02-06 19:20:54 +01:00
|
|
|
if h.Version != CurrentVersion {
|
|
|
|
return nil, fmt.Errorf("ParseHeader: invalid version: got %d, want %d", h.Version, CurrentVersion)
|
2015-11-01 01:32:33 +01:00
|
|
|
}
|
2016-10-02 06:14:18 +02:00
|
|
|
h.ID = buf[headerVersionLen:]
|
2015-11-01 01:32:33 +01:00
|
|
|
return &h, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// RandomHeader - create new fileHeader object with random Id
|
|
|
|
func RandomHeader() *FileHeader {
|
|
|
|
var h FileHeader
|
2016-02-06 19:20:54 +01:00
|
|
|
h.Version = CurrentVersion
|
2016-10-02 06:14:18 +02:00
|
|
|
h.ID = cryptocore.RandBytes(headerIDLen)
|
2015-11-01 01:32:33 +01:00
|
|
|
return &h
|
|
|
|
}
|