summaryrefslogtreecommitdiff
path: root/webircgateway/pkg/proxy/server.go
blob: 7e3f62ff34fa963c32f7a0f236c7e48869a8dc82 (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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
package proxy

import (
	"bufio"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net"
	"strconv"
	"sync"
	"syscall"
	"time"

	"github.com/kiwiirc/webircgateway/pkg/identd"
)

const (
	ResponseError       = "0"
	ResponseOK          = "1"
	ResponseReset       = "2"
	ResponseRefused     = "3"
	ResponseUnknownHost = "4"
	ResponseTimeout     = "5"
)

var identdRpc *identd.RpcClient
var Server net.Listener

type HandshakeMeta struct {
	Host      string `json:"host"`
	Port      int    `json:"port"`
	TLS       bool   `json:"ssl"`
	Username  string `json:"username"`
	Interface string `json:"interface"`
}

func MakeClient(conn net.Conn) *Client {
	return &Client{
		Client: conn,
	}
}

type Client struct {
	Client       net.Conn
	Upstream     net.Conn
	UpstreamAddr *net.TCPAddr
	Username     string
	BindAddr     *net.TCPAddr
	TLS          bool
}

func (c *Client) Run() {
	var err error

	err = c.Handshake()
	if err != nil {
		log.Println(err.Error())
		return
	}

	err = c.ConnectUpstream()
	if err != nil {
		log.Println(err.Error())
		return
	}

	c.Pipe()
}

func (c *Client) Handshake() error {
	// Read the first line - it should be JSON
	reader := bufio.NewReader(c.Client)
	line, readErr := reader.ReadBytes('\n')
	if readErr != nil {
		return readErr
	}

	var meta = HandshakeMeta{
		Username:  "user",
		Port:      6667,
		Interface: "0.0.0.0",
	}
	unmarshalErr := json.Unmarshal(line, &meta)
	if unmarshalErr != nil {
		c.Client.Write([]byte(ResponseError))
		return unmarshalErr
	}

	if meta.Host == "" || meta.Port == 0 || meta.Username == "" || meta.Interface == "" {
		c.Client.Write([]byte(ResponseError))
		return fmt.Errorf("missing args")
	}

	c.Username = meta.Username
	c.TLS = meta.TLS

	bindAddr, bindAddrErr := net.ResolveTCPAddr("tcp", meta.Interface+":")
	if bindAddrErr != nil {
		c.Client.Write([]byte(ResponseError))
		return fmt.Errorf("interface: " + bindAddrErr.Error())
	}
	c.BindAddr = bindAddr

	hostStr := net.JoinHostPort(meta.Host, strconv.Itoa(meta.Port))
	addr, addrErr := net.ResolveTCPAddr("tcp", hostStr)
	if addrErr != nil {
		c.Client.Write([]byte(ResponseUnknownHost))
		return fmt.Errorf("remote host: " + addrErr.Error())
	}
	c.UpstreamAddr = addr

	return nil
}

func (c *Client) ConnectUpstream() error {
	dialer := &net.Dialer{}
	dialer.LocalAddr = c.BindAddr
	dialer.Timeout = time.Second * 10

	conn, err := dialer.Dial("tcp", c.UpstreamAddr.String())
	if err != nil {
		response := ""
		errType := typeOfErr(err)
		switch errType {
		case "timeout":
			response = ResponseTimeout
		case "unknown_host":
			response = ResponseUnknownHost
		case "refused":
			response = ResponseRefused
		}

		c.Client.Write([]byte(response))
		return err
	}

	if identdRpc != nil {
		lAddr, lPortStr, _ := net.SplitHostPort(conn.LocalAddr().String())
		lPort, _ := strconv.Atoi(lPortStr)
		identdRpc.AddIdent(lPort, c.UpstreamAddr.Port, c.Username, lAddr)
	}

	if c.TLS {
		tlsConfig := &tls.Config{InsecureSkipVerify: true}
		tlsConn := tls.Client(conn, tlsConfig)
		err := tlsConn.Handshake()
		if err != nil {
			conn.Close()
			c.Client.Write([]byte(ResponseReset))
			return err
		}

		conn = net.Conn(tlsConn)
	}

	c.Upstream = conn
	c.Client.Write([]byte(ResponseOK))
	return nil
}

func (c *Client) Pipe() {
	wg := sync.WaitGroup{}
	wg.Add(2)

	go func() {
		io.Copy(c.Client, c.Upstream)
		c.Client.Close()
		wg.Done()
	}()

	go func() {
		io.Copy(c.Upstream, c.Client)
		c.Upstream.Close()
		wg.Done()
	}()

	wg.Wait()

	if identdRpc != nil {
		lAddr, lPortStr, _ := net.SplitHostPort(c.Upstream.LocalAddr().String())
		lPort, _ := strconv.Atoi(lPortStr)
		identdRpc.RemoveIdent(lPort, c.UpstreamAddr.Port, c.Username, lAddr)
	}
}

func Start(laddr string) {
	srv, err := net.Listen("tcp", laddr)
	if err != nil {
		log.Fatal(err.Error())
	}

	// Expose the server
	Server = srv
	log.Printf("Kiwi proxy listening on %s", srv.Addr().String())

	identdRpc = identd.MakeRpcClient("kiwiproxy" + laddr)
	go identdRpc.ConnectAndReconnect("127.0.0.1:1133")

	for {
		conn, err := srv.Accept()
		if err != nil {
			log.Print(err.Error())
			break
		}

		c := MakeClient(conn)
		go c.Run()
	}
}

func typeOfErr(err error) string {
	if err == nil {
		return ""
	}

	if netError, ok := err.(net.Error); ok && netError.Timeout() {
		return "timeout"
	}

	switch t := err.(type) {
	case *net.OpError:
		if t.Op == "dial" {
			return "unknown_host"
		} else if t.Op == "read" {
			return "refused"
		}

	case syscall.Errno:
		if t == syscall.ECONNREFUSED {
			return "refused"
		}
	}

	return ""
}