Skip to content
File

Blob: tun/server/server.go

go310 lines
1package server
2 
3import (
4 "context"
5 "errors"
6 "net"
7 "time"
8 
9 "go.miragespace.co/specter/spec/chord"
10 "go.miragespace.co/specter/spec/cipher"
11 "go.miragespace.co/specter/spec/protocol"
12 "go.miragespace.co/specter/spec/rpc"
13 "go.miragespace.co/specter/spec/transport"
14 "go.miragespace.co/specter/spec/tun"
15 "go.miragespace.co/specter/util/acceptor"
16 
17 "github.com/Yiling-J/theine-go"
18 "go.uber.org/zap"
19 "golang.org/x/sync/singleflight"
20)
21 
22// Gateway procedure:
23// use the hostname to lookup chordHash(hostname-[1..3])
24// lookup those keys sequentially on DHT
25// if all failed, that means hostname does not point to a valid tunnel
26// if any of the one is good, fetch (ClientIdentity, ServerIdentity) from DHT
27// if ServerIdentity is ourself, we have a direct connection to client
28// otherwise, DialDirect to that server to get a tunnel Stream
29// in either case, pipe the gateway connection to (direct|indirect) Stream
30// tunnel is now established
31 
32type Config struct {
33 Logger *zap.Logger
34 ParentContext context.Context
35 Chord chord.VNode
36 TunnelTransport transport.Transport
37 ChordTransport transport.Transport
38 Resolver tun.DNSResolver
39 CertProvider cipher.CertProvider
40 Apex string
41 Acme string
42}
43 
44type Server struct {
45 sessions *sessionRegistry
46 ephemeralLoads chan struct{}
47 rpcAcceptor *acceptor.HTTP2Acceptor
48 routeCache *theine.Cache[string, *routesResult]
49 routeLoads singleflight.Group
50 keylessCache *theine.LoadingCache[string, keylessCertResult]
51 hostWAFCache *theine.Cache[string, *hostWAFCacheEntry]
52 hostWAFLoads singleflight.Group
53 Config
54}
55 
56var _ tun.Server = (*Server)(nil)
57 
58var _ protocol.TunnelService = (*Server)(nil)
59 
60func New(cfg Config) *Server {
61 s := &Server{
62 Config: cfg,
63 sessions: newSessionRegistry(),
64 ephemeralLoads: make(chan struct{}, 16),
65 rpcAcceptor: acceptor.NewH2Acceptor(nil),
66 }
67 s.initRouteCache()
68 s.initKeylessCache()
69 s.initHostWAFCache()
70 return s
71}
72 
73func (s *Server) Identity() *protocol.Node {
74 return s.TunnelTransport.Identity()
75}
76 
77func (s *Server) AttachRouter(ctx context.Context, router *transport.StreamRouter) {
78 router.HandleChord(protocol.Stream_PROXY, nil, func(delegate *transport.StreamDelegate) {
79 l := s.Logger.With(
80 zap.Object("peer", delegate.Identity),
81 zap.String("remote", delegate.RemoteAddr().String()),
82 zap.String("local", delegate.LocalAddr().String()),
83 )
84 defer func() {
85 if err := recover(); err != nil {
86 l.Warn("Panic recovered while handling proxy connection", zap.Any("error", err))
87 }
88 }()
89 s.handleProxyConn(ctx, delegate)
90 })
91 router.HandleTunnel(protocol.Stream_DIRECT, func(delegate *transport.StreamDelegate) {
92 // client uses this to register connection
93 // but it is a no-op on the server side
94 delegate.Close()
95 })
96 s.attachRPC(ctx, router)
97}
98 
99func (s *Server) MustRegister(ctx context.Context) {
100 s.Logger.Info("Publishing destinations to chord")
101 
102 publishCtx, cancel := context.WithTimeout(ctx, time.Second*30)
103 defer cancel()
104 
105 if err := s.publishDestinations(publishCtx); err != nil {
106 s.Logger.Panic("Error publishing destinations", zap.Error(err))
107 }
108 
109 s.Logger.Info("specter server started")
110}
111 
112func (s *Server) Stop() {
113 defer s.routeCache.Close()
114 defer s.keylessCache.Close()
115 defer s.hostWAFCache.Close()
116 
117 s.rpcAcceptor.Close()
118 
119 ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
120 defer cancel()
121 
122 s.unpublishDestinations(ctx)
123}
124 
125func (s *Server) handleProxyConn(ctx context.Context, delegation *transport.StreamDelegate) {
126 var err error
127 var clientConn net.Conn
128 
129 defer func() {
130 tun.SendStatusProto(delegation, err)
131 if err != nil {
132 delegation.Close()
133 return
134 }
135 tun.Pipe(delegation, clientConn)
136 }()
137 
138 route := &protocol.TunnelRoute{}
139 err = rpc.BoundedReceive(delegation, route, 2048)
140 if err != nil {
141 s.Logger.Error("Error receiving remote tunnel negotiation", zap.Error(err))
142 return
143 }
144 
145 l := s.Logger.With(
146 zap.String("hostname", route.GetHostname()),
147 zap.Uint64("client", route.GetClientDestination().GetId()),
148 )
149 l.Debug("Received proxy stream from remote node",
150 zap.Object("remote_chord", delegation.Identity),
151 zap.Object("chord", route.GetChordDestination()),
152 zap.Object("tunnel", route.GetTunnelDestination()))
153 
154 if route.GetTunnelDestination().GetAddress() != s.TunnelTransport.Identity().GetAddress() {
155 l.Warn("Received remote connection for the wrong server",
156 zap.String("expected", s.TunnelTransport.Identity().GetAddress()),
157 zap.String("got", route.GetTunnelDestination().GetAddress()),
158 )
159 err = tun.ErrDestinationNotFound
160 return
161 }
162 
163 clientConn, err = s.dialDirect(ctx, route)
164 if err != nil && !tun.IsNoDirect(err) {
165 l.Error("Error dialing connection to connected client", zap.Error(err))
166 }
167}
168 
169func (s *Server) getConn(ctx context.Context, route *protocol.TunnelRoute, link *protocol.Link) (net.Conn, error) {
170 l := s.Logger.With(
171 zap.String("hostname", route.GetHostname()),
172 zap.Uint64("client", route.GetClientDestination().GetId()),
173 )
174 
175 var conn net.Conn
176 var err error
177 direct := route.GetTunnelDestination().GetAddress() == s.TunnelTransport.Identity().GetAddress()
178 if direct {
179 l.Debug("client is connected to us, opening direct stream")
180 conn, err = s.dialDirect(ctx, route)
181 } else {
182 l.Debug("client is connected to remote node, opening proxy stream",
183 zap.Object("chord", route.GetChordDestination()),
184 zap.Object("tunnel", route.GetTunnelDestination()))
185 
186 conn, err = s.ChordTransport.DialStream(ctx, route.GetChordDestination(), protocol.Stream_PROXY)
187 }
188 if err != nil {
189 return nil, err
190 }
191 
192 // Transports may retain the dialing context for a physical connection. Keep
193 // this stream's negotiation timeout separate from that connection lifecycle.
194 ctx, cancel := context.WithTimeout(ctx, lookupTimeout)
195 defer cancel()
196 
197 // Bound stream negotiation, including writes, and close failed streams before
198 // trying another route. Cancelled callers also interrupt blocked I/O.
199 stop := context.AfterFunc(ctx, func() { conn.Close() })
200 defer stop()
201 ready := false
202 defer func() {
203 if !ready {
204 conn.Close()
205 }
206 }()
207 deadline, _ := ctx.Deadline()
208 if err := conn.SetDeadline(deadline); err != nil {
209 return nil, err
210 }
211 if !direct {
212 if err := rpc.Send(conn, route); err != nil {
213 l.Error("sending remote tunnel negotiation", zap.Error(err))
214 return nil, err
215 }
216 status := &protocol.TunnelStatus{}
217 if err := rpc.BoundedReceive(conn, status, 1024); err != nil {
218 l.Error("Error receiving remote tunnel status", zap.Error(err))
219 return nil, err
220 }
221 switch status.GetStatus() {
222 case protocol.TunnelStatusCode_STATUS_OK:
223 case protocol.TunnelStatusCode_NO_DIRECT:
224 return nil, tun.ErrTunnelClientNotConnected
225 default:
226 return nil, errors.New(status.GetError())
227 }
228 }
229 if err := rpc.Send(conn, link); err != nil {
230 return nil, err
231 }
232 if !stop() {
233 return nil, ctx.Err()
234 }
235 if err := conn.SetDeadline(time.Time{}); err != nil {
236 return nil, err
237 }
238 ready = true
239 return conn, nil
240}
241 
242func (s *Server) DialInternal(ctx context.Context, node *protocol.Node) (net.Conn, error) {
243 if node.GetAddress() == "" || node.GetUnknown() {
244 return nil, transport.ErrNoDirect
245 }
246 return s.ChordTransport.DialStream(ctx, node, protocol.Stream_INTERNAL)
247}
248 
249func (s *Server) DialClient(ctx context.Context, link *protocol.Link) (net.Conn, error) {
250 ret, err := s.lookupRoutes(ctx, link.GetHostname(), nil)
251 if err != nil {
252 return nil, err
253 }
254 
255 var isNoRoute bool
256 for attempt := 0; attempt < 2; attempt++ {
257 if ret.err != nil {
258 return nil, ret.err
259 }
260 for _, route := range ret.routes {
261 if err := ctx.Err(); err != nil {
262 return nil, err
263 }
264 conn, err := s.getConn(ctx, route, link)
265 if err == nil {
266 return conn, nil
267 }
268 if tun.IsNoDirect(err) {
269 isNoRoute = true
270 } else {
271 s.Logger.Error("Failed to establish connection to client",
272 zap.String("hostname", link.GetHostname()),
273 zap.Object("chord", route.GetChordDestination()),
274 zap.Object("tunnel", route.GetTunnelDestination()),
275 zap.Object("client", route.GetClientDestination()),
276 zap.Error(err),
277 )
278 }
279 }
280 if err := ctx.Err(); err != nil {
281 return nil, err
282 }
283 if attempt == 1 {
284 break
285 }
286 fresh, err := s.lookupRoutes(ctx, link.GetHostname(), ret)
287 if err != nil {
288 return nil, err
289 }
290 if fresh == ret {
291 break
292 }
293 ret = fresh
294 }
295 
296 if isNoRoute {
297 return nil, tun.ErrTunnelClientNotConnected
298 }
299 
300 return nil, tun.ErrDestinationNotFound // fallback to not found
301}
302 
303func (s *Server) dialDirect(ctx context.Context, route *protocol.TunnelRoute) (net.Conn, error) {
304 client := route.GetClientDestination()
305 if tun.IsSessionAlias(client.GetAddress()) {
306 return s.sessions.dial(client.GetAddress(), route.GetHostname())
307 }
308 return s.TunnelTransport.DialStream(ctx, client, protocol.Stream_DIRECT)
309}