forked from anywherelan/awl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapplication.go
More file actions
704 lines (622 loc) · 22.7 KB
/
Copy pathapplication.go
File metadata and controls
704 lines (622 loc) · 22.7 KB
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
package awl
import (
"context"
"embed"
"errors"
"fmt"
"io/fs"
"net"
"net/netip"
"os"
"runtime"
"strings"
"sync"
"syscall"
"time"
"github.com/anywherelan/ts-dns/control/controlknobs"
"github.com/anywherelan/ts-dns/net/dns"
"github.com/anywherelan/ts-dns/util/dnsname"
ds "github.com/ipfs/go-datastore"
dssync "github.com/ipfs/go-datastore/sync"
"github.com/ipfs/go-log/v2"
"github.com/libp2p/go-libp2p"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-libp2p/p2p/host/eventbus"
"github.com/libp2p/go-libp2p/p2p/host/peerstore/pstoremem"
rcmgr "github.com/libp2p/go-libp2p/p2p/host/resource-manager"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"golang.zx2c4.com/wireguard/tun"
"github.com/anywherelan/awl/api"
"github.com/anywherelan/awl/awldns"
"github.com/anywherelan/awl/awldns/dnsbridge"
"github.com/anywherelan/awl/awlevent"
"github.com/anywherelan/awl/config"
"github.com/anywherelan/awl/metrics"
"github.com/anywherelan/awl/p2p"
"github.com/anywherelan/awl/protocol"
"github.com/anywherelan/awl/ringbuffer"
"github.com/anywherelan/awl/service"
"github.com/anywherelan/awl/vpn"
"github.com/anywherelan/awl/vpn/netstate"
)
const (
logBufSize = 1 << 20
)
//go:embed static
var frontendStatic embed.FS
func FrontendStatic() fs.FS {
fsys, err := fs.Sub(frontendStatic, "static")
if err != nil {
panic(err)
}
return fsys
}
// @title Anywherelan API
// @version 0.1
// @description Anywherelan API
// @Host localhost:8639
// @BasePath /api/v0/
//go:generate go run github.com/swaggo/swag/cmd/swag@latest init --parseDependency -g application.go
//go:generate rm -f docs/docs.go docs/swagger.json
type Application struct {
LogBuffer *ringbuffer.RingBuffer
logger *log.ZapEventLogger
Conf *config.Config
Eventbus awlevent.Bus
// For tests only:
ExtraLibp2pOpts []libp2p.Option
AllowEmptyBootstrapPeers bool
ctx context.Context
ctxCancel context.CancelFunc
vpnDevice *vpn.Device
P2p *p2p.P2p
Api *api.Handler
AuthStatus *service.AuthStatus
Tunnel *service.Tunnel
SOCKS5 *service.SOCKS5
VPNGateway *service.VPNGateway
Dns *DNSService
// NetManager owns the OS-level network state behind VPN gateway mode:
// socket marking plus the runtime client routes / server NAT. Callers may
// set it before Init to inject a non-default implementation —
// cmd/gomobile-lib wires the Android protector via
// netstate.NewAndroidManager, tests inject a bookkeeping-only fake (they
// run without root against a mock TUN, so the real OS setup cannot run).
// Init falls back to netstate.NewManager() if left nil.
NetManager NetManager
}
// NetManager is the surface of *netstate.Manager consumed by Application and
// its services (service.NetManager and service.SocketMarker are subsets of
// it). Declared consumer-side so tests can substitute a fake.
type NetManager interface {
Start(ctx context.Context) error
ControlFunc() func(network, address string, c syscall.RawConn) error
EnableClientRoutes(tunIfName string) error
DisableClientRoutes() error
ClientRoutesActive() bool
EnableServerNAT(awlSubnet, awlSubnet6, tunIfName string) error
DisableServerNAT() error
ServerNATActive() bool
}
func New() *Application {
return &Application{}
}
func (a *Application) Init(ctx context.Context, tunDevice tun.Device) error {
a.logger.Info("Application initialization started")
a.ctx, a.ctxCancel = context.WithCancel(ctx)
if a.NetManager == nil {
a.NetManager = netstate.NewManager()
}
// Start before InitHost so the very first libp2p sockets are already
// marked (on Windows: bound to the detected uplink). An offline start is
// not an error — see netstate.Manager.Start; only hard failures abort Init.
if err := a.NetManager.Start(a.ctx); err != nil {
return fmt.Errorf("start socket marker: %v", err)
}
a.P2p = p2p.NewP2p(a.ctx)
p2pHost, err := a.P2p.InitHost(a.makeP2pHostConfig())
if err != nil {
return err
}
privKey := p2pHost.Peerstore().PrivKey(p2pHost.ID())
a.Conf.SetIdentity(privKey, p2pHost.ID())
a.logger.Infof("P2P host initialized. My peer_id: %s", p2pHost.ID().String())
a.logger.Infof("P2P listening on addresses: %v", p2pHost.Addrs())
if a.Conf.VPNConfig.DisableVPNInterface {
a.logger.Info("VPN interface is disabled from config")
} else {
localIP, netMask := a.Conf.VPNLocalIPMask()
localIPv6, netMaskv6 := a.Conf.VPNLocalIPMaskV6()
interfaceName := a.Conf.VPNConfig.InterfaceName
a.vpnDevice, err = vpn.NewDevice(tunDevice, interfaceName, localIP, netMask, localIPv6, netMaskv6)
if err != nil {
return fmt.Errorf("failed to init vpn: %v", err)
}
a.logger.Infof("VPN interface created. Name: %s CIDR: %s", interfaceName, &net.IPNet{IP: localIP, Mask: netMask})
if localIPv6 != nil {
a.logger.Infof("VPN interface IPv6: %s", &net.IPNet{IP: localIPv6, Mask: netMaskv6})
}
a.Tunnel = service.NewTunnel(a.P2p, a.vpnDevice, a.Conf, a.Eventbus)
go a.vpnDevice.ReadTUNPackets(a.Tunnel.HandleReadPackets)
}
a.P2p.Bootstrap()
a.Dns = NewDNSService(a.Conf, a.Eventbus, a.ctx, a.logger)
a.AuthStatus = service.NewAuthStatus(a.P2p, a.Conf, a.Eventbus)
a.SOCKS5, err = service.NewSOCKS5(a.P2p, a.Conf, a.NetManager)
if err != nil {
return fmt.Errorf("failed to init socks5: %v", err)
}
p2pHost.SetStreamHandler(protocol.GetStatusMethod, a.AuthStatus.StatusStreamHandler)
p2pHost.SetStreamHandler(protocol.AuthMethod, a.AuthStatus.AuthStreamHandler)
if a.Tunnel != nil {
p2pHost.SetStreamHandler(protocol.TunnelPacketMethod, a.Tunnel.StreamHandler)
}
p2pHost.SetStreamHandler(protocol.Socks5PacketMethod, a.SOCKS5.ProxyStreamHandler)
p2pHost.SetStreamHandler(protocol.Socks5NoAuthMethod, a.SOCKS5.ProxyStreamHandler)
if a.Tunnel != nil {
awlevent.WrapSubscriptionToCallback(a.ctx, func(_ interface{}) {
a.Tunnel.RefreshPeersList()
}, a.Eventbus, new(awlevent.KnownPeerChanged))
}
a.VPNGateway = service.NewVPNGateway(a.Conf, a.Tunnel, a.vpnDevice, a.P2p, a.NetManager, a.Dns)
handler := api.NewHandler(a.Conf, a.P2p, a.AuthStatus, a.Tunnel, a.SOCKS5, a.LogBuffer, a.Dns, a.VPNGateway)
a.Api = handler
err = handler.SetupAPI()
if err != nil {
return fmt.Errorf("failed to setup api: %v", err)
}
go a.P2p.MaintainBackgroundConnections(a.ctx, a.Conf.P2pNode.ReconnectionIntervalSec*time.Second, a.Conf.KnownPeersIds)
go a.AuthStatus.BackgroundRetryAuthRequests(a.ctx)
go a.AuthStatus.BackgroundExchangeStatusInfo(a.ctx)
go a.SOCKS5.ServeConns(a.ctx)
if !a.Conf.DNS.DisableDNS && !a.Conf.VPNConfig.DisableVPNInterface {
a.setupDNS()
}
// Metrics
metrics.SetNodeInfo(config.Version, p2pHost.ID().String())
cma := &configMetricsAdapter{conf: a.Conf, authStatus: a.AuthStatus, p2p: a.P2p}
go metrics.StartBackgroundUpdater(a.ctx, cma, a.P2p)
// VPN Gateway mode setup
err = a.VPNGateway.SetupAtStartup()
if err != nil {
return fmt.Errorf("setup gateway: %v", err)
}
a.logger.Info("Application initialized successfully")
return nil
}
// setupDNS picks the platform DNS path. On Android there are no OS sockets
// and no OS DNS configurator: DNS packets are intercepted from the TUN read
// path into a netstack bridge instead.
func (a *Application) setupDNS() {
if runtime.GOOS == "android" {
a.Dns.initDNSAndroid(a.vpnDevice, a.Tunnel)
return
}
interfaceName, err := a.vpnDevice.InterfaceName()
if err != nil {
a.logger.Errorf("failed to get TUN interface name: %v", err)
return
}
a.Dns.initDNS(interfaceName)
}
func (a *Application) SetupLoggerAndConfig(appType config.AppType) *log.ZapEventLogger {
a.Eventbus = eventbus.NewBus()
// Config
conf, loadConfigErr := config.LoadConfig(appType, a.Eventbus)
if loadConfigErr != nil {
conf = config.NewConfig(appType, a.Eventbus)
}
// Logger
a.LogBuffer = ringbuffer.New(logBufSize)
syncer := zapcore.NewMultiWriteSyncer(
zapcore.Lock(zapcore.AddSync(os.Stdout)),
zapcore.AddSync(a.LogBuffer),
)
encoderConfig := zap.NewDevelopmentEncoderConfig()
encoderConfig.EncodeTime = func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(t.Format("2006-01-02 15:04:05.99"))
}
consoleEncoder := zapcore.NewConsoleEncoder(encoderConfig)
zapCore := zapcore.NewCore(consoleEncoder, syncer, zapcore.InfoLevel)
lvl := conf.LogLevel()
opts := []zap.Option{zap.AddStacktrace(zapcore.ErrorLevel)}
if conf.DevMode() {
opts = append(opts, zap.Development())
}
log.SetupLogging(zapCore, func(name string) zapcore.Level {
if strings.HasPrefix(name, "awl") {
return lvl
}
switch name {
case "swarm2", "relay", "connmgr", "autonat":
return zapcore.WarnLevel
default:
return zapcore.InfoLevel
}
},
opts...,
)
a.logger = log.Logger("awl")
a.Conf = conf
if errors.Is(loadConfigErr, fs.ErrNotExist) {
// First run: there is simply no config yet.
a.logger.Infof("no config file found, creating new one")
} else if loadConfigErr != nil {
// The file is there but unusable. We are about to run with a new
// identity and no known peers, and the first save will overwrite the
// old file, so this is data loss and must not read as a routine
// warning. LoadConfig has already copied a corrupted config aside.
a.logger.Errorf("failed to read existing config file, starting with a new one "+
"(previous identity and known peers will not be used): %v", loadConfigErr)
}
a.logger.Infof("Anywherelan %s (%s %s-%s)", config.Version, runtime.Version(), runtime.GOOS, runtime.GOARCH)
a.logger.Infof("Initializing app in %s directory", conf.DataDir())
return a.logger
}
func (a *Application) Ctx() context.Context {
return a.ctx
}
func (a *Application) Close() {
a.Conf.Save()
// Teardown VPN gateway routes first (restore direct internet before shutting down P2P)
if a.VPNGateway != nil {
a.VPNGateway.TeardownAtShutdown()
}
if a.ctxCancel != nil {
a.ctxCancel()
}
if a.Api != nil {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
err := a.Api.Shutdown(ctx)
if err != nil {
a.logger.Errorf("closing api server: %v", err)
}
}
if a.Tunnel != nil {
a.Tunnel.Close()
}
if a.SOCKS5 != nil {
a.SOCKS5.Close()
}
if a.P2p != nil {
err := a.P2p.Close()
if err != nil {
a.logger.Errorf("closing p2p server: %v", err)
}
}
if a.Dns != nil {
a.Dns.Close()
}
if a.vpnDevice != nil {
err := a.vpnDevice.Close()
if err != nil {
a.logger.Errorf("closing vpn: %v", err)
}
}
a.Conf.Close()
}
func (a *Application) makeP2pHostConfig() p2p.HostConfig {
// TODO: use persistent datastore. Check out badger2. Old badger datastore constantly use disk io
peerstore, err := pstoremem.NewPeerstore()
if err != nil {
panic(err)
}
resourceLimitsConfig := rcmgr.InfiniteLimits
mgr, err := rcmgr.NewResourceManager(rcmgr.NewFixedLimiter(resourceLimitsConfig))
if err != nil {
panic(err)
}
return p2p.HostConfig{
PrivKeyBytes: a.Conf.PrivKey(),
ListenAddrs: a.Conf.GetListenAddresses(),
UserAgent: config.UserAgent,
BootstrapPeers: a.Conf.GetBootstrapPeers(),
AllowEmptyBootstrapPeers: a.AllowEmptyBootstrapPeers,
EnableAutoRelay: true,
// SocketControlFunc is always used: marking happens at dial
// time on every socket, so libp2p connections opened *before* gateway
// mode is toggled on at runtime are already exempt from the VPN route.
SocketControlFunc: a.NetManager.ControlFunc(),
Libp2pOpts: append([]libp2p.Option{
libp2p.EnableRelay(),
libp2p.EnableAutoNATv2(),
libp2p.ResourceManager(mgr),
libp2p.EnableHolePunching(),
libp2p.NATPortMap(),
libp2p.PrometheusRegisterer(prometheus.DefaultRegisterer),
}, a.ExtraLibp2pOpts...),
ConnManager: struct {
LowWater int
HighWater int
GracePeriod time.Duration
}{
LowWater: 50,
HighWater: 100,
GracePeriod: time.Minute,
},
Peerstore: peerstore,
DHTDatastore: dssync.MutexWrap(ds.NewMapDatastore()),
}
}
type DNSService struct {
conf *config.Config
eventbus awlevent.Bus
ctx context.Context
logger *log.ZapEventLogger
mu sync.Mutex
dnsHost string
dnsOsConfigurator dns.OSConfigurator
dnsResolver *awldns.Resolver
dnsBridge *dnsbridge.Bridge
upstreamDNS string
isAwlDNSSetAsSystem bool
// forceUpstream forces the awl resolver to capture all queries
// (MatchDomains=nil) and forward them to the configured public upstream so
// DNS traverses the tunnel instead of leaking to the system resolver. Set
// in VPN gateway client mode. Desktop only: the Android netstack bridge has
// no split-DNS choice to make (it already captures all device DNS), so it
// leaves this at zero and ForceUpstreamDNS is a no-op there.
forceUpstream bool
}
func NewDNSService(conf *config.Config, eventbus awlevent.Bus, ctx context.Context, logger *log.ZapEventLogger) *DNSService {
return &DNSService{conf: conf, eventbus: eventbus, ctx: ctx, logger: logger}
}
func (a *DNSService) initDNS(interfaceName string) {
a.mu.Lock()
defer a.mu.Unlock()
dnsAddr := a.conf.DNS.ListenAddress
dnsHost, _, err := net.SplitHostPort(dnsAddr)
if err != nil {
a.logger.Errorf("invalid dns listen address %s: %v", dnsAddr, err)
return
}
a.dnsHost = dnsHost
a.dnsResolver = awldns.NewResolver(dnsAddr)
a.upstreamDNS = a.conf.DNS.UpstreamDNSAddress
a.forceUpstream = a.conf.VPNGateway.ClientEnabled
a.refreshDNSConfigLocked()
awlevent.WrapSubscriptionToCallback(a.ctx, func(_ interface{}) {
a.mu.Lock()
defer a.mu.Unlock()
a.refreshDNSConfigLocked()
}, a.eventbus, new(awlevent.KnownPeerChanged))
tsLogger := log.Logger("ts/dnsconf")
a.dnsOsConfigurator, err = dns.NewOSConfigurator(func(format string, args ...interface{}) {
tsLogger.Infof(format, args...)
}, nil, &controlknobs.Knobs{}, interfaceName)
if err != nil {
a.logger.Errorf("unable to create dns os configurator: %v", err)
return
}
a.applyOSDNSConfigLocked()
}
// initDNSAndroid sets up the Android DNS path: no OS sockets and no OS DNS
// configurator. A netstack bridge (awldns/dnsbridge) owns the in-subnet DNS
// IP, the Tunnel feeds it packets intercepted from the TUN read path, and the
// resolver serves on the bridge's listeners. The Android host passes the same
// IP to VpnService.Builder.addDnsServer, so all device DNS arrives there. On
// any failure DNS stays off with a log; VPN keeps working.
func (a *DNSService) initDNSAndroid(vpnDevice *vpn.Device, tunnel *service.Tunnel) {
a.mu.Lock()
defer a.mu.Unlock()
dnsIP := a.conf.NetstackDNSIP()
if dnsIP == nil {
a.logger.Errorf("no free IP for the DNS server in VPN subnet %s, DNS is disabled", a.conf.VPNConfig.IPNet)
return
}
dnsAddr, ok := netip.AddrFromSlice(dnsIP.To4())
if !ok {
a.logger.Errorf("invalid DNS server IP %v, DNS is disabled", dnsIP)
return
}
bridge, err := dnsbridge.New(dnsAddr, vpn.InterfaceMTU, vpnDevice.WriteRawPacket)
if err != nil {
a.logger.Errorf("create DNS netstack bridge, DNS is disabled: %v", err)
return
}
a.dnsBridge = bridge
a.dnsResolver = awldns.NewResolverFromListeners(bridge.UDPConn(), bridge.TCPListener(),
net.JoinHostPort(dnsIP.String(), awldns.DefaultDNSPort))
// TODO(android awldns): use the system DNS servers reported by the Android
// layer (ConnectivityManager network callback) as upstream, so LAN names
// keep resolving; for now non-.awl queries always go to the configured
// public upstream. In VPN gateway client mode the resolver's upstream
// socket is deliberately unprotected: its traffic loops back into the TUN
// and leaves through the gateway peer — no DNS leak.
a.upstreamDNS = a.conf.DNS.UpstreamDNSAddress
a.refreshDNSConfigLocked()
awlevent.WrapSubscriptionToCallback(a.ctx, func(_ interface{}) {
a.mu.Lock()
defer a.mu.Unlock()
a.refreshDNSConfigLocked()
}, a.eventbus, new(awlevent.KnownPeerChanged))
tunnel.SetDNSHandler(dnsIP, bridge)
// The interceptor now handles all device DNS — the host sets the same IP
// via addDnsServer — which is exactly what this flag means to the UI.
// (dnsIP is config.NetstackDNSIP, reserved from peers since setDefaults.)
a.isAwlDNSSetAsSystem = true
a.logger.Infof("DNS interceptor is set up on %s (upstream %s)", dnsAddr, a.upstreamDNS)
}
// applyOSDNSConfigLocked (re)computes the OS DNS takeover config from the
// current state (split-DNS support, base config, forceUpstream) and pushes it
// to the OS, then refreshes the awl resolver. Caller must hold a.mu and have a
// non-nil dnsOsConfigurator. Safe to call repeatedly.
func (a *DNSService) applyOSDNSConfigLocked() {
supportsSplitDNS := a.dnsOsConfigurator.SupportsSplitDNS()
var baseNameservers []netip.Addr
if !supportsSplitDNS {
baseOSConfig, err := a.dnsOsConfigurator.GetBaseConfig()
if err != nil {
a.logger.Errorf("get base config from os configurator, abort setting os dns: %v", err)
return
}
a.logger.Infof("os does not support split dns. base config: %v", baseOSConfig)
baseNameservers = baseOSConfig.Nameservers
}
matchDomains, upstream := chooseDNSPolicy(a.forceUpstream, supportsSplitDNS, baseNameservers, a.conf.DNS.UpstreamDNSAddress)
a.upstreamDNS = upstream
a.refreshDNSConfigLocked()
// TODO: consider setting SearchDomains = ["awl."] so peers resolve by bare
// short name (e.g. "mypeer" -> "mypeer.awl") instead of requiring the full
// .awl suffix. SearchDomains expands single-label queries into FQDNs and is
// additive to the OS's existing search list (distinct from MatchDomains,
// which only routes which zones reach the awl resolver). Would likely want a
// config toggle to gate it.
//
// TODO: consider pushing admin.awl into Hosts (a static FQDN->IP map applied
// to /etc/hosts) instead of (or in addition to) injecting
// AdminHttpServerDomainName into the resolver name mapping in
// refreshDNSConfigLocked — that would make the admin UI name resolvable even
// when the awl :53 resolver itself is not reachable.
newOSConfig := dns.OSConfig{
Nameservers: []netip.Addr{netip.MustParseAddr(a.dnsHost)},
MatchDomains: matchDomains,
}
if err := a.dnsOsConfigurator.SetDNS(newOSConfig); err != nil {
a.logger.Errorf("set dns config to os configurator: %v", err)
return
}
a.logger.Infof("successfully set dns config to os (forceUpstream=%v, upstream=%s, matchDomains=%v)",
a.forceUpstream, a.upstreamDNS, matchDomains)
a.isAwlDNSSetAsSystem = true
}
// chooseDNSPolicy decides which domains the awl resolver should capture and
// which upstream it forwards non-.awl queries to.
//
// - forceUpstream (VPN gateway client mode): capture everything
// (MatchDomains=nil) and forward to the configured public upstream so DNS
// goes through the tunnel — no leak.
// - split-DNS supported: capture only .awl; other queries are handled by the
// OS resolver directly, so the awl upstream is unused (kept as the
// configured default for completeness).
// - split-DNS unsupported: capture everything and forward to the system's
// first base nameserver, falling back to the configured default when the OS
// reports none.
func chooseDNSPolicy(forceUpstream, supportsSplitDNS bool, base []netip.Addr, upstreamCfg string) (matchDomains []dnsname.FQDN, upstream string) {
awlFQDN, err := dnsname.ToFQDN(awldns.LocalDomain)
if err != nil {
panic(err)
}
if forceUpstream {
return nil, upstreamCfg
}
if supportsSplitDNS {
return []dnsname.FQDN{awlFQDN}, upstreamCfg
}
// no split DNS: capture everything, forward to the system's base resolver
if len(base) == 0 {
return nil, upstreamCfg
}
// TODO: use all nameservers in awldns resolver proxy
return nil, net.JoinHostPort(base[0].String(), awldns.DefaultDNSPort)
}
// ForceUpstreamDNS toggles full-capture mode where the awl resolver intercepts
// all DNS (not just .awl) and forwards it to the configured public upstream, so
// queries traverse the tunnel and do not leak. Driven by the VPN gateway client
// apply/teardown. No-op (returns nil) when DNS was never set up as the system
// resolver (DNS disabled, or Android where the OS DNS takeover does not apply).
// Idempotent.
func (a *DNSService) ForceUpstreamDNS(enabled bool) error {
a.mu.Lock()
defer a.mu.Unlock()
if a.dnsOsConfigurator == nil || !a.isAwlDNSSetAsSystem {
return nil
}
if a.forceUpstream == enabled {
return nil
}
a.forceUpstream = enabled
a.applyOSDNSConfigLocked()
return nil
}
func (a *DNSService) refreshDNSConfigLocked() {
if a.dnsResolver == nil {
a.logger.DPanicf("called refreshDNSConfig with nil resolver %v", a.dnsResolver)
return
}
dnsNamesMapping := a.conf.DNSNamesMapping()
// TODO(android awldns): make admin.awl work on Android. The admin server is
// not reachable on AdminHttpServerIP there (the API listens elsewhere and
// port 80 cannot be bound), so don't advertise a dead name.
if runtime.GOOS != "android" {
dnsNamesMapping[config.AdminHttpServerDomainName] = config.AdminHttpServerIP
}
dnsNamesMappingV6 := a.conf.DNSNamesMappingV6()
a.dnsResolver.ReceiveConfiguration(a.upstreamDNS, dnsNamesMapping, dnsNamesMappingV6)
}
func (a *DNSService) Close() {
a.mu.Lock()
defer a.mu.Unlock()
if a.dnsOsConfigurator != nil {
err := a.dnsOsConfigurator.Close()
if err != nil {
a.logger.Errorf("closing dns configurator: %v", err)
}
}
if a.dnsResolver != nil {
a.dnsResolver.Close()
}
if a.dnsBridge != nil {
a.dnsBridge.Close()
}
}
// AwlDNSAddress returns the resolver address (ip:port) to display in the
// status API/UI/CLI, empty until both resolver servers are up. Not the
// host-wiring IP — for that see NetstackDNSServerIP.
func (a *DNSService) AwlDNSAddress() string {
a.mu.Lock()
defer a.mu.Unlock()
if a.dnsResolver != nil {
return a.dnsResolver.DNSAddress()
}
return ""
}
func (a *DNSService) IsAwlDNSSetAsSystem() bool {
a.mu.Lock()
defer a.mu.Unlock()
return a.isAwlDNSSetAsSystem
}
// NetstackDNSServerIP returns the in-tunnel IP owned by the running DNS
// interceptor (Android), nil when the interceptor is not set up.
func (a *DNSService) NetstackDNSServerIP() net.IP {
a.mu.Lock()
defer a.mu.Unlock()
if a.dnsBridge == nil {
return nil
}
return a.dnsBridge.DNSIP().AsSlice()
}
// configMetricsAdapter implements metrics.ConfigMetrics by combining Config and AuthStatus.
type configMetricsAdapter struct {
conf *config.Config
authStatus *service.AuthStatus
p2p *p2p.P2p
}
func (a *configMetricsAdapter) GetKnownPeersSnapshot() (total, confirmed, connected int, peerIDs []peer.ID) {
a.conf.RLock()
defer a.conf.RUnlock()
total = len(a.conf.KnownPeers)
peerIDs = make([]peer.ID, 0, total)
for _, kp := range a.conf.KnownPeers {
pid := kp.PeerId()
peerIDs = append(peerIDs, pid)
if kp.Confirmed {
confirmed++
}
if a.p2p.IsConnected(pid) {
connected++
}
}
return
}
func (a *configMetricsAdapter) GetBlockedPeersCount() int {
a.conf.RLock()
defer a.conf.RUnlock()
return len(a.conf.BlockedPeers)
}
func (a *configMetricsAdapter) GetAuthRequestCounts() (ingoing, outgoing int) {
return a.authStatus.GetAuthRequestCounts()
}