summaryrefslogtreecommitdiffhomepage
path: root/tunnel/tools/libwg-go/service.go
blob: 2a0dfb2d58b820f7396778090101813fba0257b3 (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
package main

import (
	"context"
	"fmt"
	"net"
	"os"

	"google.golang.org/grpc"

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

type LibwgServiceImpl struct {
	gen.UnimplementedLibwgServer
	logger *device.Logger
}

var _ gen.LibwgServer = (*LibwgServiceImpl)(nil)
var server *grpc.Server

func NewLibwgService(logger *device.Logger) gen.LibwgServer {
	return &LibwgServiceImpl{logger: logger}
}

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)

	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
	}

	r := &gen.StopGrpcResponse{
	}

	return r, nil
}