-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.go
163 lines (138 loc) · 3.83 KB
/
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
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
package wgdynamic
import (
"bytes"
"fmt"
"io"
"log"
"net"
"sync"
)
// A Server serves wg-dynamic protocol requests.
//
// Each exported function field implements a specific request. If any errors
// are returned, a protocol error is returned to the client. When the error is
// of type *Error, that protocol error is returned to the client. For generic
// errors, a generic protocol error is returned.
type Server struct {
// RequestIP handles requests for IP address assignment. If nil, a generic
// protocol error is returned to the client.
RequestIP func(src net.Addr, r *RequestIP) (*RequestIP, error)
// Log specifies an error logger for the Server. If nil, all error logs
// are discarded.
Log *log.Logger
// Guards internal fields set when Serve is first called.
mu sync.Mutex
l net.Listener
wg *sync.WaitGroup
}
// Listen creates a net.Listener suitable for use with a Server and bound to
// the specified WireGuard interface. Listen will return an error if the
// does not have the well-known IPv6 link-local server address (fe80::/64)
// configured.
func Listen(iface string) (net.Listener, error) {
ifi, err := net.InterfaceByName(iface)
if err != nil {
return nil, err
}
addrs, err := ifi.Addrs()
if err != nil {
return nil, err
}
llip, ok := linkLocalIPv6(addrs)
if !ok || !llip.IP.Equal(serverIP.IP) || !bytes.Equal(llip.Mask, serverIP.Mask) {
return nil, fmt.Errorf("wgdynamic: IPv6 server address %s must be assigned to interface %q", serverIP, iface)
}
return net.ListenTCP("tcp6", &net.TCPAddr{
IP: serverIP.IP,
Port: port,
Zone: iface,
})
}
// Serve serves incoming requests by accepting connections from l.
func (s *Server) Serve(l net.Listener) error {
// Initialize any necessary fields before starting the listener loop.
s.mu.Lock()
s.l = l
s.wg = &sync.WaitGroup{}
s.mu.Unlock()
for {
c, err := l.Accept()
if err != nil {
return err
}
// Guard s.wg to prevent a data race when another goroutine tries to
// wait during a call to Close.
s.mu.Lock()
s.wg.Add(1)
s.mu.Unlock()
go func() {
defer func() {
// The C implementation immediately closes the connection once
// a request is processed.
_ = c.Close()
s.wg.Done()
}()
s.handle(c)
}()
}
}
// Close closes the server listener and waits for all requests to complete.
func (s *Server) Close() error {
s.mu.Lock()
defer s.mu.Unlock()
defer s.wg.Wait()
return s.l.Close()
}
// handle handles an individual request. handle should be called in a goroutine.
func (s *Server) handle(c net.Conn) {
p, cmd, err := parseRequest(c)
if err != nil {
s.logf("%s: error parsing request: %v", c.RemoteAddr().String(), err)
return
}
// Pass the request to the appropriate handler.
switch cmd {
case "request_ip":
err = s.handleRequestIP(c, p)
default:
// No such command.
err = ErrInvalidRequest
}
if err == nil {
// No error handling needed.
return
}
// If the function returned *Error, use that. Otherwise, log the error and
// specify a generic error.
werr, ok := err.(*Error)
if !ok {
s.logf("%s: %q error: %v", c.RemoteAddr().String(), cmd, err)
werr = ErrInvalidRequest
}
// TODO(mdlayher): add serialization logic for Error type.
_, _ = io.WriteString(c, fmt.Sprintf("errno=%d\nerrmsg=%s\n\n",
werr.Number, werr.Message))
}
// handleRequestIP processes a request_ip command.
func (s *Server) handleRequestIP(c net.Conn, p *kvParser) error {
if s.RequestIP == nil {
// Not implemented by caller.
return ErrInvalidRequest
}
req, err := parseRequestIP(p)
if err != nil {
return err
}
res, err := s.RequestIP(c.RemoteAddr(), req)
if err != nil {
return err
}
return sendRequestIP(c, fromServer, res)
}
// logf creates a formatted log entry if s.Log is not nil.
func (s *Server) logf(format string, v ...interface{}) {
if s.Log == nil {
return
}
s.Log.Printf(format, v...)
}