aboutsummaryrefslogtreecommitdiff
path: root/zhead/header.go
blob: 2acad84722b7673b062400f947d60adc1ff2906b (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
67
68
69
70
71
72
73
74
75
76
77
78
package zhead

import (
	"bufio"
	"encoding/hex"
	"errors"
	"fmt"
	"io"
	"strconv"
	"strings"
	"time"
)

type Header struct {
	Date      time.Time
	KeyFile   string
	Alg       string
	BlockSize int
	Sums      [][]byte
}

const (
	DefaultAlg       = "SHA512/256"
	DefaultBlockSize = 65535
)

func (h Header) Print(w io.Writer) error {
	fmt.Fprintf(w, "date=%v\n", h.Date.Format("2006-01-02T15:04:05Z07:00"))
	fmt.Fprintf(w, "key=%v\n", h.KeyFile)
	fmt.Fprintf(w, "algorithm=%v\n", h.Alg)
	fmt.Fprintf(w, "blocksize=%v\n", h.BlockSize)
	fmt.Fprintf(w, "\n")
	for _, sum := range h.Sums {
		fmt.Fprintf(w, "%x\n", sum)
	}
	return nil
}

func Parse(r io.Reader) (Header, error) {
	var inSum bool
	var h Header
	scanner := bufio.NewScanner(r)
	for scanner.Scan() {
		line := scanner.Text()
		switch {
		case strings.HasPrefix(line, "date="):
			t, err := time.Parse(time.RFC3339, line[5:])
			if err != nil {
				return Header{}, err
			}
			h.Date = t
		case strings.HasPrefix(line, "key="):
			h.KeyFile = line[4:]
		case strings.HasPrefix(line, "algorithm="):
			h.Alg = line[10:]
		case strings.HasPrefix(line, "blocksize="):
			i, err := strconv.Atoi(line[10:])
			if err != nil {
				return Header{}, err
			}
			h.BlockSize = i
		case line == "":
			if inSum {
				return Header{}, errors.New("already in sum part")
			}
			inSum = true
			continue
		}
		if inSum {
			sum, err := hex.DecodeString(line)
			if err != nil {
				return Header{}, err
			}
			h.Sums = append(h.Sums, sum)
		}
	}
	return h, scanner.Err()
}