summaryrefslogtreecommitdiff
path: root/pkg/server/module/tee.go
blob: 795324748fe1ed16a0731e813fa745ce33f1cb7a (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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package module

import (
	"bytes"
	"fmt"
	"os"
	"encoding/hex"
	"sync"
	"tunnel/pkg/server/env"
	"tunnel/pkg/server/opts"
	"tunnel/pkg/server/queue"
)

const teeDefaultPath = "/tmp/tunnel.dump"

type tee struct {
	f *os.File
	mu sync.Mutex
	wg sync.WaitGroup
}

type teeModule struct {
	path string
}

func (t *tee) dump(s string, p []byte) error {
	var out bytes.Buffer

	fmt.Fprintln(&out, s, len(p))

	w := hex.Dumper(&out)
	w.Write(p)
	w.Close()

	if _, err := t.f.Write(out.Bytes()); err != nil {
		return err
	}

	return nil
}

func (t *tee) Send(rq, wq queue.Q) error {
	defer t.wg.Done()

	for b := range rq {
		t.dump(">", b)
		wq <- b
	}

	return nil
}

func (t *tee) Recv(rq, wq queue.Q) error {
	defer t.wg.Done()

	for b := range rq {
		t.dump("<", b)
		wq <- b
	}

	return nil
}

func (m *teeModule) where(env env.Env) string {
	if m.path != "" {
		return m.path
	}

	if v := env.Eval("@{tunnel.@{tunnel}.tee.path}"); v != "" {
		return v
	}

	if v, ok := env.Find("module.tee.path"); ok {
		return v
	}

	return teeDefaultPath
}

func (m *teeModule) Open(env env.Env) (interface{}, error) {
	tid, sid := env.Get("tunnel"), env.Get("stream")
	name := fmt.Sprintf("%s.%s.%s", m.where(env), tid, sid)

	var t tee

	if f, err := os.Create(name); err != nil {
		return nil, err
	} else {
		t.f = f
	}

	t.wg.Add(2)

	go func() {
		t.wg.Wait()
		t.f.Close()
	}()

	return &t, nil
}

func newTeeModule(opts opts.Opts, env env.Env) (module, error) {
	m := &teeModule{}
	if path, ok := opts["path"]; ok {
		m.path = path
	}
	return m, nil
}

func init() {
	register("tee", newTeeModule)
}