summaryrefslogtreecommitdiff
path: root/pkg/server/hook/b85.go
blob: 967882dd196ad5f52eed31ac5c2473014658e94e (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
package hook

import (
	"encoding/ascii85"
	"errors"

	"tunnel/pkg/netstring"
	"tunnel/pkg/server/queue"
)

type b85Pipe struct{}

func (b85Pipe) Send(rq, wq queue.Q) error {
	e := netstring.NewEncoder(wq.Writer())

	for b := range rq {
		out := make([]byte, ascii85.MaxEncodedLen(len(b)))
		n := ascii85.Encode(out, b)
		e.Encode(string(out[:n]))
	}

	return nil
}

func (b85Pipe) Recv(rq, wq queue.Q) error {
	d := netstring.NewDecoder(rq.Reader())

	for {
		s, err := d.Decode()
		if err != nil {
			return err
		}

		out := make([]byte, 4*len(s))

		if n, m, err := ascii85.Decode(out, []byte(s), true); err != nil {
			return err
		} else if m != len(s) {
			return errors.New("decode fail: partial consumption")
		} else {
			wq <- out[:n]
		}
	}
}

func init() {
	registerPipe("b85", "base85 filter out/in", b85Pipe{})
}