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
|
package relay
import (
"context"
"fmt"
"sync"
pb "github.com/boozec/rahanna/relay/proto"
)
type Server struct {
pb.UnimplementedRelayServer
}
type name string
// TODO: use pair of ips and ports
type ips struct {
ip0 string
ip1 string
}
var mu sync.Mutex
// Map each name to a pair of IPs
var table = make(map[name]ips)
func (s *Server) RegisterName(ctx context.Context, in *pb.RelayRequest) (*pb.RelayResponse, error) {
mu.Lock()
defer mu.Unlock()
if in.Ip == "" {
return nil, fmt.Errorf("IP address cannot be empty")
}
sessionName := NewSession()
for {
if _, ok := table[name(sessionName)]; !ok {
break
}
sessionName = NewSession()
}
table[name(sessionName)] = ips{ip0: in.Ip, ip1: ""}
return &pb.RelayResponse{Name: sessionName, Ip: in.Ip}, nil
}
func (s *Server) Lookup(ctx context.Context, in *pb.LookupRequest) (*pb.RelayResponse, error) {
mu.Lock()
defer mu.Unlock()
if in.Name == "" {
return nil, fmt.Errorf("name cannot be empty")
}
entry, ok := table[name(in.Name)]
if !ok {
return nil, fmt.Errorf("name not found")
}
return &pb.RelayResponse{Name: in.Name, Ip: entry.ip0}, nil
}
func (s *Server) CloseName(ctx context.Context, in *pb.LookupRequest) (*pb.CloseResponse, error) {
mu.Lock()
defer mu.Unlock()
if in.Name == "" {
return nil, fmt.Errorf("name cannot be empty")
}
_, ok := table[name(in.Name)]
if !ok {
return &pb.CloseResponse{Status: false}, fmt.Errorf("name not found")
}
delete(table, name(in.Name))
return &pb.CloseResponse{Status: true}, nil
}
|