forked from breez/lspd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
grpc_server.go
105 lines (93 loc) · 2.45 KB
/
grpc_server.go
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
package main
import (
"context"
"crypto/tls"
"fmt"
"log"
"net"
"strings"
"github.com/breez/lspd/common"
"github.com/breez/lspd/notifications"
lspdrpc "github.com/breez/lspd/rpc"
"github.com/caddyserver/certmagic"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
type grpcServer struct {
nodesService common.NodesService
address string
certmagicDomain string
lis net.Listener
s *grpc.Server
c lspdrpc.ChannelOpenerServer
n notifications.NotificationsServer
}
func NewGrpcServer(
nodesService common.NodesService,
address string,
certmagicDomain string,
c lspdrpc.ChannelOpenerServer,
n notifications.NotificationsServer,
) (*grpcServer, error) {
return &grpcServer{
nodesService: nodesService,
address: address,
certmagicDomain: certmagicDomain,
c: c,
n: n,
}, nil
}
func (s *grpcServer) Start() error {
var lis net.Listener
if s.certmagicDomain == "" {
var err error
lis, err = net.Listen("tcp", s.address)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
} else {
tlsConfig, err := certmagic.TLS([]string{s.certmagicDomain})
if err != nil {
log.Fatalf("failed to run certmagic: %v", err)
}
lis, err = tls.Listen("tcp", s.address, tlsConfig)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
}
srv := grpc.NewServer(
grpc_middleware.WithUnaryServerChain(func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
if md, ok := metadata.FromIncomingContext(ctx); ok {
for _, auth := range md.Get("authorization") {
if !strings.HasPrefix(auth, "Bearer ") {
continue
}
token := strings.Replace(auth, "Bearer ", "", 1)
node, err := s.nodesService.GetNode(token)
if err != nil {
continue
}
return handler(lspdrpc.WithNode(ctx, node, token), req)
}
}
return nil, status.Errorf(codes.PermissionDenied, "Not authorized")
}),
)
lspdrpc.RegisterChannelOpenerServer(srv, s.c)
notifications.RegisterNotificationsServer(srv, s.n)
s.s = srv
s.lis = lis
if err := srv.Serve(lis); err != nil {
return fmt.Errorf("failed to serve: %v", err)
}
return nil
}
func (s *grpcServer) Stop() {
srv := s.s
if srv != nil {
srv.GracefulStop()
}
}