aboutsummaryrefslogtreecommitdiff
path: root/internal/contentenc/file_header.go
blob: 8a08ef03b1dc29f02639f597dc9de79e6aeb63f9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package contentenc

// Per-file header
//
// Format: [ "Version" uint16 big endian ] [ "Id" 16 random bytes ]

import (
	"encoding/binary"
	"log"
	"syscall"

	"github.com/rfjakob/gocryptfs/internal/cryptocore"
	"github.com/rfjakob/gocryptfs/internal/tlog"
)

const (
	// CurrentVersion is the current On-Disk-Format version
	CurrentVersion = 2

	headerVersionLen = 2  // uint16
	headerIDLen      = 16 // 128 bit random file id
	// HeaderLen is the total header length
	HeaderLen = headerVersionLen + headerIDLen
)

// FileHeader represents the header stored on each non-empty file.
type FileHeader struct {
	Version uint16
	ID      []byte
}

// Pack - serialize fileHeader object
func (h *FileHeader) Pack() []byte {
	if len(h.ID) != headerIDLen || h.Version != CurrentVersion {
		log.Panic("FileHeader object not properly initialized")
	}
	buf := make([]byte, HeaderLen)
	binary.BigEndian.PutUint16(buf[0:headerVersionLen], h.Version)
	copy(buf[headerVersionLen:], h.ID)
	return buf

}

// ParseHeader - parse "buf" into fileHeader object
func ParseHeader(buf []byte) (*FileHeader, error) {
	if len(buf) != HeaderLen {
		tlog.Warn.Printf("ParseHeader: invalid length: want %d bytes, got %d. Returning EINVAL.", HeaderLen, len(buf))
		return nil, syscall.EINVAL
	}
	var h FileHeader
	h.Version = binary.BigEndian.Uint16(buf[0:headerVersionLen])
	if h.Version != CurrentVersion {
		tlog.Warn.Printf("ParseHeader: invalid version: want %d, got %d. Returning EINVAL.", CurrentVersion, h.Version)
		return nil, syscall.EINVAL
	}
	h.ID = buf[headerVersionLen:]
	return &h, nil
}

// RandomHeader - create new fileHeader object with random Id
func RandomHeader() *FileHeader {
	var h FileHeader
	h.Version = CurrentVersion
	h.ID = cryptocore.RandBytes(headerIDLen)
	return &h
}