aboutsummaryrefslogtreecommitdiff
path: root/file.go
blob: e8218d8a7f5078db4bae20043ab71db100532355 (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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main

import (
	"bufio"
	"bytes"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"strings"
)

type File struct {
	Comment string
	B64     []byte
	Body    []byte
}

const (
	commentHdr = "untrusted comment: "
	verifyWith = "verify with "
	pubKey     = "%s public key"
	secKey     = "%s secret key"
	sigFrom    = "signature from %s"
)

func checkComment(comment string) error {
	// compatibility with original version
	if len(comment) > 1024 {
		return errors.New("comment line to long")
	}
	if !strings.HasPrefix(comment, commentHdr) {
		return errors.New("expected untrusted comment")
	}
	return nil
}

func Parse(r io.Reader) (File, error) {
	buf := bufio.NewReader(r)

	comment, err := buf.ReadString('\n')
	if err != nil {
		return File{}, err
	}
	if err := checkComment(comment); err != nil {
		return File{}, err
	}
	comment = comment[len(commentHdr):]

	b64, err := buf.ReadBytes('\n')
	if err != nil {
		return File{}, err
	}

	body, err := ioutil.ReadAll(buf)
	if err != nil {
		return File{}, err
	}

	return File{
		Comment: strings.TrimSpace(comment),
		B64:     bytes.TrimSpace(b64),
		Body:    body,
	}, nil
}

func ParseFile(fname string) (File, error) {
	fd, err := os.Open(fname)
	if err != nil {
		return File{}, err
	}
	defer fd.Close()
	return Parse(fd)
}

func (f File) Encode(w io.Writer) error {
	fmt.Fprintf(w, "%v%v\n", commentHdr, f.Comment)
	fmt.Fprintf(w, "%v\n", string(f.B64))
	if f.Body != nil {
		fmt.Fprintf(w, "%v", string(f.Body))
	}
	return nil
}

func (f File) EncodeFile(fname string) error {
	fd, err := os.Create(fname)
	if err != nil {
		return err
	}
	defer fd.Close()
	return f.Encode(fd)
}