aboutsummaryrefslogtreecommitdiff
path: root/file.go
blob: 795dda03423556e540ee8f9ce5c61ef63e46e7a8 (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
package main

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

type B64 interface {
	Marshal() ([]byte, error)
	Unmarshal([]byte) error
}

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 Parse(r io.Reader) (File, error) {
	buf := bufio.NewReader(r)
	comment, err := buf.ReadString('\n')
	if err != nil {
		return File{}, err
	}
	if !strings.HasPrefix(comment, commentHdr) {
		return File{}, errors.New("expected untrusted header")
	}
	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.TrimRight(comment, "\r\n"),
		B64:     bytes.TrimRight(b64, "\r\n"),
		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)
}