summaryrefslogtreecommitdiffhomepage
path: root/tunnel/tools/libwg-go/service.go
blob: e49081e73c79eb0aa5a3d474412ad88d2f2f1170 (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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
package main

import (
	"context"
	"fmt"
	"io"
	"net"
	"net/netip"
	"net/url"
	"os"

	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	gen "golang.zx2c4.com/wireguard/android/gen"
	"golang.zx2c4.com/wireguard/device"
)

const (
	IPPROTO_TCP = 6
)

type UidRequest struct {
	Data AddrPortPair
	RetCh chan string
}

type LibwgServiceImpl struct {
	gen.UnimplementedLibwgServer
	logger *device.Logger
	httpProxy *HttpProxy
	uidRequest chan UidRequest
	stopReverse chan bool
}

var service *LibwgServiceImpl
var server *grpc.Server

func NewLibwgService(logger *device.Logger) gen.LibwgServer {
	return &LibwgServiceImpl{
		logger: logger,
		uidRequest: make(chan UidRequest),
		stopReverse: make(chan bool),
	}
}

func StartGrpc(sock_path string, logger *device.Logger) (int, string) {
	if server != nil {
		return -1, "Already started"
	}

	if _, err := os.Stat(sock_path); err == nil {
		if err := os.RemoveAll(sock_path); err != nil {
			return -1, fmt.Sprintf("Cleanup failed: %v %v", sock_path, err)
		}
	}

	listener, err := net.Listen("unix", sock_path)
	if err != nil {
		return -1, fmt.Sprintf("Listen failed: %v %v", sock_path, err)
	}

	server = grpc.NewServer()
	service = NewLibwgService(logger).(*LibwgServiceImpl)

	gen.RegisterLibwgServer(server, service)

	go func() {
		server.Serve(listener)
	}()

	logger.Verbosef("gRPC started")

	return 0, ""
}

func (e *LibwgServiceImpl) Version(ctx context.Context, req *gen.VersionRequest) (*gen.VersionResponse, error) {

	r := &gen.VersionResponse{
		Version: Version(),
	}

	return r, nil
}

func (e *LibwgServiceImpl) StopGrpc(ctx context.Context, req *gen.StopGrpcRequest) (*gen.StopGrpcResponse, error) {
	if server != nil {
		server.Stop()
		server = nil
		service = nil
	}

	r := &gen.StopGrpcResponse{
	}

	return r, nil
}

func buildStartHttpProxyError(message string) (*gen.StartHttpProxyResponse, error) {
	r := &gen.StartHttpProxyResponse{
		Error: &gen.Error{
			Message: message,
		},
	}
	return r, nil
}

func (e *LibwgServiceImpl) StartHttpProxy(ctx context.Context, req *gen.StartHttpProxyRequest) (*gen.StartHttpProxyResponse, error) {
	var listenPort uint16
	if e.httpProxy == nil {
		e.httpProxy = NewHttpProxy(e.uidRequest, e.logger)
		var err error
		listenPort, err = e.httpProxy.Start()

		if err != nil {
			e.httpProxy = nil
			return buildStartHttpProxyError(fmt.Sprintf("Http proxy start failed: %v", err))
		}
	} else {
		listenPort = e.httpProxy.GetAddrPort().Port()
	}

	pacFileUrl, err := url.Parse(req.PacFileUrl)
	if err != nil {
		return buildStartHttpProxyError(fmt.Sprintf("Bad pacFileUrl: %v (%s)", err, req.PacFileUrl))
	}

	err = e.httpProxy.SetPacFileUrl(pacFileUrl)
	if err != nil {
		return buildStartHttpProxyError(fmt.Sprintf("Bad pacFileUrl: %v (%s)", req.PacFileUrl))
	}

	r := &gen.StartHttpProxyResponse{
		ListenPort: uint32(listenPort),
	}
	return r, nil
}

func (e *LibwgServiceImpl) StopHttpProxy(ctx context.Context, req *gen.StopHttpProxyRequest) (*gen.StopHttpProxyResponse, error) {
	if e.httpProxy == nil {
		r := &gen.StopHttpProxyResponse{
			Error: &gen.Error{
				Message: fmt.Sprintf("Http proxy not running"),
			},
		}
		return r, nil
	}

	e.httpProxy.Stop()
	e.httpProxy = nil
	e.stopReverse <- true
	r := &gen.StopHttpProxyResponse{}
	return r, nil
}

func (e *LibwgServiceImpl) Reverse(stream gen.Libwg_ReverseServer) error {
	e.logger.Verbosef("Reverse enter loop")
	for e.httpProxy != nil {
		var err error

		//		err := contextError(stream.Context())
		err = stream.Context().Err()
		if err != nil {
			e.logger.Verbosef("Reverse: context: %v", err)
			return err
		}

		select {
		case <-e.stopReverse:
			e.logger.Verbosef("Reverse: stop")
			break
		case uidReq := <-e.uidRequest:
			addrPortPair := uidReq.Data
			local := addrPortPair.local
			remote := addrPortPair.remote
			r := &gen.ReverseResponse{
				Request: &gen.ReverseResponse_Uid{
					Uid: &gen.GetConnectionOwnerUidRequest{
						Protocol: IPPROTO_TCP,
						Local: &gen.InetSocketAddress{
							Address: &gen.InetAddress{
								Address: local.Addr().AsSlice(),
							},
							Port: uint32(local.Port()),
						},
						Remote: &gen.InetSocketAddress{
							Address: &gen.InetAddress{
								Address: remote.Addr().AsSlice(),
							},
							Port: uint32(remote.Port()),
						},
					},
				},
			}

			stream.Send(r)

			req, err := stream.Recv()
			if err == io.EOF {
				e.logger.Verbosef("no more data")
				uidReq.RetCh <- ""
				break
			}
			if err != nil {
				err = status.Errorf(codes.Unknown, "cannot receive stream request: %v", err)
				e.logger.Verbosef("Reverse: %v", err)
				uidReq.RetCh <- ""
				return err
			}

			e.logger.Verbosef("Reverse: received, wait: %v", req)
			uidReq.RetCh <- req.GetUid().GetPackage()
		}
	}


	e.logger.Verbosef("Reverse returns")
	return nil
}

func (e *LibwgServiceImpl) IpcSet(ctx context.Context, req *gen.IpcSetRequest) (*gen.IpcSetResponse, error) {
	tunnel, ok := GetTunnel(req.GetTunnel().GetHandle())
	if !ok {
		r := &gen.IpcSetResponse{
			Error: &gen.Error{
				Message: fmt.Sprintf("Invalid tunnel"),
			},
		}
		return r, nil
	}

	err := tunnel.device.IpcSet(req.GetConfig())
	if err != nil {
		r := &gen.IpcSetResponse{
			Error: &gen.Error{
				Message: fmt.Sprintf("IpcSet failed: %v", err),
			},
		}
		return r, nil
	}

	r := &gen.IpcSetResponse{
	}

	return r, nil
}

func (e *LibwgServiceImpl) Dhcp(ctx context.Context, req *gen.DhcpRequest) (*gen.DhcpResponse, error) {
	var relayAddr netip.Addr
	var sourceAddr netip.Addr

	source := req.GetSource()
	if source != nil {
		sourceAddr, _ = netip.AddrFromSlice(source.GetAddress())
	}

	if !sourceAddr.IsValid() || !sourceAddr.Is6() {
		r := &gen.DhcpResponse{
			Error: &gen.Error{
				Message: fmt.Sprintf("DHCPv6 source address missing"),
			},
		}
		return r, nil
	}

	relay := req.GetRelay()
	if relay != nil {
		relayAddr, _ = netip.AddrFromSlice(relay.GetAddress())
	} else {
		// Construct relay address from source prefix
		relayRaw := source.GetAddress()[:8]
		relayRaw = append(relayRaw, 0)
		relayRaw = append(relayRaw, 0)
		relayRaw = append(relayRaw, 0)
		relayRaw = append(relayRaw, 0)
		relayRaw = append(relayRaw, 0)
		relayRaw = append(relayRaw, 0)
		relayRaw = append(relayRaw, 0)
		relayRaw = append(relayRaw, 1)
		relayAddr, _ = netip.AddrFromSlice(relayRaw)
	}

	if !relayAddr.IsValid() || !relayAddr.Is6() {
		r := &gen.DhcpResponse{
			Error: &gen.Error{
				Message: fmt.Sprintf("DHCPv6 relay address calculation failed"),
			},
		}
		return r, nil
	}

	e.logger.Verbosef("RunDhcp %v %v", sourceAddr, relayAddr)

	leases, err := RunDhcp(ctx, sourceAddr, relayAddr)
	if err != nil {
		r := &gen.DhcpResponse{
			Error: &gen.Error{
				Message: fmt.Sprintf("RunDhcp failed: %v", err),
			},
		}
		return r, nil
	}

	r := &gen.DhcpResponse{
		Leases: leases,
	}
	return r, nil
}