summaryrefslogtreecommitdiff
path: root/pkg/client/client.go
blob: eee397fbf5cda10e2082c738646e9f94840db047 (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
package client

import (
	"bytes"
	"errors"
	"io"
	"net"
	"time"
	"tunnel/pkg/config"
	"tunnel/pkg/netstring"
)

var errClosed = errors.New("server closed connection")

type Client struct {
	conn net.Conn
	r    *netstring.Decoder
	w    *netstring.Encoder
}

func New(path string) (*Client, error) {
	conn, err := net.Dial("unix", path)
	if err != nil {
		return nil, err
	}

	c := &Client{
		conn: conn,
		r:    netstring.NewDecoder(conn),
		w:    netstring.NewEncoder(conn),
	}

	return c, nil
}

func (c *Client) Send(args []string) (string, error) {
	c.conn.SetDeadline(time.Now().Add(config.IoTimeout))

	defer func() {
		var t time.Time
		c.conn.SetDeadline(t)
	}()

	out := new(bytes.Buffer)
	enc := netstring.NewEncoder(out)

	for _, s := range args {
		enc.Encode(s)
	}

	ew := c.w.Encode(out.String())
	if ew != nil {
		return "", ew
	}

	resp, er := c.r.Decode()
	if er != nil {
		if errors.Is(er, io.EOF) {
			return "", errClosed
		}

		return "", er
	}

	return resp, nil
}

func (c *Client) Close() {
	c.conn.Close()
}