Compare commits

...

689 Commits

Author SHA1 Message Date
Brad Fitzpatrick
e6dbb4425c cmd/cloner, tailcfg: fix nil vs len 0 issues, add tests, use for Hostinfo
Also use go:generate and https://golang.org/s/generatedcode header style.
2020-07-27 10:41:06 -07:00
Brad Fitzpatrick
38b0c3eea2 version: new week, new version 2020-07-27 10:20:58 -07:00
Brad Fitzpatrick
43e2efe441 go mod tidy 2020-07-27 10:20:30 -07:00
Brad Fitzpatrick
fe68841dc7 wgengine/magicsock: log better with less spam on transition to stopped state
Required a minor test update too, which now needs a private key to get far
enough to test the thing being tested.
2020-07-27 10:19:17 -07:00
Brad Fitzpatrick
69f3ceeb7c derp/derphttp: don't return all nil from dialRegion when STUNOnly nodes 2020-07-27 10:10:10 -07:00
David Crawshaw
990e2f1ae9 tailcfg: generate some Clone methods
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-07-27 11:08:09 +10:00
David Crawshaw
961b9c8abf cmd/cloner: tool to generate Clone methods
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-07-27 11:08:09 +10:00
Brad Fitzpatrick
e298327ba8 wgengine/magicsock: remove overkill, slow reflect.DeepEqual of NetworkMap
No need to allocate or compare all the fields we don't care about.
2020-07-25 19:37:08 -07:00
Brad Fitzpatrick
be3ca5cbfd control/controlclient: remove unused, slow, often-not-what-you-want NetworkMap.Equal 2020-07-25 19:36:39 -07:00
Brad Fitzpatrick
4970e771ab wgengine: add debug knob to disable the watchdog during debugging
It launches goroutines and interferes with panic-based debugging,
obscuring stacks.
2020-07-25 12:59:53 -07:00
David Anderson
3669296cef wgengine/magicsock: refactor twoDevicePing to make stack construction cleaner.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-07-24 15:12:15 -07:00
Elias Naur
0a42b0a726 ipn: add OSVersion, DeviceModel fields to Prefs and propagate to Hostinfos
Needed for Android.

Signed-off-by: Elias Naur <mail@eliasnaur.com>
2020-07-24 14:12:29 -07:00
Brad Fitzpatrick
16a9cfe2f4 wgengine: configure wireguard peers lazily, as needed
wireguard-go uses 3 goroutines per peer (with reasonably large stacks
& buffers).

Rather than tell wireguard-go about all our peers, only tell it about
peers we're actively communicating with. That means we need hooks into
magicsock's packet receiving path and tstun's packet sending path to
lazily create a wireguard peer on demand from the network map.

This frees up lots of memory for iOS (where we have almost nothing
left for larger domains with many users).

We should ideally do this in wireguard-go itself one day, but that'd
be a pretty big change.

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-07-24 12:50:15 -07:00
Brad Fitzpatrick
5066b824a6 wgengine/magicsock: don't log about disco ping timeouts if we have a working address
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-07-24 11:21:50 -07:00
Brad Fitzpatrick
648268192b go.mod: bump wireguard-go 2020-07-24 08:54:17 -07:00
Brad Fitzpatrick
a89d610a3d wgengine/tstun: move sync.Pool to package global
sync.Pools should almost always be packate globals, even though in this
case we only have exactly 1 TUN device anyway, so it matters less.
Still, it's unusual to see a Pool that's not a package global, so move it.
2020-07-24 08:29:36 -07:00
Dmytro Shynkevych
318751c486 cmd/tailscaled: always flush logs properly
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-07-23 19:08:17 -04:00
Dmytro Shynkevych
4957360ecd cmd/tailscale: rename use-dns to accept-dns
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-07-23 16:09:33 -04:00
Dmytro Shynkevych
dd4e06f383 cmd/tailscale: add corpDNS flag
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-07-23 15:28:53 -04:00
Dmytro Shynkevych
c53ab3111d wgengine/router: support legacy resolvconf
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-07-23 15:01:46 -04:00
Brad Fitzpatrick
05a79d79ae control/controlclient: rewrite, test NetworkMap.ConciseDiffFrom
It stood out a lot in hello.ipn.dev's profiles for generating a lot of
garbage (and thus GC CPU).
2020-07-23 10:50:06 -07:00
Brad Fitzpatrick
48fc9026e9 tailcfg: optimize Node.Equal allocs a bit
Noticed while working on something else.
2020-07-23 10:47:49 -07:00
Brad Fitzpatrick
3b0514ef6d control/controlclient: rename uflags, give it a type, remove dead code 2020-07-23 08:38:14 -07:00
Brad Fitzpatrick
32ecdea157 control/controlclient: generate wireguard config w/o WgQuick text indirection 2020-07-23 08:30:09 -07:00
Brad Fitzpatrick
2545575dd5 cmd/tailscale: default to not reporting daemon version
That's what I meant to do when I added "tailscale version" but
apparently I didn't.
2020-07-22 14:05:51 -07:00
David Anderson
189d86cce5 wgengine/router: don't use 88 or 8888 as table/rule numbers.
We originally picked those numbers somewhat at random, but with the idea
that 8 is a traditionally lucky number in Chinese culture. Unfortunately,
"88" is also neo-nazi shorthand language.

Use 52 instead, because those are the digits above the letters
"TS" (tailscale) on a qwerty keyboard, so we're unlikely to collide with
other users. 5, 2 and 52 are also pleasantly culturally meaningless.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-07-22 11:59:54 -07:00
Dmytro Shynkevych
218de6d530 ipn: load hostname in Start.
This prevents hostname being forced to os.Hostname despite override
when control is contacted for the first time after starting tailscaled.

Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-07-22 13:37:41 -04:00
Brad Fitzpatrick
de11f90d9d ipn: remove unused parameter to func LoadPrefs, fix godoc subject 2020-07-22 10:35:35 -07:00
David Anderson
972a42cb33 wgengine/router: fix router_test to match the new marks.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-07-22 01:31:49 +00:00
David Anderson
d60917c0f1 wgengine/router: switch packet marks to avoid conflict with Weave Net.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-07-22 01:24:46 +00:00
Brad Fitzpatrick
f26b409bd5 tempfork: add lite fork of net/http/pprof w/o html/template or reflect 2020-07-21 16:17:03 -07:00
Brad Fitzpatrick
6095a9b423 cmd/tailscale: add "version" subcommand
Fixes #448

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-07-21 12:23:33 -07:00
Brad Fitzpatrick
f745e1c058 version: new week, new version 2020-07-20 20:55:47 -07:00
Brad Fitzpatrick
ca2428ecaf tailcfg: add Hostinfo.OSVersion, DeviceModel
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-07-20 16:10:06 -07:00
Brad Fitzpatrick
d8e67ca2ab safesocket: gofmt
gofmt differences between versions :(
2020-07-20 14:40:19 -07:00
Brad Fitzpatrick
f562c35c0d safesocket: support connecting to Mac TCP server from within App Sandbox 2020-07-20 14:23:50 -07:00
Brad Fitzpatrick
f267a7396f metrics: add LabelMap.GetFloat 2020-07-19 12:31:12 -07:00
Brad Fitzpatrick
c06d2a8513 wgengine/magicsock: fix typo in comment 2020-07-18 13:57:26 -07:00
Brad Fitzpatrick
bf195cd3d8 wgengine/magicsock: reduce log verbosity of discovery messages
Don't log heartbeat pings & pongs. Track the reason for pings and then
only log the ping/pong traffic if it was for initial path discovery.
2020-07-18 13:54:00 -07:00
Brad Fitzpatrick
7cf50f6c84 go.sum: update 2020-07-18 13:43:11 -07:00
Dmytro Shynkevych
3efc29d39d go.mod: bump netaddr.
Closes #567.

Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-07-18 04:28:03 -04:00
Dmytro Shynkevych
a3e7252ce6 wgengine/router: use better NetworkManager API
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-07-18 04:03:45 -04:00
Eduardo Kienetz
5df6be9d38 Use LittleEndian for correct byte order on DNS IPs
Nameserver IP 10.11.12.13 would otherwise get written to resolv.conf as 13.12.11.10, as was happening on my client.

Signed-off-by: Eduardo Kienetz <eduardo@kienetz.com>
2020-07-17 23:34:28 -07:00
Brad Fitzpatrick
52969bdfb0 derp: fix atomic padding on 32-bit again
Broken by earlier OnlyDisco addition.
2020-07-16 13:38:21 -07:00
Brad Fitzpatrick
a6559a8924 wgengine/magicsock: run test DERP in mode where only disco packets allowed
So we don't accidentally pass a NAT traversal test by having DERP pick up our slack
when we really just wanted DERP as an OOB messaging channel.
2020-07-16 12:58:35 -07:00
Brad Fitzpatrick
75e1cc1dd5 github/workflows: add go vet ./... step 2020-07-16 09:15:09 -07:00
Brad Fitzpatrick
10ac066013 all: fix vet warnings 2020-07-16 08:39:38 -07:00
Brad Fitzpatrick
d74c9aa95b wgengine/magicsock: update comment, fix earlier commit
891898525c had a continue that meant the didCopy synchronization never ran.
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-07-16 08:29:38 -07:00
Brad Fitzpatrick
c976264bd1 wgengine/magicsock: gofmt 2020-07-16 08:15:27 -07:00
Dmytro Shynkevych
f3e2b65637 wgengine/magicsock: time.Sleep -> time.After
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-07-16 11:04:53 -04:00
Dmytro Shynkevych
380ee76d00 wgengine/magicsock: make time.Sleep in runDerpReader respect cancellation.
Before this patch, the 250ms sleep would not be interrupted by context cancellation,
which would result in the goroutine sometimes lingering in tests (100ms grace period).

Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-07-16 10:45:48 -04:00
Dmytro Shynkevych
891898525c wgengine/magicsock: make receive from didCopy respect cancellation.
Very rarely, cancellation occurs between a successful send on derpRecvCh
and a call to copyBuf on the receiving side.
Without this patch, this situation results in <-copyBuf blocking indefinitely.

Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-07-16 10:34:49 -04:00
Brad Fitzpatrick
1f923124bf ipn/ipnserver: support simultaneous connections
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-07-15 21:39:09 -07:00
Dmytro Shynkevych
852136a03c cmd/tailscale: simplify hostname validation
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-07-15 21:32:25 -07:00
Dmytro Shynkevych
65d2537c05 cmd/tailscale: modify empty hostname case
Signed-Off-By: Dmytro Shynkevych <dmytro@tailscale.com>
2020-07-15 21:32:25 -07:00
Dmytro Shynkevych
8163521c33 cmd/tailscale: allow overriding hostname in tailscale up
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-07-15 21:32:25 -07:00
Brad Fitzpatrick
a2267aae99 wgengine: only launch pingers for peers predating the discovery protocol
Peers advertising a discovery key know how to speak the discovery
protocol and do their own heartbeats to get through NATs and keep NATs
open. No need for the pinger except for with legacy peers.
2020-07-15 21:08:26 -07:00
Brad Fitzpatrick
cdfea347d0 wgengine: update for tailscale/wireguard-go API changes
* update to new HandshakeDone signature
* use new Device.IpcGetOperationFiltered call to avoid sending allowed_ips

See dd6c1c8fe1
2020-07-15 20:30:45 -07:00
Brad Fitzpatrick
44baa3463f cmd/tailscale/cli: add initial predicate func ActLikeCLI 2020-07-15 18:56:07 -07:00
David Anderson
45578b47f3 tstest/natlab: refactor PacketHandler into a larger interface.
The new interface lets implementors more precisely distinguish
local traffic from forwarded traffic, and applies different
forwarding logic within Machines for each type. This allows
Machines to be packet forwarders, which didn't quite work
with the implementation of Inject.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-07-15 14:38:33 -07:00
Brad Fitzpatrick
723b9eecb0 net/interfaces: set SysProcAttr.HideWindow to prevent cmd.exe flash on Windows 2020-07-15 12:43:48 -07:00
Brad Fitzpatrick
df674d4189 atomicfile: don't Chmod on windows
Not supported.
2020-07-15 12:31:40 -07:00
Dmytro Shynkevych
d361511512 control/controlclient: eliminate race in loginGoal access.
This code is currently racy due to an incorrect assumption
that goal is never modified in-place, so does not require extra locking.
This change makes the assumption correct.

Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-07-15 13:04:44 -04:00
Dmytro Shynkevych
19d77ce6a3 cmd/tailscale: fix typo in license headers
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-07-15 12:48:35 -04:00
Brad Fitzpatrick
7ba148e54e cmd/tailscale: make tailscale status -active also filter in -json mode 2020-07-15 09:28:37 -07:00
Dmytro Shynkevych
19867b2b6d tstun: remove buggy-looking log line.
This log line looks buggy, even though lacking a filter is expected during bringup.
We already know if we forget to SetFilter: it breaks the magicsock test,
so no useful information is lost.

Resolves #559.

Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-07-15 11:48:33 -04:00
Brad Fitzpatrick
60f4982f9b cmd/tailscale: move code into new reusable cmd/tailscale/cli package
cmd/tailscale's package main is now just a few lines.

This'll let us embed the CLI in the Mac and Windows clients.

Updates #541
2020-07-15 07:58:29 -07:00
Brad Fitzpatrick
bcbd41102c atomicfile: use ioutil.TempFile, sync
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-07-14 21:58:06 -07:00
Wendi Yu
c3736250a4 wgengine: fix macos staticcheck errors (#557)
Signed-off-by: Wendi <wendi.yu@yahoo.ca>
2020-07-14 17:28:02 -06:00
Dmytro Shynkevych
d9ac2ada45 ipn: add self to dns map
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-07-14 18:50:07 -04:00
Dmytro Shynkevych
3b36400e35 tsdns: response to type ANY queries
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-07-14 18:50:07 -04:00
Zijie Lu
c9e40abfb8 tsweb: jsonhandler: fix content type
Signed-off-by: Zijie Lu <zijie@tailscale.com>
2020-07-14 15:27:26 -04:00
David Anderson
23123907c0 tstest/natlab: add a configurable SNAT44 translator.
This lets us implement the most common kinds of NAT in the wild.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-07-14 12:17:47 -07:00
Dmytro Shynkevych
2f15894a10 wgengine/magicsock: wait for derphttp client goroutine to exit
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-07-14 14:20:35 -04:00
Elias Naur
fa45d606fa types/logger: fix go test vet error
Silences

types/logger/logger_test.go:63:30: conversion from int to string yields a string of one rune

Signed-off-by: Elias Naur <mail@eliasnaur.com>
2020-07-14 09:28:45 -07:00
Dmytro Shynkevych
30bbbe9467 wgengine/router: dns: unify on *BSD, multimode on Linux, Magic DNS (#536)
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-07-14 09:12:00 -04:00
Elias Naur
6e8f0860af ipn: add Login backend command for sign-in with token
The StartLoginInteractive command is for delegating the sign-in flow
to a browser. The Android Gooogle Sign-In SDK inverts the flow by
giving the client ID tokens.

Add a new backend command for accepting such tokens by exposing the existing
controlclient.Client.Login support for OAuth2 tokens. Introduce a custom
TokenType to distinguish ID tokens from other OAuth2 tokens.

Signed-off-by: Elias Naur <mail@eliasnaur.com>
2020-07-14 13:09:36 +02:00
Brad Fitzpatrick
969206fe88 version: new week, new date 2020-07-13 11:52:03 -07:00
Brad Fitzpatrick
e589c76e98 cmd/tailscaled: don't require --socket path on windows 2020-07-13 11:30:46 -07:00
David Anderson
39ecb37fd6 tstest/natlab: support different firewall selectivities.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-07-13 10:52:46 -07:00
Brad Fitzpatrick
c1d9e41bef cmd/tailscaled: use "Tailscale" as default TUN device name on Windows
That's what's used in the Windows GUI version and seems special. If we don't use
that, Windows tries to rename it and fails.
2020-07-13 09:23:57 -07:00
Brad Fitzpatrick
f98706bdb3 paths, cmd/tailscaled: on Windows, don't try to migrate from legacy relay.conf
Avoids confusing logspam on Windows.
2020-07-13 08:59:54 -07:00
Dmytro Shynkevych
61abab999e cmd/tailscaled: graceful shutdown (#534)
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-07-13 06:17:58 -04:00
Brad Fitzpatrick
6255ce55df Revert "version: don't have a third version number form for xcode"
This reverts commit 5280d039c4.

Turns out to not be possible. The semver form and the human readable
form both must of form x.y.z.
2020-07-12 14:45:06 -07:00
David Anderson
88e8456e9b wgengine/magicsock: add a connectivity test for facing firewalls.
The test demonstrates that magicsock can traverse two stateful
firewalls facing each other, that each require localhost to
initiate connections.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-07-11 07:04:08 +00:00
David Anderson
1f7b1a4c6c wgengine/magicsock: rearrange TwoDevicePing test for future natlab tests.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-07-11 06:48:08 +00:00
David Anderson
b3d65ba943 tstest/natlab: refactor, expose a Packet type.
HandlePacket and Inject now receive/take Packets. This is a handy
container for the packet, and the attached Trace method can be used
to print traces from custom packet handlers that integrate nicely
with natlab's internal traces.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-07-11 06:33:01 +00:00
David Anderson
5eedbcedd1 tstest/natlab: add a stateful firewall.
The firewall provides a ProcessPacket handler, and implements an
address-and-port endpoint dependent firewall that allows all
traffic to egress from the trusted interface, and only allows
inbound traffic if corresponding outbound traffic was previously
seen.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-07-11 05:17:38 +00:00
David Anderson
0ed9f62ed0 tstest/natlab: provide inbound interface to HandlePacket.
Requires a bunch of refactoring so that Networks only ever
refer to Interfaces that have been attached to them, and
Interfaces know about both their Network and Machine.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-07-10 20:08:48 -07:00
David Anderson
977381f9cc wgengine/magicsock: make trivial natlab test pass.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-07-11 01:53:21 +00:00
Brad Fitzpatrick
6c74065053 wgengine/magicsock, tstest/natlab: start hooking up natlab to magicsock
Also adds ephemeral port support to natlab.

Work in progress.

Pairing with @danderson.
2020-07-10 14:32:58 -07:00
Brad Fitzpatrick
edcbb5394e go.sum: update 2020-07-10 14:31:29 -07:00
Dmytro Shynkevych
21d1dbfce0 wgengine/tsdns: local DNS server for testing
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-07-10 14:56:59 -04:00
Brad Fitzpatrick
7815633821 github: also run 32-bit tests on Linux
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-07-10 08:43:12 -07:00
Brad Fitzpatrick
98ffd78251 go.mod: bump wireguard-go dep 2020-07-09 21:46:44 -07:00
Brad Fitzpatrick
dba9b96908 version: remove quoting around version name
I added them earlier while fighting our redo+xcode build which wasn't
picking up these files on incremental builds. It still isn't, but now I've
verified with full builds that no quotes is correct.
2020-07-09 14:38:23 -07:00
Brad Fitzpatrick
96994ec431 control/controlclient: fix a couple more data races 2020-07-09 11:42:43 -07:00
Brad Fitzpatrick
0551bec95b cmd/tailscale: add -active flag to 'tailscale status' to filter out inactive peers 2020-07-09 10:38:18 -07:00
Brad Fitzpatrick
96d806789f ipn: add Notify.LocalTCPPort field for macOS Network Extension to use
We want the macOS Network Extension to share fate with the UI frontend,
so we need the backend to know when the frontend disappears.

One easy way to do that is to reuse the existing TCP server it's
already running (for tailscale status clietns).

We now tell the frontend our ephemeral TCP port number, and then have
the UI connect to it, so the backend can know when it disappears.

There are likely Swift ways of doing this, but I couldn't find them
quickly enough, so I reached for the hammer I knew.
2020-07-09 09:11:23 -07:00
Dmytro Shynkevych
248d28671b tsdns: fix race in delegate
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-07-08 20:07:14 -04:00
Brad Fitzpatrick
bd59bba8e6 wgengine/magicsock: stop discoEndpoint timers on Close
And add some defensive early returns on c.closed.
2020-07-08 16:51:17 -07:00
Brad Fitzpatrick
a8b95571fb ipn, control/controlclient: fix some data races
More remain.

Fixes tailscale/corp#432
2020-07-08 16:51:17 -07:00
Brad Fitzpatrick
de875a4d87 wgengine/magicsock: remove DisableSTUNForTesting 2020-07-08 15:50:41 -07:00
Brad Fitzpatrick
ecf5d69c7c net/netcheck: add missing comment asked for in earlier code review 2020-07-08 15:26:56 -07:00
Brad Fitzpatrick
3984f9be2f ipn, ipn/ipnserver: add support for serving in error-message-only mode
So Windows service failures can be propagated to the Windows UI client.
2020-07-08 14:20:01 -07:00
Brad Fitzpatrick
5280d039c4 version: don't have a third version number form for xcode
Our primary version format is git describe --long --abbrev=9.

Our Apple scheme is:
    (major+100).minor.(patch*10,000+gitDescribeCommits).

This CL gets rid of the third, which was:
    major.minor.(patch*10,000+gitDescribeCommits).

Now the "About" box in the macOS app shows the same version that we
show on pkgs.tailscale.com, userz, changelog, etc.

This will be more important once/if we get standalone DMG downloads
for macOS on pkgs.tailscale.com.

Fixes tailscale/corp#364
2020-07-07 21:49:58 -07:00
Brad Fitzpatrick
0d481030f3 tailcfg: use ? for portmap summary to match netcheck 2020-07-07 18:54:50 -07:00
Dmytro Shynkevych
67ebba90e1 tsdns: dual resolution mode, IPv6 support (#526)
This change adds to tsdns the ability to delegate lookups to upstream nameservers.
This is crucial for setting Magic DNS as the system resolver.

Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-07-07 15:25:32 -04:00
Brad Fitzpatrick
ce1b52bb71 wgengine/monitor: fix other potential crashes on Linux
Never return "nil, nil" anymore. The caller expected a usable
interface now. I missed some of these earlier.

Also, handle address deletion now.

Updates #532
2020-07-07 11:08:16 -07:00
Brad Fitzpatrick
4b75a27969 wgengine/monitor: fix crash on Linux on type 21 messages
Fixes #532
2020-07-07 10:45:25 -07:00
Brad Fitzpatrick
c1cabe75dc derp: fix server struct fielfd alignment on 32-bit
Mostly so the GitHub CI will pass on 32-bit.
2020-07-07 09:08:15 -07:00
Brad Fitzpatrick
724ad13fe1 wgengine/tstun: fix alignment of 64-bit atomic field
We had a test for it, but no 32-bit builder apparently. :(

Fixes #529
2020-07-07 08:28:40 -07:00
Brad Fitzpatrick
4db60a8436 wgengine/monitor: parse Linux netlink messages, ignore our own events
Fixes tailscale/corp#412 ("flood of link change events at start-up")

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-07-06 22:42:01 -07:00
Brad Fitzpatrick
742b8b44a8 net/tsaddr: new package to hold Tailscale-specific IPs/ranges
And update existing callers with (near) duplicated cases.
2020-07-06 22:33:29 -07:00
Brad Fitzpatrick
5c6d8e3053 netcheck, tailcfg, interfaces, magicsock: survey UPnP, NAT-PMP, PCP
Don't do anything with UPnP, NAT-PMP, PCP yet, but see how common they
are in the wild.

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-07-06 15:25:35 -07:00
Brad Fitzpatrick
6196b7e658 wgengine/magicsock: change API to not permit disco key changes
Generate the disco key ourselves and give out the public half instead.

Fixes #525
2020-07-06 12:10:39 -07:00
Brad Fitzpatrick
32156330a8 net/interfaces: add func LikelyHomeRouterIP
For discovering where we might direct NAT-PMP/PCP/UPnP queries at in
the future.
2020-07-06 10:38:00 -07:00
Brad Fitzpatrick
c3c607e78a util/lineread: add little package to read lines from files/Readers 2020-07-06 10:34:33 -07:00
Brad Fitzpatrick
cf74e9039e net/netcheck: add an informative payload in the netcheck UDP helper packets
Per comment from @normanr:
0a5ab533c1 (r40401954)

Updates #188
2020-07-06 09:55:11 -07:00
Brad Fitzpatrick
0a5ab533c1 net/netcheck: send dummy packet out to help airport extreme in hairpin check
At least the Apple Airport Extreme doesn't allow hairpin
sends from a private socket until it's seen traffic from
that src IP:port to something else out on the internet.

See https://github.com/tailscale/tailscale/issues/188#issuecomment-600728643

And it seems that even sending to a likely-filtered RFC 5737
documentation-only IPv4 range is enough to set up the mapping.
So do that for now. In the future we might want to classify networks
that do and don't require this separately. But for now help it.

I've confirmed that this is enough to fix the hairpin check on Avery's
home network, even using the RFC 5737 IP.

Fixes #188
2020-07-06 08:24:22 -07:00
Brad Fitzpatrick
b9a95e6ce1 go.sum: add missing lines 2020-07-06 08:23:44 -07:00
Brad Fitzpatrick
0fc15dcbd5 version: explicitly use 9 hex digits in git describe version number
So it doesn't vary based on who's doing the release with which version
of git.

Fixes tailscale/corp#419
2020-07-03 22:28:45 -07:00
Brad Fitzpatrick
5132edacf7 wgengine/magicsock: fix data race from undocumented wireguard-go requirement
Endpoints need to be Stringers apparently.

Fixes tailscale/corp#422
2020-07-03 22:27:52 -07:00
Brad Fitzpatrick
9fbe8d7cf2 go.mod: bump wireguard 2020-07-03 14:09:29 -07:00
Brad Fitzpatrick
c9089c82e8 control/controlclient, tailcfg: turn active route discovery on by default
Updates #483
2020-07-03 13:55:33 -07:00
Brad Fitzpatrick
3f74859bb0 version: new month, new date string 2020-07-03 13:47:09 -07:00
Brad Fitzpatrick
630379a1d0 cmd/tailscale: add tailscale status region name, last write, consistently star
There's a lot of confusion around what tailscale status shows, so make it better:
show region names, last write time, and put stars around DERP too if active.

Now stars are always present if activity, and always somewhere.
2020-07-03 13:44:22 -07:00
Brad Fitzpatrick
0ea51872c9 types/logger: add rateFreePrefix rate-limiting-exempt log format prefixes
Per conversation with @danderson.
2020-07-03 13:09:32 -07:00
Brad Fitzpatrick
9a8700b02a wgengine/magicsock: add discoEndpoint heartbeat
Updates #483
2020-07-03 12:43:39 -07:00
Brad Fitzpatrick
9f930ef2bf wgengine/magicsock: remove the discoEndpoint.timers map
It ended up being more complicated than it was worth.
2020-07-03 11:45:41 -07:00
Brad Fitzpatrick
f5f3885b5b wgengine/magicsock: bunch of misc discovery path cleanups
* fix tailscale status for peers using discovery
* as part of that, pull out disco address selection into reusable
  and testable discoEndpoint.addrForSendLocked
* truncate ping/pong logged hex txids in half to eliminate noise
* move a bunch of random time constants into named constants
  with docs
* track a history of per-endpoint pong replies for future use &
  status display
* add "send" and " got" prefix to discovery message logging
  immediately before the frame type so it's easier to read than
  searching for the "<-" or "->" arrows earlier in the line; but keep
  those as the more reasily machine readable part for later.

Updates #483
2020-07-03 11:26:22 -07:00
Dmytro Shynkevych
e9643ae724 wgengine: prevent log after exit in watchdog test
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-07-03 10:52:39 -07:00
Dmytro Shynkevych
16b2bbbbbb wgengine: close in reverse order of bringup
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-07-03 10:52:39 -07:00
Brad Fitzpatrick
7883e5c5e7 go.mod: restore staticcheck module, make it stick around, go mod tidy
It kept coming & going as different people ran go mod tidy and others
ran staticcheck.

Make it stop going away with go mod tidy by adding a dep to it.
2020-07-02 22:55:14 -07:00
Brad Fitzpatrick
6c70cf7222 wgengine/magicsock: stop ping timeout timer on pong receipt, misc log cleanup
Updates #483
2020-07-02 22:54:57 -07:00
David Anderson
0aea087766 tstest/natlab: add PacketHandler and Inject.
Together, they can be used to plug custom packet processors into
Machines.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-07-02 21:51:09 -07:00
David Anderson
73db7e99ab tstest/natlab: make Machine constructible directly.
This is a prelude to adding more fields, which would otherwise
become more unnamed function params.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-07-02 21:51:09 -07:00
David Anderson
d94593e884 tstest/natlab: unregister conn4 if registration of conn6 fails.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-07-03 02:27:31 +00:00
David Anderson
d7bc4ec029 tstest/natlab: use common helper for conn registration.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-07-03 02:26:54 +00:00
David Anderson
80a14c49c6 tstest/natlab: add comments to conns4/conns6.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-07-03 02:23:01 +00:00
David Anderson
c53b154171 tstest/natlab: use &Network in test.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-07-03 02:22:06 +00:00
David Anderson
622c0d0cb3 tstest/natlab: print trace data when NATLAB_TRACE is set.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-07-03 02:10:41 +00:00
David Anderson
1d4f9852a7 tstest/natlab: correctly handle dual-stacked PacketConns.
Adds a test with multiple networks, one of which is v4-only.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-07-02 19:09:31 -07:00
David Anderson
771eb05bcb tstest/natlab: first network attached becomes the default route.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-07-03 01:03:05 +00:00
David Anderson
f2e5da916a tstest/natlab: allow sensible default construction of networks.
Add a test for LAN->LAN traffic.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-07-03 00:53:24 +00:00
David Anderson
9cd4e65191 smallzstd: new package that constructs zstd small encoders/decoders.
It's just a config wrapper that passes "use less memory at the
expense of compression" parameters by default, so that we don't
accidentally construct resource-hungry (de)compressors.

Also includes a benchmark that measures the memory cost of the
small variants vs. the stock variants. The savings are significant
on both compressors (~8x less memory) and decompressors (~1.4x less,
not including the savings from the significantly smaller
window on the compression side - with those savings included it's
more like ~140x smaller).

BenchmarkSmallEncoder-8            	   56174	     19354 ns/op	      31 B/op	       0 allocs/op
BenchmarkSmallEncoderWithBuild-8   	    2900	    382940 ns/op	 1746547 B/op	      36 allocs/op
BenchmarkStockEncoder-8            	   48921	     25761 ns/op	     286 B/op	       0 allocs/op
BenchmarkStockEncoderWithBuild-8   	     426	   2630241 ns/op	13843842 B/op	     124 allocs/op
BenchmarkSmallDecoder-8            	  123814	      9344 ns/op	       0 B/op	       0 allocs/op
BenchmarkSmallDecoderWithBuild-8   	   41547	     27455 ns/op	   27694 B/op	      31 allocs/op
BenchmarkStockDecoder-8            	  129832	      9417 ns/op	       1 B/op	       0 allocs/op
BenchmarkStockDecoderWithBuild-8   	   25561	     51751 ns/op	   39607 B/op	      92 allocs/op

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-07-02 16:13:06 -07:00
Brad Fitzpatrick
97910ce712 tstest/natlab: remove unused PacketConner type 2020-07-02 14:50:04 -07:00
Brad Fitzpatrick
14b4213c17 tstest/natlab: add missing tests from earlier commits
Now you can actually see that packet delivery works.

Pairing with @danderson
2020-07-02 14:19:43 -07:00
Brad Fitzpatrick
3f4f1cfe66 tstest/natlab: basic NAT-free packet delivery works
Pairing with @danderson
2020-07-02 14:18:36 -07:00
Brad Fitzpatrick
a477e70632 tstest/natlab: network address allocation
Pairing with @danderson
2020-07-02 13:39:41 -07:00
Brad Fitzpatrick
bb1a9e4700 tstest/natlab: bit more of in-memory network testing package
Pairing with @danderson
2020-07-02 13:02:13 -07:00
Brad Fitzpatrick
23c93da942 tstest/natlab: start of in-memory network testing package
Pairing with @danderson
2020-07-02 12:36:12 -07:00
Brad Fitzpatrick
c52905abaa wgengine/magicsock: log less on no-op disco route switches
Also, renew trustBestAddrUntil even if latency isn't better.
2020-07-02 11:39:05 -07:00
Brad Fitzpatrick
847b6f039b disco: simplify expression, appease staticcheck
Was:
disco/disco.go:164:10: unnecessary use of fmt.Sprintf (S1039)
2020-07-02 10:52:23 -07:00
Brad Fitzpatrick
57e8931160 control/controlclient: fix copy/paste-o in debug knob accessor
Introduced in a975e86bb8.

Only affected TS_DEBUG_* env users.
2020-07-02 10:51:23 -07:00
Brad Fitzpatrick
0f0ed3dca0 wgengine/magicsock: clean up discovery logging
Updates #483
2020-07-02 10:48:13 -07:00
Brad Fitzpatrick
056fbee4ef wgengine/magicsock: add TS_DEBUG_OMIT_LOCAL_ADDRS knob to force STUN use only
For debugging.
2020-07-02 09:53:10 -07:00
Brad Fitzpatrick
6233fd7ac3 control/controlclient: don't truncate AuthURL in log
It's useful to copy/paste directly from there, without using tailscale up.
If it's truncated for some specific reason, it doesn't say why.
2020-07-02 09:45:08 -07:00
Brad Fitzpatrick
e03cc2ef57 wgengine/magicsock: populate discoOfAddr upon receiving ping frames
Updates #483
2020-07-02 08:37:46 -07:00
Brad Fitzpatrick
275a20f817 wgengine/magicsock: keep discoOfAddr populated, use it for findEndpoint
Update the mapping from ip:port to discokey, so when we retrieve a
packet from the network, we can find the same conn.Endpoint that we
gave to wireguard-go previously, without making it think we've
roamed. (We did, but we're not using its roaming.)

Updates #483
2020-07-01 22:15:41 -07:00
Brad Fitzpatrick
77e89c4a72 wgengine/magicsock: handle CallMeMaybe discovery mesages
Roughly feature complete now. Testing and polish remains.

Updates #483
2020-07-01 15:30:25 -07:00
Brad Fitzpatrick
710ee88e94 wgengine/magicsock: add timeout on discovery pings, clean up state
Updates #483
2020-07-01 14:39:21 -07:00
Brad Fitzpatrick
77d3ef36f4 wgengine/magicsock: hook up discovery messages, upgrade to LAN works
Ping messages now go out somewhat regularly, pong replies are sent,
and pong replies are now partially handled enough to upgrade off DERP
to LAN.

CallMeMaybe packets are sent & received over DERP, but aren't yet
handled. That's next (and regular maintenance timers), and then WAN
should work.

Updates #483
2020-07-01 13:00:50 -07:00
Brad Fitzpatrick
9b8ca219a1 wgengine/magicsock: remove allocs in UDP write, use new netaddr.PutUDPAddr
The allocs were only introduced yesterday with a TODO. Now they're gone again.
2020-07-01 10:17:08 -07:00
Brad Fitzpatrick
7b3c0bb7f6 wgengine/magicsock: fix crash reading DERP packet
Starting at yesterday's e96f22e560 (convering some UDPAddrs to
IPPorts), Conn.ReceiveIPv4 could return a nil addr, which would make
its way through wireguard-go and blow up later. The DERP read path
wasn't initializing the addr result parameter any more, and wgRecvAddr
wasn't checking it either.

Fixes #515
2020-07-01 09:36:19 -07:00
Brad Fitzpatrick
47b4a19786 wgengine/magicsock: use netaddr.ParseIPPort instead of net.ResolveUDPAddr 2020-07-01 08:23:37 -07:00
Brad Fitzpatrick
f7124c7f06 wgengine/magicsock: start of discoEndpoint state tracking
Updates #483
2020-06-30 15:33:56 -07:00
Brad Fitzpatrick
92252b0988 wgengine/magicsock: add a little LRU cache for netaddr.IPPort lookups
And while plumbing, a bit of discovery work I'll need: the
endpointOfAddr map to map from validated paths to the discoEndpoint.
Not being populated yet.

Updates #483
2020-06-30 14:38:10 -07:00
Brad Fitzpatrick
2d6e84e19e net/netcheck, wgengine/magicsock: replace more UDPAddr with netaddr.IPPort 2020-06-30 13:25:13 -07:00
Brad Fitzpatrick
9070aacdee wgengine/magicsock: minor comments & logging & TODO changes 2020-06-30 13:14:41 -07:00
Brad Fitzpatrick
e96f22e560 wgengine/magicsock: start handling disco message, use netaddr.IPPort more
Updates #483
2020-06-30 12:24:23 -07:00
Brad Fitzpatrick
790ef2bc5f internal/deepprint: update copyright header to appease license checker script
Plus mention that it's not an exact copy.
2020-06-29 22:22:44 -07:00
Brad Fitzpatrick
eb4eb34f37 disco: new package for parsing & marshaling discovery messages
Updates #483
2020-06-29 21:54:34 -07:00
Brad Fitzpatrick
7ca911a5c6 internal/deepprint: add missing copyright headers 2020-06-29 19:36:47 -07:00
Brad Fitzpatrick
a83ca9e734 wgengine/magicsock: cache precomputed nacl/box shared keys
Updates #483
2020-06-29 14:26:25 -07:00
Brad Fitzpatrick
a975e86bb8 wgengine/magicsock: add new endpoint type used for discovery-supporting peers
This adds a new magicsock endpoint type only used when both sides
support discovery (that is, are advertising a discovery
key). Otherwise the old code is used.

So far the new code only communicates over DERP as proof that the new
code paths are wired up. None of the actually discovery messaging is
implemented yet.

Support for discovery (generating and advertising a key) are still
behind an environment variable for now.

Updates #483
2020-06-29 13:59:54 -07:00
Brad Fitzpatrick
72bfea2ece control/controlclient: remove IPv6 opt-out environment variable
It was temporary and 3 months has elapsed without problems.
2020-06-29 09:03:00 -07:00
Brad Fitzpatrick
6f73f2c15a wgengine, internal/deepprint: replace UAPI usage as hash func; add deepprint
The new deepprint package just walks a Go data structure and writes to
an io.Writer. It's not pretty like go-spew, etc.

We then use it to replace the use of UAPI (which we have a TODO to
remove) to generate signatures of data structures to detect whether
anything changed (without retaining the old copy).

This was necessary because the UAPI conversion ends up trying to do
DNS lookups which an upcoming change depends on not happening.
2020-06-28 10:59:58 -07:00
Brad Fitzpatrick
103c06cc68 wgengine/magicsock: open discovery naclbox messages from known peers
And track known peers.

Doesn't yet do anything with the messages. (nor does it send any yet)

Start of docs on the message format. More will come in subsequent changes.

Updates #483
2020-06-26 14:57:12 -07:00
David Crawshaw
9258d64261 wgengine/router: do not call ifconfig up if SetRoutesFunc is set
The NetworkExtension brings up the interface itself and does not have
access to `ifconfig`, which the underlying BSD userspace router attempts
to use when Up is called.

Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-06-26 09:45:28 -07:00
Brad Fitzpatrick
23e74a0f7a wgengine, magicsock, tstun: don't regularly STUN when idle (mobile only for now)
If there's been 5 minutes of inactivity, stop doing STUN lookups. That
means NAT mappings will expire, but they can resume later when there's
activity again.

We'll do this for all platforms later.

Updates tailscale/corp#320

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-06-25 19:14:24 -07:00
Brad Fitzpatrick
fe50cd0c48 ipn, wgengine: plumb NetworkMap down to magicsock
Now we can have magicsock make decisions based on tailcfg.Debug
settings sent by the server.

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-06-25 19:14:24 -07:00
Brad Fitzpatrick
b8edb7a5e9 control/controlclient: add Debug field to NetworkMap
As part of disabling background STUN packets when idle, we want an
emergency override switch to turn it back on, in case it interacts
poorly in the wild. We'll send that via control, but we'll want to
plumb it down to magicsock via NetworkMap.

Updates tailscale/corp#320

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-06-25 19:14:24 -07:00
Brad Fitzpatrick
0071888a17 types/opt: add Bool.EqualBool method
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-06-25 19:14:24 -07:00
Brad Fitzpatrick
4732722b87 derp: add frameClosePeer to move around clients within a region
For various reasons (mostly during rollouts or config changes on our
side), nodes may end up connecting to a fallback DERP node in a
region, rather than the primary one we tell them about in the DERP
map.

Connecting to the "wrong" node is fine, but it's in our best interest
for all nodes in a domain to connect to the same node, to reduce
intra-region packet forwarding.

This adds a privileged frame type used by the control system that can
kick off a client connection when they're connected to the wrong node
in a region. Then they hopefully reconnect immediately to the correct
location. (If not, we can leave them alone and stop closing them.)

Updates tailscale/corp#372
2020-06-25 09:33:10 -07:00
Brad Fitzpatrick
dd43d9bc5f derp: fix varz typo
Updates tailscale/corp#391
2020-06-25 08:43:28 -07:00
Brad Fitzpatrick
3553512a71 cmd/derper: fix embarassing bug introduced in earlier refactor
The remove hook implementation was copy/pasted from the line above and
I didn't change the body, resulting in packet forwarding routes never
being removed.

Fortunately we weren't using this path yet, but it led to stats being
off, and (very) slow memory growth.
2020-06-24 19:45:27 -07:00
Brad Fitzpatrick
36e9cb948f control/controlclient: cut down some NetworkMap stringification & diff allocations
And start of tests.
2020-06-24 15:00:02 -07:00
Brad Fitzpatrick
894e3bfc96 control/controlclient: trim /32 suffix a bit more succinctly 2020-06-24 14:24:32 -07:00
Brad Fitzpatrick
19d95e095a wgengine: fix blank line in interface method comment 2020-06-24 14:10:42 -07:00
Brad Fitzpatrick
5bc29e7388 ipn: add missing locking in LocalBackend.NetMap
Looks like it's only used by tests.
2020-06-24 13:55:56 -07:00
Brian Chu
2a8e064705 cmd/tailscale: Allow advertising subnet routes on *BSD.
Use sysctl to check IP forwarding state for better OS compatiblity.

Signed-off-by: Brian Chu <cynix@cynix.org>
2020-06-24 09:48:43 -07:00
Reinaldo de Souza
a8635784bc wgengine: add BSD userspace router to darwin
Darwin and FreeBSD are compatible enough to share the userspace router.

The OSX router delegates to the BSD userspace router unless `SetRoutesFunc` is set.
That preserves the mechanism that allows `ipn-go-bridge` to specify its own routing behavior.

Fixes #177

Signed-off-by: Reinaldo de Souza <github@rei.nal.do>
2020-06-24 09:42:20 -07:00
Brad Fitzpatrick
b87396b5d9 cmd/derper, derp: add some more varz and consistency check handler
I'm trying to hunt down a slow drift in numbers not agreeing.
2020-06-23 14:01:51 -07:00
Elias Naur
c2682553ff version: add support for setting version with the -X Go linker flag
Updates tailscale/tailscale#486

Signed-off-by: Elias Naur <mail@eliasnaur.com>
2020-06-22 12:59:38 -07:00
Brad Fitzpatrick
6fbd1abcd3 derp: update peerGone code to work with regional DERP mesh clusters too
Updates #150
Updates #388
2020-06-22 10:06:42 -07:00
Dmytro Shynkevych
de5f6d70a8 magicsock: eliminate logging race in test
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-06-22 11:06:12 -04:00
Brad Fitzpatrick
666d404066 ipn: put discovery key generation behind an environment flag for now
Later we'll want to use the presence of a discovery key as a signal
that the node knows how to participate in discovery. Currently the
code generates keys and sends them to the control server but doesn't
do anything with them, which is a bad state to stay in lest we release
this code and end up with nodes in the future that look like they're
functional with the new discovery protocol but aren't.

So for now, make this opt-in as a debug option for now, until the rest
of it is in.

Updates #483
2020-06-20 10:18:13 -07:00
Dmytro Shynkevych
00ca17edf4 ipn: fix race in enterState
Signed-Off-By: Dmytro Shynkevych <dmytro@tailscale.com>
2020-06-19 13:42:05 -07:00
Brad Fitzpatrick
53fb25fc2f all: generate discovery key, plumb it around
Not actually used yet.

Updates #483
2020-06-19 12:12:00 -07:00
Brad Fitzpatrick
88c305c8af tailcfg: add DiscoKey, unify some code, add some tests
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-06-19 09:22:34 -07:00
Brad Fitzpatrick
d9054da86a wgengine: disambiguate Reconfig logging paths 2020-06-18 22:07:20 -07:00
David Anderson
0ecaf7b5ed control/controlclient: make netmap generation use rate-limited logger. 2020-06-18 23:24:44 +00:00
David Anderson
401e2ec307 control/controlclient: delete unused function. 2020-06-18 23:20:01 +00:00
Brad Fitzpatrick
58c9591a49 version: bump date 2020-06-18 09:10:50 -07:00
David Anderson
10368ef4c0 go.mod: bump wireguard-go version. 2020-06-17 02:54:18 +00:00
Dmytro Shynkevych
c12d87c54b Fix concurrency issues in controlclient, ipn, types/logger (#456)
Signed-Off-By: Dmytro Shynkevych <dmytro@tailscale.com>
2020-06-15 19:04:12 -04:00
Brad Fitzpatrick
c8cf3169ba cmd/derper, derp/derphttp: move bulk of derp mesh code into derphttp
To be reused in various other tools.
2020-06-15 11:58:10 -07:00
Brad Fitzpatrick
7cbf6ab771 cmd/derper: remove unused parameter in runMeshClient 2020-06-15 11:35:50 -07:00
Avery Pennarun
5d4415399b Merge remote-tracking branch 'origin/master' into main
* origin/master:
  Fix staticcheck warning, add Makefile with staticcheck targets, lock in staticcheck version in go.mod
2020-06-15 14:23:19 -04:00
Brad Fitzpatrick
6757c990a8 Fix staticcheck warning, add Makefile with staticcheck targets, lock in staticcheck version in go.mod 2020-06-15 11:05:46 -07:00
Brad Fitzpatrick
08a6eeb55a Fix staticcheck warning, add Makefile with staticcheck targets, lock in staticcheck version in go.mod 2020-06-15 11:04:19 -07:00
Avery Pennarun
d9fd5db1e1 Rename master -> main.
Background:
https://www.zdnet.com/article/github-to-replace-master-with-alternative-term-to-avoid-slavery-references/
2020-06-15 13:47:11 -04:00
Brad Fitzpatrick
abd79ea368 derp: reduce DERP memory use; don't require callers to pass in memory to use
The magicsock derpReader was holding onto 65KB for each DERP
connection forever, just in case.

Make the derp{,http}.Client be in charge of memory instead. It can
reuse its bufio.Reader buffer space.
2020-06-15 10:26:50 -07:00
Quoc-Viet Nguyen
15a23ce65f net/stun: Remove unreachable code
- Reuse IP length constants from net package.
- Remove beu16 to make endianness functions consistent.

Signed-off-by: Quoc-Viet Nguyen <afelion@gmail.com>
2020-06-15 07:55:21 -07:00
Brad Fitzpatrick
a036c8c718 version: add blank line to separate comment from package line
So it's not a package comment.
2020-06-15 07:50:51 -07:00
David Anderson
0371848097 Revert "version: delete GENERATE.go."
This reverts commit a447caebf8.
2020-06-12 23:32:22 +00:00
David Anderson
4c23b5e4ea version: remove leftover debug print.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-06-12 22:38:12 +00:00
David Anderson
03aa319762 version: add an AtLeast helper to compare versions.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-06-12 14:28:21 -07:00
David Anderson
9dd3544e84 version: bump oss datestamp.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-06-12 18:49:55 +00:00
David Anderson
1f4ccae591 version: remove comment about being unused.
version.SHORT is now being used in various places.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-06-12 18:46:17 +00:00
David Anderson
a447caebf8 version: delete GENERATE.go.
It existed previously to persuade Go that redo-ful directory was
a Go package prior to the first build. But now we have other Go
files in the directory that will fulfil that function.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-06-12 18:37:10 +00:00
Brad Fitzpatrick
50b2e5ffe6 log/logheap: appease staticcheck 2020-06-12 10:31:42 -07:00
Brad Fitzpatrick
8edcab04d5 log/logheap: change to POST to a URL instead of logging
It's too big to log.
2020-06-12 10:13:08 -07:00
Brad Fitzpatrick
51f421946f tailcfg: add some example strings in comments 2020-06-12 08:17:31 -07:00
Brad Fitzpatrick
deb113838e net/netcheck: use logger.ArgWriter in logConciseReport, fix comma bug, add tests 2020-06-11 21:37:15 -07:00
Brad Fitzpatrick
280e8884dd wgengine/magicsock: limit redundant log spam on packets from low-pri addresses
Fixes #407

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-06-11 09:40:55 -07:00
David Anderson
d05b0500ac wgengine: loop back tuntap packets destined for local IPs.
macOS incorrectly sends packets for the local Tailscale IP
into our tunnel interface. We have to turn the packets around
and send them back to the kernel.

Fixes tailscale/corp#189.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-06-09 18:55:57 -07:00
Zijie Lu
d1a30be275 tsweb: JSONHandler: supports HTTPError
Signed-off-by: Zijie Lu <zijie@tailscale.com>
2020-06-09 17:40:45 -04:00
Avery Pennarun
51d176ecff wgengine: Remove leftover debug message.
Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-06-09 17:03:52 -04:00
Dmytro Shynkevych
07e02ec9d3 wgengine/tsdns: add test and prevent useless updates (#449)
Signed-Off-By: Dmytro Shynkevych <dmytro@tailscale.com>
2020-06-09 13:09:43 -04:00
Dmytro Shynkevych
511840b1f6 tsdns: initial implementation of a Tailscale DNS resolver (#396)
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-06-08 18:19:26 -04:00
Zijie Lu
5e1ee4be53 tsweb: fix JSONHandler nil response
Signed-off-by: Zijie Lu <zijie@tailscale.com>
2020-06-08 15:48:38 -04:00
Brad Fitzpatrick
c3f7733f53 logpolicy: don't check version.CmdName on Windows unnecessarily
... it was crashing for some reason, running out of stack while
loading a DLL in goversion. I don't understand Windows (or the Go
runtime for Windows) enough to know why that'd be problematic in that
context.

In any case, don't call it, as tryFixLogStateLocation does nothing on
Windows anyway.

tryFixLogStateLocation should probably just call version.CmdName
itself if/when it needs to, after the GOOS check.
2020-06-08 10:32:34 -07:00
Brad Fitzpatrick
5c9ddf5e76 version: fix typo in comment 2020-06-08 10:30:16 -07:00
Brad Fitzpatrick
2ca2389c5f portlist: set SysProcAttr.HideWindow on Windows
Prevents annoying shell window flashes when running /server by hand.
2020-06-08 09:04:31 -07:00
Brad Fitzpatrick
07ca0c1c29 derp: fix tracking problem if conn starts local, then also joins mesh peer 2020-06-05 12:53:43 -07:00
Brad Fitzpatrick
39f2fe29f7 tempfork/registry: work around issue with Tailscale's redo build system
Updates tailscale/corp#293
2020-06-05 10:46:15 -07:00
Brad Fitzpatrick
1cb7dab881 cmd/derper: support forwarding packets amongst set of peer DERP servers
Updates #388

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-06-05 10:14:33 -07:00
Brad Fitzpatrick
e441d3218e tempfork/registry: add golang.org/x/sys/windows/registry + CL 236681
Temporary fork of golang.org/x/sys/windows/registry with:

   windows/registry: add Key.WaitChange wrapper around RegNotifyChangeKeyValue
   https://go-review.googlesource.com/c/sys/+/236681
2020-06-05 09:45:16 -07:00
Dmytro Shynkevych
02231e968e wgengine/tstun: add tests and benchmarks (#436)
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-06-05 11:19:03 -04:00
Avery Pennarun
6f590f5b52 logtail: we missed a case for the backoff timer.
We want to run bo.Backoff() after every upload, regardless. If
upload==true but err!=nil, we weren't backing off, which caused some
very-high-throughput log upload retries in bad network conditions.

Updates #282.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-06-05 03:55:45 -04:00
halulu
1d2e497d47 tsweb: JSONHandler using reflect (#437)
Updates #395 #437

Signed-off-by: Zijie Lu <zijie@tailscale.com>
2020-06-05 00:10:50 -04:00
Dmytro Shynkevych
059b1d10bb wgengine/packet: refactor and expose UDP header marshaling (#408)
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-06-04 18:42:44 -04:00
Brad Fitzpatrick
5e0ff494a5 derp: change NewClient constructor to an option pattern
(The NewMeshClient constructor I added recently was gross in
retrospect at call sites, especially when it wasn't obvious that a
meshKey empty string meant a regular client)
2020-06-04 11:40:12 -07:00
Brad Fitzpatrick
4d599d194f derp, derp/derphttp: add key accessors, add Client.RecvDetail
Client.RecvDetail returns a connection generation so interested clients
can detect when a reconnect happened. (Will be needed for #388)
2020-06-04 11:35:53 -07:00
Brad Fitzpatrick
b33c86b542 derp: add an unexported key.Public zero value variable to be less verbose 2020-06-04 11:28:00 -07:00
Brad Fitzpatrick
b663ab4685 cmd/derper: treat self-connection connection watch as no-op
Updates #388
2020-06-04 08:26:05 -07:00
Brad Fitzpatrick
5798826990 cmd/derper: add /home/bradfitz/keys to default mesh key search list 2020-06-04 08:19:44 -07:00
David Anderson
e01a4c50ba go.mod: require Go 1.14, since we use some of its features.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-06-03 17:53:48 -07:00
David Anderson
5a32f8e181 wgengine/router: also accept exit code 254 from ip rule del.
iproute2 3.16.0-2 from Debian Jessie (oldoldstable) doesn't return
exit code 2 when deleting a non-existent IP rule.

Fixes #434

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-06-03 13:46:31 -07:00
Brad Fitzpatrick
484b7fc9a3 derp, cmd/derper: add frameWatchConns, framePeerPresent for inter-DERP routing
This lets a trusted DERP client that knows a pre-shared key subscribe
to the connection list. Upon subscribing, they get the current set
of connected public keys, and then all changes over time.

This lets a set of DERP server peers within a region all stay connected to
each other and know which clients are connected to which nodes.

Updates #388

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-06-03 08:03:29 -07:00
David Anderson
c62b80e00b cmd/tailscale: fix inverted flag meanings.
The flags were --no-blah for a brief time, then we switched them to
--blah=true/false with a default of true, but didn't fix the boolean
inversions in the code. So up was down, true was false, etc.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-06-03 05:43:51 +00:00
David Anderson
cc687fc3e6 version: always include the long form version in describe.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-06-03 05:42:46 +00:00
David Anderson
08a38f21c9 wgengine/router: don't filter subnet routing in netfilter.
We have a filter in tailscaled itself now, which is more robust
against weird network topologies (such as the one Docker creates).

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-06-02 20:52:06 -07:00
David Anderson
c71754eba2 ipn/ipnserver: revert decoder memory limit.
The zstd library treats that limit as a hard cap on decompressed
size, in the mode we're using it, rather than a window size.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-06-03 02:41:49 +00:00
David Anderson
d4127db0fe logpolicy: add a temporary fixup for #247.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-06-02 15:56:25 -07:00
David Anderson
0dac03876a logpolicy: don't put log state in /.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-06-02 15:56:25 -07:00
Elias Naur
364a8508b2 ipn: add Hostname override to Prefs
Overriding the hostname is required for Android, where os.Hostname
is often just "localhost".

Updates #409

Signed-off-by: Elias Naur <mail@eliasnaur.com>
2020-06-02 21:40:27 +02:00
Dmytro Shynkevych
73c40c77b0 filter: prevent escape of QDecode to the heap (#417)
Performance impact:

name              old time/op  new time/op  delta
Filter/tcp_in-4   70.7ns ± 1%  30.9ns ± 1%  -56.30%  (p=0.008 n=5+5)
Filter/tcp_out-4  58.6ns ± 0%  19.4ns ± 0%  -66.87%  (p=0.000 n=5+4)
Filter/udp_in-4   96.8ns ± 2%  55.5ns ± 0%  -42.64%  (p=0.016 n=5+4)
Filter/udp_out-4   120ns ± 1%    79ns ± 1%  -33.87%  (p=0.008 n=5+5)

Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-06-02 08:09:20 -04:00
David Anderson
83b6b06cc4 cmd/tailscale: fix broken build, result of borked stash pop. 2020-06-02 04:27:28 +00:00
David Anderson
3c7791f6bf cmd/tailscale: remove double negation arguments.
--no-snat becomes --snat-subnet-routes
--no-single-routes becomes --host-routes

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-06-02 04:23:15 +00:00
David Anderson
5aae6b734d version: support major.minor.patch tags without breaking Apple builds.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-06-01 18:14:27 -07:00
Brad Fitzpatrick
984a699219 cmd/tailscale: warn to stderr that netcheck -format=json isn't stable 2020-06-01 11:15:58 -07:00
Brad Fitzpatrick
24009241bf net/netns: move SOCKS dialing to netns for now
This lets control & logs also use SOCKS dials.

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-06-01 11:00:03 -07:00
Brad Fitzpatrick
cf0d19f0ab net/tlsdial, derp/derphttp: finish DERPNode.CertName validation 2020-06-01 09:01:37 -07:00
Brad Fitzpatrick
722673f307 Update go4.org/mem, adjust to revised API. 2020-05-31 20:22:46 -07:00
Brad Fitzpatrick
a5d6c9d616 net/netns: optimize defaultRouteInterface a bit
It'll be called a bunch, so worth a bit of effort. Could go further, but not yet.
(really, should hook into wgengine/monitor and only re-read on netlink changes?)

name                     old time/op    new time/op    delta
DefaultRouteInterface-8    60.8µs ±11%    44.6µs ± 5%  -26.65%  (p=0.000 n=20+19)

name                     old alloc/op   new alloc/op   delta
DefaultRouteInterface-8    3.29kB ± 0%    0.55kB ± 0%  -83.21%  (p=0.000 n=20+20)

name                     old allocs/op  new allocs/op  delta
DefaultRouteInterface-8      9.00 ± 0%      6.00 ± 0%  -33.33%  (p=0.000 n=20+20)
2020-05-31 15:37:09 -07:00
Brad Fitzpatrick
9e5d79e2f1 wgengine/magicsock: drop a bytes.Buffer sync.Pool, use logger.ArgWriter instead 2020-05-31 15:29:04 -07:00
Brad Fitzpatrick
becce82246 net/netns, misc tests: remove TestOnlySkipPrivilegedOps, argv checks
The netns UID check is sufficient for now. We can do something else
later if/when needed.
2020-05-31 14:40:18 -07:00
Brad Fitzpatrick
7a410f9236 net/netns: unindent, refactor to remove some redunant code
Also:
* always error on Control failing. That's very unexpected.
* pull out sockopt funcs into their own funcs for easier future testing
2020-05-31 14:29:54 -07:00
Brad Fitzpatrick
45b139d338 net/netns: remove redundant build tag
Filename is sufficient.
2020-05-31 14:05:54 -07:00
Brad Fitzpatrick
dcd7a118d3 net/netns: add a test that tailscaleBypassMark stays in sync between packages 2020-05-31 14:02:13 -07:00
Brad Fitzpatrick
1e837b8e81 net/netns: refactor the sync.Once usage a bit 2020-05-31 14:01:20 -07:00
Avery Pennarun
e7ae6a2e06 net/netns, wgengine/router: support Linux machines that don't have 'ip rule'.
We'll use SO_BINDTODEVICE instead of fancy policy routing. This has
some limitations: for example, we will route all traffic through the
interface that has the main "default" (0.0.0.0/0) route, so machines
that have multiple physical interfaces might have to go through DERP to
get to some peers. But machines with multiple physical interfaces are
very likely to have policy routing (ip rule) support anyway.

So far, the only OS I know of that needs this feature is ChromeOS
(crostini). Fixes #245.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-31 04:31:01 -04:00
Avery Pennarun
8575b21ca8 Merge branch 'master' of github.com:tailscale/tailscale
* 'master' of github.com:tailscale/tailscale:
  tailcfg: remove unused, unimplemented DERPNode.CertFingerprint for now
  net/netns: also don't err on tailscaled -fake as a regular user
  net/netcheck: fix HTTPS fallback bug from earlier today
  net/netns: don't return an error if we're not root and running the tailscale binary
2020-05-31 03:05:51 -04:00
Avery Pennarun
e46238a2af wgengine: separately dedupe wireguard configs and router configs.
Otherwise iOS/macOS will reconfigure their routing every time anything
minor changes in the netmap (in particular, endpoints and DERP homes),
which is way too often.

Some users reported "network reconfigured" errors from Chrome when this
happens.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-31 02:37:58 -04:00
Avery Pennarun
f0b6ba78e8 wgengine: don't pass nil router.Config objects.
These are hard for swift to decode in the iOS app.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-31 02:37:22 -04:00
Brad Fitzpatrick
096d7a50ff tailcfg: remove unused, unimplemented DERPNode.CertFingerprint for now 2020-05-30 20:44:18 -07:00
Brad Fitzpatrick
765695eaa2 net/netns: also don't err on tailscaled -fake as a regular user
That's one of my dev workflows.
2020-05-29 22:40:26 -07:00
Brad Fitzpatrick
7f68e097dd net/netcheck: fix HTTPS fallback bug from earlier today
My earlier 3fa58303d0 tried to implement
the net/http.Tranhsport.DialTLSContext hook, but I didn't return a
*tls.Conn, so we ended up sending a plaintext HTTP request to an HTTPS
port. The response ended up being Go telling as such, not the
/derp/latency-check handler's response (which is currently still a
404). But we didn't even get the 404.

This happened to work well enough because Go's built-in error response
was still a valid HTTP response that we can measure for timing
purposes, but it's not a great answer. Notably, it means we wouldn't
be able to get a future handler to run server-side and count those
latency requests.
2020-05-29 22:33:08 -07:00
Brad Fitzpatrick
1407540b52 net/netns: don't return an error if we're not root and running the tailscale binary
tailscale netcheck was broken otherwise.

We can fix this a better way later; I'm just fixing a regression in
some way because I'm trying to work on netcheck at the moment.
2020-05-29 21:58:31 -07:00
David Anderson
5114df415e net/netns: set the bypass socket mark on linux.
This allows tailscaled's own traffic to bypass Tailscale-managed routes,
so that things like tailscale-provided default routes don't break
tailscaled itself.

Progress on #144.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-29 15:16:58 -07:00
Brad Fitzpatrick
3fa58303d0 netcheck: address some HTTP fallback measurement TODOs 2020-05-29 13:34:09 -07:00
Brad Fitzpatrick
db2a216561 wgengine/magicsock: don't log on UDP send errors if address family known missing
Fixes #376
2020-05-29 12:41:30 -07:00
Brad Fitzpatrick
d3134ad0c8 syncs: add AtomicBool 2020-05-29 12:41:30 -07:00
Brad Fitzpatrick
7247e896b5 net/netcheck: add Report.IPv4 and another TODO 2020-05-29 12:41:30 -07:00
Brad Fitzpatrick
dd6b96ba68 types/logger: add TS_DEBUG_LOG_RATE knob to easily turn off rate limiting 2020-05-29 12:41:29 -07:00
David Crawshaw
cf5d25e15b wgengine: ensure pingers are gone before returning from Close
We canceled the pingers in Close, but didn't wait around for their
goroutines to be cleaned up. This caused the ipn/e2e_test to catch
pingers in its resource leak check.

This commit introduces an object, but also simplifies the semantics
around the pinger's cancel functions. They no longer need to be called
while holding the mutex.

Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-05-30 05:30:26 +10:00
Brad Fitzpatrick
004780b312 ipn: restore LiveDERPs assignment in LocalBackend.parseWgStatus
Updates #421 (likely fixes it; need to do an iOS build to be sure)
2020-05-29 09:53:04 -07:00
David Anderson
03682cb271 control/controlclient: use netns package to dial connections.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-29 00:06:08 +00:00
David Anderson
1617a232e1 logpolicy: remove deprecated DualStack directive.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-29 00:04:28 +00:00
David Anderson
a6bd3a7e53 logpolicy: use netns for dialing log.tailscale.io. 2020-05-28 23:53:19 +00:00
David Anderson
e9f7d01b91 derp/derphttp: make DERP client use netns for dial-outs. 2020-05-28 23:48:08 +00:00
Brad Fitzpatrick
9e3ad4f79f net/netns: add package for start of network namespace support
And plumb in netcheck STUN packets.

TODO: derphttp, logs, control.

Updates #144

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-05-28 16:20:16 -07:00
Brad Fitzpatrick
a428656280 wgengine/magicsock: don't report v4 localhost addresses on IPv6-only systems
Updates #376
2020-05-28 14:16:23 -07:00
David Anderson
fff062b461 wgengine/router: make runner.go linux-only for now.
Otherwise, staticcheck complains that these functions are unused
and unexported on macOS.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-28 12:19:01 -07:00
Brad Fitzpatrick
f0204098d8 Revert "control/controlclient: use "getprop net.hostname" for Android hostname"
This reverts commit afb9c6a6ab.

Doesn't work. See:

    https://github.com/tailscale/tailscale/issues/409#issuecomment-635241550

Looks pretty dire:

    https://medium.com/capital-one-tech/how-to-get-an-android-device-nickname-d5eab12f4ced

Updates #409
2020-05-28 10:50:11 -07:00
Brad Fitzpatrick
0245bbe97b Make netcheck handle v6-only interfaces better, faster.
Also:

* add -verbose flag to cmd/tailscale netcheck
* remove some API from the interfaces package
* convert some of the interfaces package to netaddr.IP
* don't even send IPv4 probes on machines with no IPv4 (or only v4
  loopback)
* and once three regions have replied, stop waiting for other probes
  at 2x the slowest duration.

Updates #376
2020-05-28 10:04:20 -07:00
Brad Fitzpatrick
c5495288a6 Bump inet.af/netaddr dep for FromStdIP behavior change I want to depend on. 2020-05-28 09:34:41 -07:00
Brad Fitzpatrick
9bbcdba2b3 tempfork/internal/testenv: remove
It was for our x509 fork and no longer needed. (x509 changes
went into our Go fork instead)
2020-05-28 09:34:22 -07:00
Brad Fitzpatrick
a96165679c cmd/tailscale: add netcheck flags for incremental reports, JSON output 2020-05-28 08:28:04 -07:00
Avery Pennarun
f69003fd46 router_linux: work around terrible bugs in old iptables-compat versions.
Specifically, this sequence:
	iptables -N ts-forward
	iptables -A ts-forward -m mark --mark 0x10000 -j ACCEPT
	iptables -A FORWARD -j ts-forward
doesn't work on Debian-9-using-nftables, but this sequence:
	iptables -N ts-forward
	iptables -A FORWARD -j ts-forward
	iptables -A ts-forward -m mark --mark 0x10000 -j ACCEPT
does work.

I'm sure the reason why is totally fascinating, but it's an old version
of iptables and the bug doesn't seem to exist on modern nftables, so
let's refactor our code to add rules in the always-safe order and
pretend this never happened.

Fixes #401.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-28 07:15:06 -04:00
Avery Pennarun
9ff51909a3 router_linux: fix behaviour when switching --netfilter-mode.
On startup, and when switching into =off and =nodivert, we were
deleting netfilter rules even if we weren't the ones that added them.

In order to avoid interfering with rules added by the sysadmin, we have
to be sure to delete rules only in the case that we added them in the
first place.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-28 07:15:05 -04:00
Avery Pennarun
a496cdc943 router_linux: remove need for iptables.ListChains().
Instead of retrieving the list of chains, or the list of rules in a
chain, just try deleting the ones we don't want and then adding the
ones we do want. An error in flushing/deleting still means the rule
doesn't exist anymore, so there was no need to check for it first.

This avoids the need to parse iptables output, which avoids the need to
ever call iptables -S, which fixes #403, among other things. It's also
much more future proof in case the iptables command line changes.

Unfortunately the iptables go module doesn't properly pass the iptables
command exit code back up when doing .Delete(), so we can't correctly
check the exit code there. (exit code 1 really means the rule didn't
exist, rather than some other weird problem).

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-28 07:15:05 -04:00
Avery Pennarun
8a6bd21baf router_linux: extract process runner routines into runner.go.
These will probably be useful across platforms. They're not really
Linux-specific at all.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-28 07:15:05 -04:00
Avery Pennarun
34c30eaea0 router_linux: use only baseline 'ip rule' features that exist in old kernels.
This removes the use of suppress_ifgroup and fwmark "x/y" notation,
which are, among other things, not available in busybox and centos6.

We also use the return codes from the 'ip' program instead of trying to
parse its output.

I also had to remove the previous hack that routed all of 100.64.0.0/10
by default, because that would add the /10 route into the 'main' route
table instead of the new table 88, which is no good. It was a terrible
hack anyway; if we wanted to capture that route, we should have
captured it explicitly as a subnet route, not as part of the addr. Note
however that this change affects all platforms, so hopefully there
won't be any surprises elsewhere.

Fixes #405
Updates #320, #144

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-28 07:07:39 -04:00
Avery Pennarun
85d93fc4e3 cmd/tailscale: make ip_forward warnings more actionable.
Let's actually list the file we checked
(/proc/sys/net/ipv4/ip_forward). That gives the admin something
specific to look for when they get this message.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-28 07:07:39 -04:00
Avery Pennarun
99aa33469e cmd/tailscale: be quiet when no interaction or errors are needed.
We would print a message about "nothing more to do", which some people
thought was an error or warning. Let's only print a message after
authenticating if we previously asked for interaction, and let's
shorten that message to just "Success," which is what it means.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-28 07:07:39 -04:00
Avery Pennarun
30e5c19214 magicsock: work around race condition initializing .Regions[].
Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-28 03:42:03 -04:00
Avery Pennarun
7cd9ff3dde net/netcheck: fix race condition initializting RegionLatency maps.
Under some conditions, code would try to look things up in the maps
before the first call to updateLatency. I don't see any reason to delay
initialization of the maps, so let's just init them right away when
creating the Report instance.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-28 03:41:37 -04:00
Avery Pennarun
5eb09c8f5e filch_test: clarify the use of os.RemoveAll().
Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-27 18:50:44 -04:00
Brad Fitzpatrick
afb9c6a6ab control/controlclient: use "getprop net.hostname" for Android hostname
Updates #409
2020-05-27 12:50:41 -07:00
David Anderson
2b74236567 ipn: move e2e_test back to corp repo.
It depends on corp things, so can't run here anyway.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-27 19:23:36 +00:00
David Anderson
557b310e67 control/controlclient: move auto_test back to corp repo.
It can't run without corp stuff anyway, and makes it harder to
refactor the control server.
2020-05-27 19:08:21 +00:00
Dmytro Shynkevych
737124ef70 tstun: tolerate zero reads
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-05-27 14:32:09 -04:00
David Anderson
7317e73bf4 control/controlclient: move direct_test back to corp repo.
It can only be built with corp deps anyway, and having it split
from the control code makes our lives harder.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-27 17:00:23 +00:00
Dmytro Shynkevych
7508b67c54 cmd/tailscale: expose --enable-derp
Signed-off-by: Dmytro Shynkevych <dm.shynk@gmail.com>
2020-05-26 21:38:26 -04:00
Brad Fitzpatrick
703d789005 tailcfg: add MapResponse.Debug mechanism to trigger logging heap pprof
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-05-25 15:22:13 -07:00
Brad Fitzpatrick
b0c10fa610 stun, netcheck: move under net 2020-05-25 09:18:24 -07:00
Brad Fitzpatrick
43ded2b581 wgengine/packet: add some tests, more docs, minor Go style, performance changes 2020-05-25 08:58:10 -07:00
Brad Fitzpatrick
3f4a567032 types/strbuilder: add a variant of strings.Builder that uses sync.Pool
... and thus does not need to worry about when it escapes into
unprovable fmt interface{} land.

Also, add some convenience methods for efficiently writing integers.
2020-05-25 08:50:48 -07:00
Brad Fitzpatrick
e6b84f2159 all: make client use server-provided DERP map, add DERP region support
Instead of hard-coding the DERP map (except for cmd/tailscale netcheck
for now), get it from the control server at runtime.

And make the DERP map support multiple nodes per region with clients
picking the first one that's available. (The server will balance the
order presented to clients for load balancing)

This deletes the stunner package, merging it into the netcheck package
instead, to minimize all the config hooks that would've been
required.

Also fix some test flakes & races.

Fixes #387 (Don't hard-code the DERP map)
Updates #388 (Add DERP region support)
Fixes #399 (wgengine: flaky tests)

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-05-23 22:31:59 -07:00
David Anderson
e8b3a5e7a1 wgengine/filter: implement a destination IP pre-filter.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-22 17:03:30 +00:00
Brad Fitzpatrick
35a8586f7e go.sum: go mod tidy 2020-05-22 09:07:02 -07:00
Avery Pennarun
3ed2124356 ipn: Resolve some resource leaks in test.
Updates tailscale/corp#255.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-21 16:37:25 -04:00
Avery Pennarun
ea8f92b312 ipn/local: get rid of some straggling calls to the log module.
Use b.logf() instead.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-21 15:51:41 -04:00
Avery Pennarun
af9328c1b7 log rate limiting: reformat limiter messages, and use nonempty burst size.
- Reformat the warning about a message being rate limited to print the
  format string, rather than the formatted message. This helps give a
  clue what "type" of message is being limited.

- Change the rate limit warning to be [RATE LIMITED] in all caps. This
  uses less space on each line, plus is more noticeable.

- In tailscaled, change the frequency to be less often (once every 5
  seconds per format string) but to allow bursts of up to 5 messages.
  This greatly reduces the number of messages that are rate limited
  during startup, but allows us to tighten the limit even further during
  normal runtime.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-20 11:59:21 -04:00
Avery Pennarun
f2db4ac277 cmd/tailscaled: SetGCPercent() if GOGC is not set.
This cuts RSS from ~30MB to ~20MB on my machine, after the previous fix
to get rid of unnecessary zstd buffers.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-20 11:40:50 -04:00
Avery Pennarun
db051fb013 ipnserver and logpolicy: configure zstd with low-memory settings.
The compressed blobs we send back and forth are small and infrequent,
which doesn't justify the 8MB * GOMAXPROCS memory that was being
allocated. This was the overwhelming majority of memory use in
tailscaled. On my system it goes from ~100M RSS to ~15M RSS (which is
still suspiciously high, but we can worry about that more later).

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-20 11:23:26 -04:00
Avery Pennarun
d074ec6571 cmd/tailscaled: eliminate unnecessary use of an init() function.
Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-20 11:23:26 -04:00
Avery Pennarun
c5fcc38bf1 controlclient tests: fix more memory leaks and add resource checking.
I can now run these tests with -count=1000 without running out of RAM.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-20 11:23:26 -04:00
Avery Pennarun
d03de31404 controlclient/direct: fix a race condition accessing auth keys.
Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-19 03:02:09 -04:00
Avery Pennarun
1013cda799 controlclient/auto_test: don't print the s.control object.
This contains atomic ints that trigger a race check error if we access
them non-atomically.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-19 02:07:05 -04:00
Avery Pennarun
806de4ac94 portlist: fix "readdirent: no such file or directory" errors on Linux.
This could happen when a process disappeared while we were reading its
file descriptor list.

I was able to replicate the problem by running this in another
terminal:

    while :; do for i in $(seq 10); do
      /bin/true & done >&/dev/null; wait >&/dev/null;
    done

And then running the portlist tests thousands of times.

Fixes #339.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-19 01:51:21 -04:00
David Anderson
c97c45f268 ipn: sprinkle documentation and clarity rewrites through LocalBackend.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-19 02:32:34 +00:00
David Anderson
39d20e8a75 go.mod: bump wireguard-go version. 2020-05-18 21:03:48 +00:00
David Anderson
cd2f6679bb go.mod: bump wireguard-go version.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-15 22:29:27 +00:00
David Anderson
7fb33123d3 wgengine/router: warn about another variation of busybox's ip.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-15 20:48:25 +00:00
Wendi Yu
bb55694c95 wgengine: log node IDs when peers are added/removed (#381)
Also stop logging data sent/received from nodes we're not connected to (ie all those `x`s being logged in the `peers: ` line)
Signed-off-by: Wendi <wendi.yu@yahoo.ca>
2020-05-15 14:13:44 -06:00
Dmytro Shynkevych
635f7b99f1 wgengine: pass tun.NativeDevice to router
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-05-15 10:11:56 -04:00
David Anderson
9c914dc7dd wgengine/router: stop using -m comment.
The comment module is compiled out on several embedded systems (and
also gentoo, because netfilter can't go brrrr with comments holding it
back). Attempting to use comments results in a confusing error, and a
non-functional firewall.

Additionally, make the legacy rule cleanup non-fatal, because we *do*
have to probe for the existence of these -m comment rules, and doing
so will error out on these systems.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-15 07:09:33 +00:00
David Anderson
3e27b3c33c wgengine/router: more comments.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-14 23:51:44 -07:00
David Anderson
0fe262f093 ipn: plumb NetfilterMode all the way out to the CLI.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-14 23:51:44 -07:00
David Anderson
c67c8913c3 wgengine/router: add a test for linux router state transitions.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-14 23:51:44 -07:00
David Anderson
292606a975 wgengine/router: support multiple levels of netfilter involvement.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-14 23:51:44 -07:00
Brad Fitzpatrick
cff53c6e6d tailcfg: add DERP map structures
Updates #387
Updates #388

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-05-14 21:09:54 -07:00
Brad Fitzpatrick
5ec7ac1d02 tstest: document PanicOnLog 2020-05-14 10:05:32 -07:00
Brad Fitzpatrick
e6d0c92b1d wgengine/magicsock: clean up earlier fix a bit
Move WaitReady from fc88e34f42 into the
test code, and keep the derp-reading goroutine named for debugging.
2020-05-14 10:01:48 -07:00
Avery Pennarun
d0754760e7 controlclient/auto_test: fix flake "peer OS is not linux" on macOS.
We were mis-counting the number of Synchronized messages that we should
have been generating.
2020-05-14 06:31:19 -04:00
Avery Pennarun
8f8607b6bf control/controlclient/auto_test: clean up logging to defeat 'go test' idiocy.
By default, nothing differentiates errors or fatals from regular logs, so they just
blend into the rest of the logs.

As a bonus, if you run a test using t.Run(), the log messages printed
via the sub-t.Run() are printed at a different time from log messages
printed via the parent t.Run(), making debugging almost impossible.

This doesn't actually fix the test flake I'm looking for, but at least
I can find it in the logs now.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-14 06:31:09 -04:00
Avery Pennarun
d53e8fc0da router_darwin_support: we can build this on every platform.
Our new build scripts try to build ipn-go-bridge on more than just
linux and darwin, so let's enable this file so it can be successful on
every platform.
2020-05-14 04:42:36 -04:00
Avery Pennarun
3b1ce30967 Merge branch 'master' of github.com:tailscale/tailscale
* 'master' of github.com:tailscale/tailscale:
  derp/derphttp: don't use x/net/proxy for SOCKS on iOS
2020-05-14 02:56:49 -04:00
Avery Pennarun
286f96e412 control/controlclient: fix a very rare httptest.Server log.Printf.
Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-14 01:52:35 -04:00
Brad Fitzpatrick
040a0d5121 derp/derphttp: don't use x/net/proxy for SOCKS on iOS
We don't want those extra dependencies on iOS, at least yet.

Especially since there's no way to set the relevant environment
variables so it's just bloat with no benefits. Perhaps we'll need to
do SOCKS on iOS later, but probably differently if/when so.

Updates #227

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-05-13 22:35:17 -07:00
Avery Pennarun
fc88e34f42 wgengine/magicsock/tests: wait for home DERP connection before sending packets.
This fixes an elusive test flake. Fixes #161.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-13 23:50:25 -04:00
Avery Pennarun
4f128745d8 magicsock/test: oops, fix a data race in nested-test logf hack.
Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-13 23:50:09 -04:00
Avery Pennarun
42a0e0c601 wgengine/magicsock/tests: call tstest.ResourceCheck for each test.
This didn't catch anything yet, but it's good practice for detecting
goroutine leaks that we might not find otherwise.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-13 23:17:51 -04:00
Avery Pennarun
08acb502e5 Add tstest.PanicOnLog(), and fix various problems detected by this.
If a test calls log.Printf, 'go test' horrifyingly rearranges the
output to no longer be in chronological order, which makes debugging
virtually impossible. Let's stop that from happening by making
log.Printf panic if called from any module, no matter how deep, during
tests.

This required us to change the default error handler in at least one
http.Server, as well as plumbing a bunch of logf functions around,
especially in magicsock and wgengine, but also in logtail and backoff.

To add insult to injury, 'go test' also rearranges the output when a
parent test has multiple sub-tests (all the sub-test's t.Logf is always
printed after all the parent tests t.Logf), so we need to screw around
with a special Logf that can point at the "current" t (current_t.Logf)
in some places. Probably our entire way of using subtests is wrong,
since 'go test' would probably like to run them all in parallel if you
called t.Parallel(), but it definitely can't because the're all
manipulating the shared state created by the parent test. They should
probably all be separate toplevel tests instead, with common
setup/teardown logic. But that's a job for another time.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-13 23:12:35 -04:00
Avery Pennarun
e0b666c5d2 tstest.ResourceCheck: clarify success message.
Inclusion of the word "assert" made it seem like a failure, even though
it was supposed to be identifying the name of the function (Assert()).

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-13 23:02:32 -04:00
Avery Pennarun
89a6f27cf8 Merge remote-tracking branch 'origin/master' into base
* origin/master:
  types/logger: add ArgWriter
  wgengine: wrap tun.Device to support filtering and packet injection (#358)
2020-05-13 23:01:32 -04:00
Avery Pennarun
a7edf11a40 {ipn,control/controlclient}/tests: pass a logf function to control.New().
This matches the new API requirements.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-13 22:44:20 -04:00
Brad Fitzpatrick
fe97bedf67 types/logger: add ArgWriter 2020-05-13 14:47:13 -07:00
Dmytro Shynkevych
33b2f30cea wgengine: wrap tun.Device to support filtering and packet injection (#358)
Right now, filtering and packet injection in wgengine depend
on a patch to wireguard-go that probably isn't suitable for upstreaming.

This need not be the case: wireguard-go/tun.Device is an interface.
For example, faketun.go implements it to mock a TUN device for testing.

This patch implements the same interface to provide filtering
and packet injection at the tunnel device level,
at which point the wireguard-go patch should no longer be necessary.

This patch has the following performance impact on i7-7500U @ 2.70GHz,
tested in the following namespace configuration:
┌────────────────┐    ┌─────────────────────────────────┐     ┌────────────────┐
│      $ns1      │    │               $ns0              │     │      $ns2      │
│    client0     │    │      tailcontrol, logcatcher    │     │     client1    │
│  ┌─────┐       │    │  ┌──────┐         ┌──────┐      │     │  ┌─────┐       │
│  │vethc│───────┼────┼──│vethrc│         │vethrs│──────┼─────┼──│veths│       │
│  ├─────┴─────┐ │    │  ├──────┴────┐    ├──────┴────┐ │     │  ├─────┴─────┐ │
│  │10.0.0.2/24│ │    │  │10.0.0.1/24│    │10.0.1.1/24│ │     │  │10.0.1.2/24│ │
│  └───────────┘ │    │  └───────────┘    └───────────┘ │     │  └───────────┘ │
└────────────────┘    └─────────────────────────────────┘     └────────────────┘
Before:
---------------------------------------------------
| TCP send               | UDP send               |
|------------------------|------------------------|
| 557.0 (±8.5) Mbits/sec | 3.03 (±0.02) Gbits/sec |
---------------------------------------------------
After:
---------------------------------------------------
| TCP send               | UDP send               |
|------------------------|------------------------|
| 544.8 (±1.6) Mbits/sec | 3.13 (±0.02) Gbits/sec |
---------------------------------------------------
The impact on receive performance is similar.

Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-05-13 09:16:17 -04:00
David Anderson
9ccbcda612 wgengine/router: rename config.Settings to config.Config, make pointer.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-12 15:58:33 -07:00
David Anderson
72cae5504c wgengine: generate and plumb router.Settings in from ipn.
This saves a layer of translation, and saves us having to
pass in extra bits and pieces of the netmap and prefs to
wgengine. Now it gets one Wireguard config, and one OS
network stack config.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-12 15:58:33 -07:00
Brad Fitzpatrick
e42ec4efba derp/derphttp: use SOCKS/etc proxies for derphttp dials
Updates #227

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-05-12 14:38:15 -07:00
Wendi Yu
3663797815 Reduce logspam from node with no peers
Signed-off-by: Wendi Yu <wendi.yu@yahoo.ca>
2020-05-12 12:28:51 -07:00
David Anderson
cd01bcc395 wgengine/router: allow loopback traffic from our own IP(s).
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-11 16:57:35 -07:00
Brad Fitzpatrick
64f6104e63 portlist: reduce log spam/scariness for portlist in mac sandbox
Fixes tailscale/corp#235
2020-05-11 16:13:29 -07:00
David Anderson
bfdc8175b1 wgengine/router: add a setting to disable SNAT for subnet routes.
Part of #320.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-11 20:17:13 +00:00
Brad Fitzpatrick
8eda667aa1 types/logger: simplify mutex locking in rate-limited logger
Updates #365

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-05-11 08:44:10 -07:00
halulu
874be6566d netcheck: DERP latency over HTTPS when UDP is blocked
* netcheck: DERP letency over HTTPS when UDP failed

Updates #207

Signed-off-by: Zijie Lu <zijie@tailscale.com>

* netcheck: async DERP latency check over HTTPS

Updates #207

Signed-off-by: Zijie Lu <zijie@tailscale.com>

* netcheck: DERP latency check over HTTPS: fix concurrent map

Updates #207

Signed-off-by: Zijie Lu <zijie@tailscale.com>

* netcheck: DERP latency check over HTTPS: some improvements

Updates #207

Signed-off-by: Zijie Lu <zijie@tailscale.com>

* netcheck: DERP latency check over HTTPS: use timeout context

Updates #207

Signed-off-by: Zijie Lu <zijie@tailscale.com>

* netcheck: DERP latency check over HTTPS: use report mutex

Updates #207

Signed-off-by: Zijie Lu <zijie@tailscale.com>

* netcheck: DERP latency check over HTTPS if UDP is BLOCKED

Updates #207

Signed-off-by: Zijie Lu <zijie@tailscale.com>

* netcheck: DERP latency check over HTTPS: new function measureHTTPSLatency

Updates #207

Signed-off-by: Zijie Lu <zijie@tailscale.com>
2020-05-11 11:23:09 -04:00
Brad Fitzpatrick
8a3e77fc43 ipn, wgengine/filter: remove exported type aliases 2020-05-11 07:19:17 -07:00
David Anderson
8b0be7475b cmd/tailscale: warn subnet route users if IP forwarding is off. #320
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-11 06:08:58 +00:00
David Anderson
ad1cfe8bbe cmd/tailscale: support IPs or CIDRs in -advertise-routes.
Fixes #370.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-11 01:49:03 +00:00
David Anderson
21ac65d3da wgengine/router: explicitly detect and complain about busybox's ip.
Defensive programming against #368 in environments other than Docker,
e.g. if you try using Tailscale in Alpine Linux directly, sans
container.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-10 17:12:17 -07:00
David Anderson
e00b814a24 Dockerfile: install iproute2 in the container image.
Fixes #368.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-10 17:12:17 -07:00
David Anderson
381b94d4d1 wgengine/router: include command output if ip rule list fails.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-10 17:12:17 -07:00
David Anderson
e83d02ffd1 wgengine: don't double-close tundev on setup error.
Part of #368.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-10 17:12:17 -07:00
David Anderson
efc1feedc9 wgengine/router: include more information when iptables ops fail.
The iptables package we use doesn't include command output, so we're
left with guessing what went wrong most of the time. This will at
least narrow things down to which operation failed.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-10 22:14:33 +00:00
Brad Fitzpatrick
529e2cb31a ipn: add AllowVersionSkew bool to Notify & Message
For "tailscale status" on macOS (from separately downloaded
cmd/tailscale binary against App Store IPNExtension).

(This isn't all of it, but I've had this sitting around uncommitted.)
2020-05-09 13:51:48 -07:00
Wendi Yu
fde384b359 Fix macOS build
staticcheck used to fail on macOS (and presumably windows) due to a
variable declared in a common package that was only used by the Linux
build, which would prevent `redo pr` from passing on Mac. Moved variable
declaration from the common file to the Linux-specific one to resolve
the compiler complaint.

Signed-off-by: Wendi Yu <wendi.yu@yahoo.ca>
2020-05-08 21:14:41 -07:00
David Anderson
e16f7e48a3 wgengine: simplify wgcfg.* to netaddr.* conversion.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-09 03:30:37 +00:00
David Anderson
48b1e85e8a types/logger: fix deadlock in the burst case.
Fixes #365.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-09 02:52:03 +00:00
David Anderson
ccbd0937d0 wgengine: avoid v6 mapped v4 IPs when converting to netaddr types.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-08 23:32:06 +00:00
Sylvain Rabot
74d6ab995d ipn/ipnstate: improve HTML output
Signed-off-by: Sylvain Rabot <sylvain@abstraction.fr>
2020-05-08 14:29:42 -07:00
Wendi Yu
0c69b4e00d Implement rate limiting on log messages (#356)
Implement rate limiting on log messages

Addresses issue #317, where logs can get spammed with the same message
nonstop. Created a rate limiting closure on logging functions, which
limits the number of messages being logged per second based on format
string. To keep memory usage as constant as possible, the previous cache
purging at periodic time intervals has been replaced by an LRU that
discards the oldest string when the capacity of the cache is reached.


Signed-off-by: Wendi Yu <wendi.yu@yahoo.ca>
2020-05-08 13:21:36 -06:00
Wendi Yu
499c8fcbb3 Replace our ratelimiter with standard rate package (#359)
* Replace our ratelimiter with standard rate package

Signed-off-by: Wendi Yu <wendi.yu@yahoo.ca>
2020-05-08 12:30:22 -06:00
David Anderson
b01db109f5 wgengine/router: use inet.af/netaddr, not wgcfg.CIDR.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-07 23:40:03 -07:00
David Anderson
b8f01eed34 wgengine/router: remove wireguard-go config from settings.
Instead, pass in only exactly the relevant configuration pieces
that the OS network stack cares about.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-07 19:04:13 -07:00
David Anderson
8861bb5a19 wgengine/router: alter API to support multiple addrs, and use on linux.
FreeBSD and OpenBSD will error out with a complaint if we pass >1 address
right now, but we don't yet so that's okay.
2020-05-08 00:18:18 +00:00
David Anderson
6802481bf5 wgengine/router: don't use gateway routes on linux. 2020-05-07 19:22:50 +00:00
David Anderson
78b1ed39ea wgengine/router: add more documentation. 2020-05-07 18:30:37 +00:00
David Anderson
c9de43cd59 wgengine/router: fix typo.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-07 18:01:55 +00:00
David Anderson
89af51b84d wgengine: plumb locally advertised subnet routes.
With this change, advertising subnet routes configures the
firewall correctly.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-07 17:48:49 +00:00
David Anderson
89198b1691 wgengine/router: rewrite netfilter and routing logic.
New logic installs precise filters for subnet routes,
plays nice with other users of netfilter, and lays the
groundwork for fixing routing loops via policy routing.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-06 22:13:38 +00:00
David Anderson
7618d7e677 wgengine/router: simplify some cmd invocations.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-05-06 22:13:38 +00:00
Zijie Lu
e3559d1c45 cmd/netcheck: better DERP latency checking output
Fixes #206

Signed-off-by: Zijie Lu <zijie@tailscale.com>
2020-05-05 15:11:20 -04:00
Dmytro Shynkevych
46f4b18fe8 control/controlclient: revert extreneous synchronization.
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-05-05 09:39:45 -07:00
Dmytro Shynkevych
3b94eabee3 control/controlclient: synchronize hostinfo test.
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-05-05 07:42:48 -07:00
Brad Fitzpatrick
44b07aa708 netcheck: STUN less aggressively to known distant servers
If Australia's far away and not going to be used, it's still going to
be far away a minute later. No need to send backup
just-in-case-UDP-gets-lost STUN packets to the known far away
destinations. Those are the ones most likely to trigger retries due to
delay anyway (in random 50-250ms, currently). But we'll keep sending 1
packet to them, just in case our airplane landed.

Likewise, be less aggressive with IPv6. The main point is just to see
whether IPv6 works. No need to send up to 10 packets every round. Max
two is enough (except for the first round). This does mean our STUN
traffic graphs for IPv4-vs-IPv6 will change shape. Oh well. It was a
weird eyeball metric for IPv6 connectivity anyway and we have better
metrics.

We can tweak this policy over time. It's factored out and has tests
now.
2020-05-04 23:37:01 -07:00
Brad Fitzpatrick
828aa6dcb0 stunner: add Stunner.MaxTries option 2020-05-04 23:37:01 -07:00
Brad Fitzpatrick
495796fff1 derp/derpmap: add World.ForeachServer, check STUN server validity earlier 2020-05-04 23:37:01 -07:00
Avery Pennarun
108237798d controlclient and ipn tests: supply --advertise-tags and --advertise-routes.
This helps validate the server's behaviour when these are present.
2020-05-05 01:42:20 -04:00
Dmytro Shynkevych
68a173bc24 cmd/mkpkg: support adding empty directories.
Signed-off-by: Dmytro Shynkevych <dmytro@tailscale.com>
2020-05-04 17:57:13 -04:00
Brad Fitzpatrick
3b546dc29a portlist: make two error paths have unique messages
For debugging #339
2020-05-04 07:45:15 -07:00
Brad Fitzpatrick
fefd7e10dc types/structs: add structs.Incomparable annotation, use it where applicable
Shotizam before and output queries:

sqlite> select sum(size) from bin where func like 'type..%';
129067
=>
120216
2020-05-03 14:05:32 -07:00
Elias Naur
7b901fdbbc logpolicy: report the correct error
Signed-off-by: Elias Naur <mail@eliasnaur.com>
2020-05-01 07:05:24 -07:00
Elias Naur
0068e57407 go.mod,go.sum: bump golang.org/x/sys for the Android dup2 fix
No tidy, because it doesn't work for me:

$ go mod tidy
go: finding module for package tailscale.io/control
go: finding module for package tailscale.io/control/cfgdb
tailscale.com/control/controlclient tested by
	tailscale.com/control/controlclient.test imports
	tailscale.io/control: cannot find module providing package tailscale.io/control: unrecognized import path "tailscale.io/control": parse https://tailscale.io/control?go-get=1: no go-import meta tags (meta tag tailscale.com did not match import path tailscale.io/control)
tailscale.com/control/controlclient tested by
	tailscale.com/control/controlclient.test imports
	tailscale.io/control/cfgdb: cannot find module providing package tailscale.io/control/cfgdb: unrecognized import path "tailscale.io/control/cfgdb": parse https://tailscale.io/control/cfgdb?go-get=1: no go-import meta tags (meta tag tailscale.com did not match import path tailscale.io/control/cfgdb)

Signed-off-by: Elias Naur <mail@eliasnaur.com>
2020-05-01 18:41:19 +10:00
Avery Pennarun
9d1f48032a cmd/tailscale: add --advertise-tags option.
These will be used for dynamically changing the identity of a node, so
its ACL rights can be different from your own.

Note: Not all implemented yet on the server side, but we need this so
we can request the tagged rights in the first place.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-05-01 01:32:24 -04:00
David Crawshaw
5650f1ecf9 controlclient, ipn: adjust tests for tailscale.com keepalive change 2020-05-01 13:44:47 +10:00
David Crawshaw
c10f90357e ipn/e2e_test: fix flaky logout state drain 2020-05-01 13:44:47 +10:00
David Anderson
657f331e8b net/dnscache: remove unnecessary lint warning. 2020-04-30 20:31:44 -07:00
David Anderson
9396024bd7 portlist: move code around to avoid unused function warnings. 2020-04-30 20:31:44 -07:00
David Anderson
755fd9253c wgengine/router: fix up docstring.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-04-30 13:37:40 -07:00
David Anderson
1ac570def7 wgengine/router: split out from wgengine.
The router implementations are logically separate, with their own API.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-04-30 13:31:24 -07:00
Avery Pennarun
ee3395e63a wgengine/filter: fix linter warning.
Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-04-30 06:16:53 -04:00
Avery Pennarun
5e5e5db75f Appease the "missing copyright header" check.
Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-04-30 06:15:26 -04:00
Avery Pennarun
65fbb9c303 wgengine/filter: support subnet mask rules, not just /32 IPs.
This depends on improved support from the control server, to send the
new subnet width (Bits) fields. If these are missing, we fall back to
assuming their value is /32.

Conversely, if the server sends Bits fields to an older client, it will
interpret them as /32 addresses. Since the only rules we allow are
"accept" rules, this will be narrower or equal to the intended rule, so
older clients will simply reject hosts on the wider subnet (fail
closed).

With this change, the internal filter.Matches format has diverged
from the wire format used by controlclient, so move the wire format
into tailcfg and convert it to filter.Matches in controlclient.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-04-30 04:56:43 -04:00
Avery Pennarun
d6c34368e8 ipn/local: differentiate Shields Up from Uninitialized in logs.
We were printing "Shields Up" when the netmap wasn't initialized yet,
which while technically effectively true, turned out to be confusing
when trying to debug things.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-04-30 04:56:36 -04:00
Avery Pennarun
64db026c8b backoff: add a LogLongerThan configuration.
Some programs use frequent short-duration backoffs even under non-error
conditions. They can set this to avoid logging short backoffs when
things are operating normally, but still get messages when longer
backoffs kick in.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-04-29 05:41:39 -04:00
Avery Pennarun
ced9b4008a ipn: clear the hostinfo.Services list when prefs.ShieldsUp==true.
When shields are up, no services are available to connect to, so hide
them all. This will also help them disappear from the UI menu on
other nodes.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-04-29 05:25:45 -04:00
Avery Pennarun
d7429b9a8d Add prefs.ShieldsUp and --shields-up option.
This sets a default packet filter that blocks all incoming requests,
giving end users more control over who can get into their machine, even
if the admin hasn't set any central ACLs.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-04-29 05:25:45 -04:00
Avery Pennarun
85e675940d wgengine/filter: allow ICMP response packets.
Longer term, we should probably update the packet filter to be fully
stateful, for both TCP and ICMP. That is, only ICMP packets related to
a session *we* initiated should be allowed back in. But this is
reasonably secure for now, since wireguard is already trimming most
traffic. The current code would not protect against eg. Ping-of-Death style
attacks from VPN nodes.

Fixes tailscale/tailscale#290.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-04-29 05:25:45 -04:00
Avery Pennarun
dbc1f71e5d ipn/message: fix some message encoding problems.
- Reset() was not including a Version field, so was getting rejected;
  the Logout operation no longer happened when the client got disconnected.

- Don't crash if we can't decode 0-byte messages, which I suspect might
  sometimes come through on EOF.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2020-04-29 05:25:45 -04:00
David Crawshaw
2372530964 logtail/backoff: only log backoffs > 2sec
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-04-29 17:41:48 +10:00
David Anderson
0038223632 tstest: rename from testy.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-04-28 20:45:12 -07:00
Brad Fitzpatrick
e1526b796e ipn: don't listen on the unspecified address in test
To avoid the Mac firewall dialog of (test) death.

See 4521a59f30
which I added to help debug this.
2020-04-28 19:20:02 -07:00
David Crawshaw
d2b7cb1e45 ipn, controlclient: add control.New parameter
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-04-29 08:06:06 +10:00
Brad Fitzpatrick
f4c7eb8c44 ipn: revert part of 18017f7630
In retrospect I don't trust it and I'm afraid might've caused some Mac flakiness.
I'd like more tests here before I work on this.

Updates #288
2020-04-28 14:04:45 -07:00
Brad Fitzpatrick
18017f7630 ipn, wgengine/magicsock: be more idle when in Stopped state with no peers
(Previously as #288, but with some more.)

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-04-28 13:41:29 -07:00
David Anderson
66c7875974 control/controlclient: wait for c1 to receive a netmap.
This strictly sequences things such that c1 is fully registered in
the control server before c2 creates its poll. Failure to do this
can cause an inversion where c2's poll finishes establishing
before c1's poll starts, which results in c2 getting disconnected
rather than c1, and the test times out waiting for c1 to get kicked.

Fixes #98.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-04-27 23:06:02 -07:00
David Anderson
cbb1e2e853 control/controlclient: document test TestClientsReusingKeys.
The test is straightforward, but it's a little perplexing if you're
not overly familiar with controlclient.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-04-27 22:48:40 -07:00
fgergo
8296c934ac Update ifconfig_windows.go
OLE calls sometimes unexpectedly fail, but retries can succeed. Change panic() to return errors. This way ConfigureInterface() retries can succeed.
2020-04-27 19:57:57 -07:00
David Anderson
9669b85b41 wgengine/magicsock: wait for endpoint updater goroutine when closing.
Fixes #204.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-04-27 14:46:10 -07:00
Elias Naur
ad0795efc2 net/dnscache: don't use the Go resolver on Android
The local resolver is not available for apps on Android.

Signed-off-by: Elias Naur <mail@eliasnaur.com>
2020-04-27 12:04:39 -07:00
Brad Fitzpatrick
a464439658 control/controlclient: fix build break caused by overzealous gitting 2020-04-27 08:18:35 -07:00
Brad Fitzpatrick
2244cca5ff net/tlsdial: update package doc to say it's now somewhat useless 2020-04-27 08:17:18 -07:00
Brad Fitzpatrick
58e83d8f66 tempfork/x509: moved to tailscale/go's crypto/x509 instead 2020-04-27 08:14:54 -07:00
Brad Fitzpatrick
172d72a060 Revert "net/tlsdial: add memory-optimized TLS cert verification path for iOS"
This reverts commit 6fcbd4c4d4.

Decided to put it in tailscale/go's crypto/x509 instead.
2020-04-27 08:13:37 -07:00
Brad Fitzpatrick
5d67365cc9 logtail: add PrivateID.IsZero method 2020-04-27 07:33:23 -07:00
Brad Fitzpatrick
9497921f52 logpolicy: also set up TLS dialing (for iOS) for log uploads
This was the last of the three places that do TLS from clients (logs,
control, derp). With this, iOS should be able to use the
memory-efficient x509 root CertPool.
2020-04-26 08:31:14 -07:00
Brad Fitzpatrick
c726c1eec9 logtail: add const DefaultHost with default server name 2020-04-26 08:31:07 -07:00
Brad Fitzpatrick
1a0f6fea58 go.mod, go.sum: bump wireguard-go, tidy 2020-04-26 08:06:06 -07:00
Brad Fitzpatrick
95a658e1e3 control/controlclient: also rename HTTPC in the tests 2020-04-26 07:51:54 -07:00
Brad Fitzpatrick
eb6de2bd88 control/controlclient: restore Options.HTTPC as Options.HTTPTestClient
I removed the HTTPC field in b6fa5a69be but it was apparently still
used in [oss-skipped] tests.

Restore it, but name it so it's more obvious that it's only for
tests. (It currently is, and I'd like to keep it like that for now.)
2020-04-26 07:48:26 -07:00
Brad Fitzpatrick
6fcbd4c4d4 net/tlsdial: add memory-optimized TLS cert verification path for iOS
Behind a build tag for now.
2020-04-25 13:55:51 -07:00
Brad Fitzpatrick
b6fa5a69be net/tlsdial: add package for TLS dials, and make DERP & controlclient use it
This will do the iOS-optimized cert checking in a following change.
2020-04-25 13:24:53 -07:00
Brad Fitzpatrick
d427fc023e tempfork/x509: remove the bundle tag in our fork
We want to be able to omit from only one (not both)
2020-04-25 10:00:10 -07:00
Brad Fitzpatrick
28c632c97b tempfork/x509: store certs for iOS compressed in binary, parse lazily 2020-04-25 08:54:01 -07:00
Brad Fitzpatrick
8fd8fc9c7d tempfork/x509: fix build on darwin and windows
These fixes were originally in the updates to CL 229917 after
Trybots failed there.
See https://go-review.googlesource.com/c/go/+/229917/1..3
2020-04-25 08:03:10 -07:00
Brad Fitzpatrick
bfc1261ab6 crypto/x509: keep smaller root cert representation in memory until needed
(from patchset 1, c12c890c64dd6372b3893af1e6f5ab11802c9e81, of
https://go-review.googlesource.com/c/go/+/230025/1, with merges fixes
due to parent commit's differents from its ps1..ps3)

Instead of parsing the PEM files and then storing the *Certificate
values forever, still parse them to see if they're valid and pick out
some fields, but then only store the decoded pem.Block.Bytes until
that cert is first needed.

Saves about 500K of memory on my (Debian stable) machine after doing a
tls.Dial or calling x509.SystemCertPool.

A more aggressive version of this is still possible: we can not keep
the pem.Block.Bytes in memory either, and re-read them from disk when
necessary. But dealing with files disappearing and even large
multi-cert PEM files changing (with offsets sliding around) made this
conservative version attractive. It doesn't change the
slurp-roots-on-startup semantics. It just does so with less memory
retained.

Change-Id: I3aea333f4749ae3b0026042ec3ff7ac015c72204
2020-04-24 21:27:48 -07:00
Brad Fitzpatrick
f5993f2440 crypto/x509: add support for CertPool to load certs lazily
(from patchset 1, 7cdc3c3e7427c9ef69e19224d6036c09c5ea1723, of
https://go-review.googlesource.com/c/go/+/229917/1)

This will allow building CertPools that consume less memory. (Most
certs are never accessed. Different users/programs access different
ones, but not many.)

This CL only adds the new internal mechanism (and uses it for the
old AddCert) but does not modify any existing root pool behavior.
(That is, the default Unix roots are still all slurped into memory as
of this CL)

Change-Id: Ib3a42e4050627b5e34413c595d8ced839c7bfa14
2020-04-24 21:27:48 -07:00
Brad Fitzpatrick
6b232b5a79 Disable staticcheck for tempfork packages. 2020-04-24 20:46:06 -07:00
Numerous Gophers
3bab226299 Add fork of Go 1.15-dev's crypto/x509
Snapshotted from Go commit 619c7a48a38b28b521591b490fd14ccb7ea5e821
(https://go-review.googlesource.com/c/go/+/229762,
"crypto/x509: add x509omitbundledroots build tag to not embed roots")

With 975c01342a25899962969833d8b2873dc8856a4f
(https://go-review.googlesource.com/c/go/+/220721) removed, because it
depends on other stuff in Go std that doesn't yet exist in a Go
release.

Also, add a subset fork of Go's internal/testenv, for use by x509's tests.
2020-04-24 20:19:41 -07:00
Elias Naur
2dac4f2b24 wgengine/monitor: disable monitor on Android
Netlink is not supported on Android.

Signed-off-by: Elias Naur <mail@eliasnaur.com>
2020-04-24 06:35:31 -07:00
David Anderson
eccae0cd0c tsweb: add ReturnHandlerFunc.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-04-22 15:34:28 -07:00
Brad Fitzpatrick
0a50ecbad3 control/controlclient: add missing vlog, for consistency with other sites 2020-04-21 15:36:46 -07:00
Brad Fitzpatrick
b8594dc937 control/controlclient: fix deadlock in timeout+keepalive race
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-04-21 15:22:58 -07:00
wardn
d052586da7 cmd/taillogin: delete it
Signed-off-by: wardn <wardn@users.noreply.github.com>
2020-04-19 21:40:52 -07:00
David Anderson
108e3af76f github: use Go 1.14 in CI.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-04-19 14:46:24 -07:00
Brad Fitzpatrick
268d331cb5 wgengine/magicsock: prune key.Public-keyed on peer removals
Fixes #215
2020-04-18 08:48:01 -07:00
Brad Fitzpatrick
00d053e25a wgengine/magicsock: fix slow memory leak as peer endpoints move around
Updates #215
2020-04-18 08:28:10 -07:00
Brad Fitzpatrick
7fc97c5493 wgengine/magicsock: use netaddr more
In prep for deleting from the ever-growing maps.
2020-04-17 15:15:42 -07:00
Brad Fitzpatrick
6fb30ff543 wgengine/magicsock: start using inet.af/netaddr a bit 2020-04-17 13:51:52 -07:00
David Anderson
42e62a7eb2 testy: fix clock initialization when Start is provided.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-04-17 13:20:09 -07:00
David Anderson
ccfc4e0634 go.mod: bump wireguard-go version.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-04-16 12:53:58 -07:00
David Anderson
afbfe4f217 wgengine: drop wireguard MTU to 1280 bytes.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-04-14 16:36:28 -07:00
David Anderson
b925e18f70 tstime: hand-implement parseInt for specific needs of rfc3339 parsing.
Makes parsing 4.6x faster.

name         old time/op  new time/op  delta
ParseInt-12  32.1ns ± 1%   6.9ns ± 2%  -78.55%  (p=0.000 n=10+9)

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-04-14 12:36:55 -07:00
Avery Pennarun
dc9b39e3fb wgengine/windows: use new winipcfg.Sync{Addresses,Routes} functions.
This avoids flushing and reloading the whole list of addresses and
routes whenever remote node information changes.
2020-04-13 13:20:20 -04:00
Brad Fitzpatrick
adf74c75ed wgengine: also diagnose not-yet-rebooted system updates on Arch 2020-04-13 09:22:08 -07:00
Brad Fitzpatrick
3464114b88 logtail: add ParsePublicID that doesn't allocate 2020-04-13 08:54:35 -07:00
Brad Fitzpatrick
780deb9996 go.mod, go.sum: update go4.org/mem to its new home in its own module
Cleans up our go.sum, not that it really matters.
2020-04-11 14:00:48 -07:00
Brad Fitzpatrick
614eec174f derp/derphttp: avoid endless reconnect race on failure
Originally from @stablebits (Dmitry Adamushko) in:
https://github.com/tailscale/tailscale/pull/264
2020-04-11 13:37:20 -07:00
Brad Fitzpatrick
347a926ac4 control/controlclient: add opt-in netmap verbose debugging env var 2020-04-11 09:22:33 -07:00
Brad Fitzpatrick
45f2b53aca all: remove unnecessary trailing newlines in format patterns for consistency
And document on logger.Logf that it's unnecessary.
2020-04-11 08:35:34 -07:00
Brad Fitzpatrick
a7e7c7b548 wgengine/magicsock: close derp connections on rebind
Fixes #276

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-04-10 20:43:00 -07:00
Brad Fitzpatrick
614261d00d wgengine/magicsock: reset AddrSet states on Rebind
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-04-10 20:27:35 -07:00
Brad Fitzpatrick
c0697e1feb net/interfaces: add IsExpensive and up state to State
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-04-10 20:25:12 -07:00
Brad Fitzpatrick
a55c4217db wgengine: diagnose why CreateTUN might've failed for users
Fixes #273

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-04-10 20:16:27 -07:00
Brad Fitzpatrick
3a3b64301e wgengine: quiet some engine reconfig logging, make more consistent
Updates #282

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-04-10 13:53:01 -07:00
Dmitry Adamushko
806645ea0e derp: prevent readFrame() from reading more than len(b) bytes.
Signed-off-by: Dmitry Adamushko <da@stablebits.net>
2020-04-10 08:56:23 -07:00
Dmitry Adamushko
f2c2d0de68 derp/derp_server: unregisterClient() for replaced client connections.
When unregistering a replaced client connection, move the
still-connected peers to the current client connecition. Inform
the peers that we've gone only when unregistering the active
client connection.

Signed-off-by: Dmitry Adamushko <da@stablebits.net>
2020-04-10 08:52:30 -07:00
Brad Fitzpatrick
39ae80a2e7 version: bump date 2020-04-10 08:23:36 -07:00
Brad Fitzpatrick
1ec27dbb5b wgengine: remove an allocation in reconfig
Minor.
2020-04-10 08:22:13 -07:00
Brad Fitzpatrick
b24029717b ipn: outdent some code in if that's statically always true 2020-04-10 07:52:30 -07:00
David Crawshaw
5b95aa81ea wgengine: remove IpcSetOperation on LinkChange
This was only done occasionally, but was extremely disruptive
when done and is no longer necessary.

It used to be that when switching links, we had to immediately
generate handshakes to everyone we were communicating with to
punch a hole in any NAT we were talking through. (This ended up
not really working, because in the process we got rid of our
session keys and ended up having a futile conversation for many
seconds.)

Now we have DERP, our link change propogates to the other side
as a new list of endpoints, so they start spraying packets.
We will definitely get one thanks to DERP, which will cause us
to spray, opening any NAT we are behind.

The result is that for good connections, we don't trash session
keys and cause an interruption.

Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-04-10 15:07:20 +10:00
Brad Fitzpatrick
fe149979e6 logpolicy: include Go version in version log 2020-04-09 14:46:19 -07:00
Brad Fitzpatrick
73249f8032 netcheck: aggregate spammy logging onto one concise line 2020-04-09 13:14:38 -07:00
Brad Fitzpatrick
922d9546bf wgengine: don't allocate so much in userspaceEngine.getStatus
It was one of the top garbage producers on my phone.

It's slated to be deleted and replaced anyway, but this helps in the
meantime.

The go.sum changes look scary, but the new dep only adds 240 bytes to
the binary. The go.sum noise is just cmd/go being aggressive in
including a lot of stuff (which is being fixed in Go 1.15, for what I
understand). And I ran a go mod tidy, which added some too. (I had to
write a custom wrapper around go mod tidy because this mod tidy
normally breaks on tailscale.io/control being missing but referenced
in tests)

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-04-09 12:49:17 -07:00
David Crawshaw
6b2e29867e controlclient: add auth key test
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-04-09 20:17:09 +10:00
David Crawshaw
f8b72d2b5b cmd/tailscale: add up --authkey flag
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-04-09 20:17:09 +10:00
David Crawshaw
1747d099e9 ipn: add auth key
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-04-09 20:17:09 +10:00
David Crawshaw
3f087466f5 controlclient: add auth key
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-04-09 20:17:09 +10:00
David Crawshaw
22a0acff39 tailcfg: add auth key to RegisterRequest
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-04-09 20:17:09 +10:00
Sylvain Rabot
a279032998 cmd/mkpkg: fix missing default value for --depends
Signed-off-by: Sylvain Rabot <sylvain@abstraction.fr>
2020-04-08 12:07:07 -07:00
Brad Fitzpatrick
0f64d7f9cc wgengine: remove a tiny allocation
Drop in the bucket compared to the larger issues, but noticed it
when looking at pprof.
2020-04-07 22:23:40 -07:00
Brad Fitzpatrick
59800138ff bump wireguard dep 2020-04-07 10:02:34 -07:00
Brad Fitzpatrick
277fe84c6b version: don't depend on goversion on ios 2020-04-07 09:28:09 -07:00
Brad Fitzpatrick
2776209e49 portlist: don't depend on osexec package on ios, even if it's unused
Continuation of 5bb14c07dc.

The earlier commit provided the space savings (as the linker could see
through that osexec was unused at runtime), but it didn't clean up the
dep graph (from go list -json or godepgraph).

This removes the netstat.go file from the build too, just so the dep list
looks more reasonable.
2020-04-07 08:09:13 -07:00
Brad Fitzpatrick
5bb14c07dc portlist: don't depend on tempfork/osexec on iOS, saves 90KB
This gives us 90KB more of memory on iOS, as it shrinks the
NetworkExtension binary by 90KB.

The netstat binary isn't available in the network extension anyway, so
no point pulling in the osexec package which'll just fail to find
netstat anyway.
2020-04-07 07:58:09 -07:00
Brad Fitzpatrick
ec0cd60fc3 portlist: fail earlier, more nicely on iOS 2020-04-06 20:11:24 -07:00
David Anderson
96b2f20c5b types/logger: add Discard helper. 2020-04-06 19:15:19 -07:00
Dmitry Adamushko
44434fdc82 derp/derp_server: fixed unbalanced {register,unregister}Client() calls.
Signed-off-by: Dmitry Adamushko <da@stablebits.net>
2020-04-06 15:13:47 -07:00
Blake Gentry
e19287f60f wgengine/magicsock: fix Conn docs type reference
The docs on magicsock.Conn stated that they implemented the
wireguard/device.Bind interface, yet this type does not exist. In
reality, the Conn type implements the wireguard/conn.Bind interface.

I also fixed a small typo in the same file.

Signed-off-by: Blake Gentry <blakesgentry@gmail.com>
2020-04-06 15:11:56 -07:00
Brad Fitzpatrick
71d6738333 tstime: change an Errorf+return to Fatalf in subtest
Forgot to git add this during review. Fail.
2020-04-06 08:20:15 -07:00
Brad Fitzpatrick
febdac0499 tstime: write Parse3339 parse that doesn't use time.Parse
It doesn't allocate and it's half the time of time.Parse (which
allocates), and 2/3rds the time of time.ParseInLocation (which
doesn't).

Go with a UTC time:

BenchmarkGoParse3339/Z-8                 2200995               534 ns/op               0 B/op          0 allocs/op
BenchmarkGoParse3339/Z-8                 2254816               554 ns/op               0 B/op          0 allocs/op
BenchmarkGoParse3339/Z-8                 2159504               522 ns/op               0 B/op          0 allocs/op

Go allocates with a "-08:00" suffix instead of ending in "Z":

BenchmarkGoParse3339/TZ-8                1276491               884 ns/op             144 B/op          3 allocs/op
BenchmarkGoParse3339/TZ-8                1355858               942 ns/op             144 B/op          3 allocs/op
BenchmarkGoParse3339/TZ-8                1385484               911 ns/op             144 B/op          3 allocs/op

Go doesn't allocate if you use time.ParseInLocation, but then you need
to parse the string to find the location anyway, so might as well go
all the way (below).

BenchmarkGoParse3339InLocation-8         1912254               597 ns/op               0 B/op          0 allocs/op
BenchmarkGoParse3339InLocation-8         1980043               612 ns/op               0 B/op          0 allocs/op
BenchmarkGoParse3339InLocation-8         1891366               612 ns/op               0 B/op          0 allocs/op

Parsing RFC3339 ourselves, UTC:

BenchmarkParse3339/Z-8                   3889220               307 ns/op               0 B/op          0 allocs/op
BenchmarkParse3339/Z-8                   3718500               309 ns/op               0 B/op          0 allocs/op
BenchmarkParse3339/Z-8                   3621231               303 ns/op               0 B/op          0 allocs/op

Parsing RFC3339 ourselves, with timezone (w/ *time.Location fetched
from sync.Map)

BenchmarkParse3339/TZ-8                  3019612               418 ns/op               0 B/op          0 allocs/op
BenchmarkParse3339/TZ-8                  2921618               401 ns/op               0 B/op          0 allocs/op
BenchmarkParse3339/TZ-8                  3031671               408 ns/op               0 B/op          0 allocs/op

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-04-06 08:19:17 -07:00
Brad Fitzpatrick
02948d2c86 Dockerfile: add some usage docs, bump to Go 1.14 2020-04-06 07:57:47 -07:00
Brad Fitzpatrick
d503dee6f1 tstime: add new package for time utilities, starting with Parse3339
Go's time.Parse always allocates a FixedZone for time strings not in
UTC (ending in "Z"). This avoids that allocation, at the cost of
adding a cache.

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-04-05 20:05:49 -07:00
David Anderson
4e0ee141e8 derp/derpmap: add derp5 (Sydney) to prod map.
Signed-off-by: David Anderson <dave@natulte.net>
2020-04-05 18:55:29 -07:00
Brad Fitzpatrick
996bf9cae7 logtail: don't send a User-Agent
Just useless bytes on the wire. Especially with HTTP/1.

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-04-05 13:16:56 -07:00
Brad Fitzpatrick
7bf436ba30 tsweb: add some Benchmarks
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-04-05 13:16:36 -07:00
Brad Fitzpatrick
64334143a1 tsweb: rename Handler to ReturnHandler
The name's been bugging me for a long time.

I liked neither the overlap between tsweb.Handler and http.Handler,
nor the name "ServeHTTPErr" which sounds like it's an error being
returned, like it's an error handler and not sometimes a happy path.

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-04-05 13:16:36 -07:00
Brad Fitzpatrick
bdc55d7091 logtail: add ParsePrivateID 2020-04-05 09:15:15 -07:00
Brad Fitzpatrick
50aeb5b9ad wgengine: unexport some windows funcs 2020-04-05 08:23:53 -07:00
David Anderson
b446de103a tsweb: fix tests.
Signed-off-by: David Anderson <dave@natulte.net>
2020-04-05 00:22:03 -07:00
David Anderson
af3a9dfad6 tsweb: add a StdHandler that doesn't log 200 responses.
Signed-off-by: David Anderson <dave@natulte.net>
2020-04-05 00:14:38 -07:00
David Anderson
ba2774ea27 cmd/mkpkg: support depending on stuff.
Signed-off-by: David Anderson <dave@natulte.net>
2020-04-04 18:38:09 -07:00
David Anderson
362d6af4e2 cmd/tailscaled: set CacheDirectory in service.
Signed-off-by: David Anderson <dave@natulte.net>
2020-04-04 16:52:05 -07:00
Brad Fitzpatrick
e71a7c7a2c logtail: read to EOF on chunked response
We'll be fixing the server so this won't trigger in practice,
but it demos the connection reuse problem.

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-04-04 16:12:15 -07:00
Brad Fitzpatrick
fcb6a34f4b logtail: reduce allocations encoding text
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-04-04 16:12:02 -07:00
Brad Fitzpatrick
2863e49db9 tsweb: don't flush, treat no-op Handler as 200, like Go
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-04-04 16:11:53 -07:00
Brad Fitzpatrick
3b4b17d239 logpolicy: log on dials, add knob to force HTTP/1 for log uploads
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-04-04 14:46:41 -07:00
David Anderson
5d995d9d6b tsweb: add a test case for nil child errors in tsweb.Error.
Signed-off-by: David Anderson <dave@natulte.net>
2020-04-03 10:37:39 -07:00
David Anderson
2c2dff9559 tsweb: don't panic if we get a tsweb.Error with no embedded error.
It's technically weird to return a tsweb.Error with no child err,
but it's a sensible thing to want to do, and we shouldn't panic
if it happens.

Signed-off-by: David Anderson <dave@natulte.net>
2020-04-03 10:36:21 -07:00
David Crawshaw
2f8719741e controlclient: do not send duplicate hostinfo/netinfo
This should never happen, so log when it does so we can fix it.

Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-04-02 13:12:29 +11:00
David Anderson
48d7ee1c6a cmd/microproxy: adjust to export node stats and a Go expvar server's stats.
This is a temporary specialization to what tailscale prod needs right now,
it'll go back to something more generic later.
2020-04-01 16:50:02 -07:00
Brad Fitzpatrick
8ca796d144 ipn, ipn/policy: filter portlist to a short list of "interesting" ports
Adds new package ipn/policy to be shared between node client & control server.

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-04-01 10:03:44 -07:00
Brad Fitzpatrick
c6aa5b639f tailcfg: clarify Hostinfo.OS doc 2020-04-01 09:27:35 -07:00
Brad Fitzpatrick
4524dcf51e version: move runtime.OS to tailscale OS mapping func to version
So other code can use this without duplicating the policy.
2020-04-01 08:50:56 -07:00
David Anderson
c14bc028ac cmd/microproxy: tiny TLS proxy that borrows autocert x509 certs. 2020-03-31 12:24:33 -07:00
Brad Fitzpatrick
1df3c8d02a derp, netcheck: make tests listen on localhost only
avoid macOS firewall pop-ups
2020-03-30 11:29:08 -07:00
Brad Fitzpatrick
5362e952e1 safesocket: gofmt
Was developed on a random machine without my normal environment.
2020-03-30 11:23:18 -07:00
Brad Fitzpatrick
fee2d9fad4 safesocket: connect to the macOS network extension on darwin (as last resort)
(For cmd/tailscale CLI support on macOS)

Signed-off-by: Brad Fitzpatrick <brad@danga.com>
2020-03-29 22:15:28 -07:00
David Crawshaw
0590ad68be controlclient, ipn: adjust tests for authURL semantic changes
The tests cheat at filling out web forms by directly POSTing to
the target. The target for authURLs has changed slightly, the base
authURL now redirects the user to the login page.

Additionally, the authURL cycle now checks the cookie is set
correctly, so we add cookie jars where necessary to pass the
cookie through.
2020-03-30 15:51:46 +11:00
Brad Fitzpatrick
a4ef345737 cmd/tailscale: add status subcommand
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-27 20:34:36 -07:00
Brad Fitzpatrick
810c1e9704 types/key: make Public implement TextMarshaler, TextUnmarshaler
So it can be a map key with encoding/json
2020-03-27 13:03:35 -07:00
Brad Fitzpatrick
f51f18b42b ipn: move FakeBackend to a test-only file 2020-03-27 13:02:33 -07:00
Brad Fitzpatrick
8ebee05fbd cmd/tailscale: remove unnecessary logpolicy/logtail logging 2020-03-27 08:27:36 -07:00
David Anderson
80261b02ba testy: make safe for concurrent use.
Signed-off-by: David Anderson <dave@natulte.net>
2020-03-27 03:05:34 -07:00
David Anderson
1fdadf06f1 testy: don't give Clock.Step==0 magical behavior.
Turns out it's sometimes useful to stop time entirely.

Signed-off-by: David Anderson <dave@natulte.net>
2020-03-27 00:38:39 -07:00
Brad Fitzpatrick
8b3f6be008 control/controlclient: flip IPv6 to be on by default
The DEBUG_INCLUDE_IPV6 environment variable is now an opt-out.

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-26 22:02:56 -07:00
Brad Fitzpatrick
322499473e cmd/tailscaled, wgengine, ipn: add /debug/ipn handler with world state
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-26 14:26:24 -07:00
David Anderson
dbca186a64 stunner: fix data race.
In very low-latency conditions, a STUN request can complete before
the startup loop has finished firing off goroutines, leading to
a concurrent map mutation.
2020-03-25 23:11:22 -07:00
Brad Fitzpatrick
7fb8d873ac logpolicy: don't log timestamp when running under systemd
It'll do it anyway.

Makes journalctl -fu cleaner.

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-25 21:03:06 -07:00
Brad Fitzpatrick
2d48f92a82 wgengine/magicsock: re-stun every [20,27] sec, not 28
28 is cutting it close, and we think jitter will help some spikes
we're seeing.

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-25 14:25:33 -07:00
Brad Fitzpatrick
2c7ddd0828 go.mod, go.sum: tidy 2020-03-25 14:05:33 -07:00
Brad Fitzpatrick
577f321c38 wgengine/magicsock: revise derp fallback logic
Revision to earlier 6284454ae5

Don't be sticky if we have no peers.

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-25 13:09:18 -07:00
David Anderson
cbd8aceb95 go.mod: bump wireguard-go version.
Fixes #219.

Signed-off-by: David Anderson <dave@natulte.net>
2020-03-25 12:20:46 -07:00
Brad Fitzpatrick
2e420ad8b6 wgengine, wgengine/filter: minor doc, style, performance, locking changes
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-25 08:41:01 -07:00
Brad Fitzpatrick
6284454ae5 wgengine/magicsock: if UDP blocked, pick DERP where most peers are
Updates #207

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-25 08:00:44 -07:00
Avery Pennarun
f53e78e0d5 wgengine: don't lose filter state on filter reconfig.
We were abandoning the UDP port LRU every time we got a new packet
filter from tailcontrol, which caused return packets to suddenly stop
arriving.
2020-03-25 04:52:41 -04:00
Avery Pennarun
4336de0d98 ipn/local: don't print packet filter every single time.
It's extremely noisy right now for domains with complex ACLs.
2020-03-25 04:52:41 -04:00
Avery Pennarun
a56e853b72 cmd/relaynode: delete it!
tailscale+tailscaled now completely obsoletes relaynode, so let's let
it finally go away.
2020-03-25 04:48:15 -04:00
David Anderson
73fccd8b06 control/controlclient: remove old compat PacketFilter initialization.
Signed-off-by: David Anderson <dave@natulte.net>
2020-03-24 16:00:41 -07:00
Brad Fitzpatrick
d321190578 wgengine/magicsock: stringify [IPv6]:port normally in AddrSet.String 2020-03-24 13:40:43 -07:00
Brad Fitzpatrick
3c3ea8bc8a wgengine/magicsock: finish IPv6 transport support
DEBUG_INCLUDE_IPV6=1 is still required, but works now.

Updates #18 (fixes it, once env var gate is removed)
2020-03-24 10:56:22 -07:00
Brad Fitzpatrick
82ed7e527e wgengine/magicsock: remove log allocation
This was the whole point but I goofed at the last line.
2020-03-24 08:14:47 -07:00
Brad Fitzpatrick
8454bbbda5 wgengine/magicsock: more logging improvements
* remove endpoint discovery noise when results unchanged
* consistently spell derp nodes as "derp-N"
* replace "127.3.3.40:" with "derp-" in CreateEndpoint log output
* stop early DERP setup before SetPrivateKey is called;
  it just generates log nosie
* fix stringification of peer ShortStrings (it had an old %x on it,
  rendering it garbage)
* describe why derp routes are changing, with one of:
  shared home, their home, our home, alt
2020-03-24 08:12:55 -07:00
Brad Fitzpatrick
64aff0db7b control/controlclient: add TODO to delete the UAPI method 2020-03-24 07:25:14 -07:00
Brad Fitzpatrick
7740cbd8d9 ipn: call SetNetInfoCallback later, in Start
It was being called back into ultimately from magicsock before there
was a control client.

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-23 22:19:40 -07:00
Brad Fitzpatrick
680311b3df wgengine/magicsock: fix few remaining logs without package prefix 2020-03-23 22:11:49 -07:00
Brad Fitzpatrick
c473927558 wgengine/magicsock: clean up, add, improve DERP logs 2020-03-23 21:57:58 -07:00
Brad Fitzpatrick
e749377a56 derp/derphttp: remove a redundant log message 2020-03-23 21:23:36 -07:00
Brad Fitzpatrick
1d3f45f9be derp/derphttp: ignore PeerGoneMessage in test 2020-03-23 14:13:49 -07:00
Brad Fitzpatrick
ea9310403d wgengine/magicsock: re-STUN on DERP connection death
Fixes #201
2020-03-23 13:19:33 -07:00
Brad Fitzpatrick
1ab5b31c4b derp, magicsock: send new "peer gone" frames when previous sender disconnects
Updates #150 (not yet enabled by default in magicsock)

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-22 21:00:47 -07:00
David Crawshaw
e60b433831 tailcfg: NetInfo.String: handle nil object without panicing
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-03-23 13:34:33 +11:00
Brad Fitzpatrick
b6f77cc48d wgengine/magicsock: return early, outdent in derpWriteChanOfAddr 2020-03-22 14:08:59 -07:00
Brad Fitzpatrick
8c4cef60f8 derp: wait for send goroutine to finish before returning from run
I saw a test flake due to the sender goroutine logging (ultimately to
t.Logf) after the server was closed.

This makes sure the all goroutines are cleaned up before Server.Close
returns.
2020-03-22 13:10:07 -07:00
Brad Fitzpatrick
521ad7b0fc derp: only flush writes to clients when we're out of things to write
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-22 08:01:25 -07:00
Brad Fitzpatrick
0a25abcdaa derp: remove TODO comment
It was done in bf704a5218
2020-03-22 07:54:50 -07:00
Brad Fitzpatrick
8519a1b29f derp: revert rename of pkt to sendMsg
New plan, sorry.

Most reverts 77921a31b1, except some doc changes.
2020-03-21 22:17:22 -07:00
Brad Fitzpatrick
c34b350efa derp: remove the mutex around and closing of send channel
Makes it less complicated.

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-21 22:00:04 -07:00
Brad Fitzpatrick
77921a31b1 derp: rename pkt to sendMsg, in prep for other types of writes
Updates #150
2020-03-21 20:34:49 -07:00
Brad Fitzpatrick
1453aecb44 derp: add sclient.done channel, simplify some context passing
This is mostly prep for a few future CLs, making sure we always have a
close-on-dead done channel available to select on when doing other
channel operations.
2020-03-21 18:28:34 -07:00
David Anderson
ea90780066 derp: specify type of the by-reason drop varz.
Signed-off-by: David Anderson <dave@natulte.net>
2020-03-20 15:53:04 -07:00
Brad Fitzpatrick
fd824df1fa derp: export metric for server's initial MemStats.Sys reading
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-20 15:37:36 -07:00
David Anderson
64b5248929 derp: sprinkle comments and docstrings.
Signed-off-by: David Anderson <dave@natulte.net>
2020-03-20 15:14:01 -07:00
David Anderson
58b8ebd290 derp: add per-reason packet drop counter.
In parallel with the summed counter for now, for dashboard migration.

Signed-off-by: David Anderson <dave@natulte.net>
2020-03-20 15:14:01 -07:00
David Anderson
1e031001db derp: move write timeout to package constant.
Signed-off-by: David Anderson <dave@natulte.net>
2020-03-20 15:14:01 -07:00
David Anderson
dbfc916273 derp: add short queues between reader and writer, drop on overload.
This avoids the server blocking on misbehaving or heavily contended
clients. We attempt to drop from the head of the queue to keep
overall queueing time lower.

Also:
 - fixes server->client keepalives, which weren't happening.
 - removes read rate-limiter, deferring instead to kernel-level
   global limiter/fair queuer.

Signed-off-by: David Anderson <dave@natulte.net>
2020-03-20 15:14:01 -07:00
Brad Fitzpatrick
dd31285ad4 wgengine/magicsock: send IPv6 using pconn6, if available
In prep for IPv6 support. Nothing should make it this far yet.
2020-03-20 14:30:12 -07:00
Brad Fitzpatrick
af277a6762 controlclient, magicsock: add debug knob to request IPv6 endpoints
Add opt-in method to request IPv6 endpoints from the control plane.
For now they should just be skipped. A previous version of this CL was
unconditional and reportedly had problems that I can't reproduce. So
make it a knob until the mystery is solved.

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-20 14:27:24 -07:00
Brad Fitzpatrick
221e7d7767 wgengine/magicsock: make log message include DERP port (node) 2020-03-20 13:51:20 -07:00
Brad Fitzpatrick
33bdcabf03 wgengine/magicsock: call stun callback w/ only valid part of STUN packet 2020-03-20 13:44:27 -07:00
David Crawshaw
13eed1e88b controlclient: remove common log on very quiet nodes
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-03-21 07:11:10 +11:00
Brad Fitzpatrick
f9cc4e8f53 tailcfg: restore MapRequest.IncludeIPv6 bool
Partially restores 0be475ba46
2020-03-20 08:13:47 -07:00
David Anderson
0be475ba46 Revert "tailcfg, controlclient, magicsock: request IPv6 endpoints, but ignore them"
Breaks something deep in wireguard or magicsock's brainstem, no packets at all
can flow. All received packets fail decryption with "invalid mac1".

This reverts commit 94024355ed.

Signed-off-by: David Anderson <dave@natulte.net>
2020-03-20 03:26:17 -07:00
Brad Fitzpatrick
f9184ad12b go.mod: update wireguard-go for https://github.com/tailscale/wireguard-go/pull/13 2020-03-19 22:46:36 -07:00
Brad Fitzpatrick
94024355ed tailcfg, controlclient, magicsock: request IPv6 endpoints, but ignore them
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-19 21:01:52 -07:00
David Anderson
12a6626a94 tsweb: use a ResponseWriter wrapper to log more accurately.
Also adds tests, because the logging handler is acquiring a fair
number of branches.

Signed-off-by: David Anderson <dave@natulte.net>
2020-03-19 20:11:07 -07:00
David Anderson
2e43cd3f95 testy: add a virtual clock helper for tests.
Signed-off-by: David Anderson <dave@natulte.net>
2020-03-19 20:11:07 -07:00
Brad Fitzpatrick
b1d5548fa7 tailcfg: make NodeKey.IsZero have a value receiver 2020-03-19 20:00:32 -07:00
Brad Fitzpatrick
51b669e4bd ipn: skip tailscaled UDP ports in service list 2020-03-19 19:56:02 -07:00
Brad Fitzpatrick
60ea635c6d wgengine/magicsock: delete inaccurate comment
I meant to include this in the earlier commit.
2020-03-19 19:48:02 -07:00
David Crawshaw
6ddbcab71e logtail: rename the unused CheckLogs to DrainLogs
Its semantics has changed slightly, this will let us use it to
drive batched logging in special circumstances.

Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-03-20 13:26:33 +11:00
David Crawshaw
51a12d1307 filch: a few minor comments
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-03-20 13:20:45 +11:00
Brad Fitzpatrick
a184e05290 wgengine/magicsock: listen on udp6, use it for STUN, report endpoint
More steps towards IPv6 transport.

We now send it to tailcontrol, which ignores it.

But it doesn't actually actually support IPv6 yet (outside of STUN).

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-19 13:54:38 -07:00
Brad Fitzpatrick
073bb8de80 control/controlclient: don't use Node as value type 2020-03-19 13:19:02 -07:00
Brad Fitzpatrick
7caa288213 wgengine/magicsock: rename pconn field to pconn4, in prep for pconn6 2020-03-19 08:49:30 -07:00
Brad Fitzpatrick
5fa825f057 go.mod, go.sum: update 2020-03-19 08:49:12 -07:00
David Crawshaw
addbdce296 wgengine, ipn: include number of active DERPs in status
Use this when making the ipn state transition from Starting to
Running. This way a network of quiet nodes with no active
handshaking will still transition to Active.

Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-03-19 17:55:16 +11:00
David Crawshaw
1ad78ce698 magicsock: reconnect to home DERP on key change
Typically the home DERP server is found and set on startup before
magicsock's SetPrivateKey can be called, so no DERP connection is
established. Make sure one is by kicking the home DERP tires in
SetPrivateKey.

Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-03-19 17:53:44 +11:00
David Crawshaw
455ba751d9 magicsock: start connection to HOME derp immediately
The code as written intended to do this, but it repeated the
comparison of derpNum and c.myDerp after c.myDerp had been
updated, so it never executed.

Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-03-19 17:36:30 +11:00
David Crawshaw
73cae4eb11 tailcfg, controlclient: standardize on wgcfg ShortString key printing
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-03-19 09:17:34 +11:00
David Crawshaw
acd14960f8 go.mod: bump wireguard-go
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-03-19 09:10:13 +11:00
Brad Fitzpatrick
14a2564ef0 go.mod: bump wireguard-go 2020-03-18 13:26:08 -07:00
Brad Fitzpatrick
19a1704abd netcheck: use best DERP server in past 5 minutes to avoid flip-flopping
Fixes #162
2020-03-18 13:07:13 -07:00
Brad Fitzpatrick
6de37f4cc0 tsweb: move some comments, add a TODO 2020-03-18 09:54:48 -07:00
David Anderson
df4636567f tsweb: adjust names and docs of the "handler with errors" functions.
Signed-off-by: David Anderson <dave@natulte.net>
2020-03-18 01:39:01 -07:00
David Crawshaw
131541c06d derp: deflake test
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-03-18 16:33:25 +11:00
David Anderson
52d9613b42 github: add license check to CI.
Signed-off-by: David Anderson <dave@natulte.net>
2020-03-17 21:34:44 -07:00
David Anderson
315a5e5355 scripts: add a license header checker.
Signed-off-by: David Anderson <dave@natulte.net>
2020-03-17 21:34:44 -07:00
David Anderson
3e2fadf872 version: add license header to input for generated file.
Signed-off-by: David Anderson <dave@natulte.net>
2020-03-17 21:34:44 -07:00
David Anderson
98eceae55e tsweb: add a Handler type.
Handler is like http.Handler, but returns errors. ErrHandler
converts back to an http.Handler, with added error handling
and logging.

Signed-off-by: David Anderson <dave@natulte.net>
2020-03-17 21:34:44 -07:00
Brad Fitzpatrick
f8d67bb591 portlist: ignore ports bound to localhost
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-17 20:55:45 -07:00
Brad Fitzpatrick
c706731dc7 tsweb: add copyright header
And fix an unlikely but potential crash.
2020-03-17 20:08:13 -07:00
David Anderson
a567c56971 tsweb: pull in tlog data structures from corp repo.
This is a prelude to having logging helpers in tsweb.

Signed-off-by: David Anderson <dave@natulte.net>
2020-03-17 17:21:50 -07:00
David Crawshaw
5a0822eefd controlclient, ipn: fix tests for new control param 2020-03-18 08:35:34 +11:00
Brad Fitzpatrick
e085aec8ef all: update to wireguard-go API changes
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-17 08:53:05 -07:00
David Anderson
dd14b658a2 version: bump again, for 0.97.0. 2020-03-16 21:16:18 -07:00
David Anderson
9ea445acd1 version: bump for 0.96.1 tag. 2020-03-16 20:35:35 -07:00
David Anderson
5758d8d48f Merge branch 'master' of github.com:tailscale/tailscale into HEAD 2020-03-16 18:37:38 -07:00
David Anderson
bf98913106 go.mod: bump wireguard-go version.
Signed-off-by: David Anderson <dave@natulte.net>
2020-03-16 18:36:30 -07:00
Brad Fitzpatrick
8f9fa6a842 logtail: minor style/simplification changes 2020-03-15 22:41:50 -07:00
Brad Fitzpatrick
8de67844bd cmd/tailscale: make failure message when tailscaled down less technical 2020-03-15 22:40:41 -07:00
Brad Fitzpatrick
5aafe0ee96 cmd/tailscale: don't crash on too many non-flag args 2020-03-15 22:27:36 -07:00
Brad Fitzpatrick
d348b94505 stun, stunner: clarify an error log message more
But two earlier changes mean this doesn't show up anymore anyway.
But if it does, it'll be a nice message.
2020-03-15 22:19:45 -07:00
David Crawshaw
1b2be3f1c8 controlclient: test peer keepalive directive
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-03-14 14:11:07 -05:00
David Crawshaw
8712164a0a controlclient: use per-peer KeepAlive signal
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-03-14 14:11:03 -05:00
David Crawshaw
290f83e9f6 tailcfg: fix test
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-03-14 11:03:00 -05:00
David Crawshaw
7a57ab1793 tailcfg: add a per-peer KeepAlive field 2020-03-14 10:56:52 -05:00
David Anderson
ea0836dce9 cmd/tailscaled: remove default user/group from systemd. 2020-03-13 23:58:38 -07:00
Brad Fitzpatrick
120273d7f6 portlist: document, clean up, fix an open fd spike, optimize a bit
I noticed portlist when looking at some profiles and hadn't looked at
the code much before. This is a first pass over it. It allocates a
fair bit. More love remains, but this does a bit:

name       old time/op    new time/op    delta
GetList-8    9.92ms ± 8%    9.64ms ±12%     ~     (p=0.247 n=10+10)

name       old alloc/op   new alloc/op   delta
GetList-8     931kB ± 0%     869kB ± 0%   -6.70%  (p=0.000 n=10+10)

name       old allocs/op  new allocs/op  delta
GetList-8     4.59k ± 0%     3.69k ± 1%  -19.71%  (p=0.000 n=10+10)

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-13 21:06:41 -07:00
Brad Fitzpatrick
6c3820e8c4 cmd/tailscaled: rename relaynode reference in defaults file comment 2020-03-13 14:38:04 -07:00
Brad Fitzpatrick
19cc4f8b8e control/controlclient: remove a number literal in string slice offset 2020-03-13 09:48:15 -07:00
Brad Fitzpatrick
42e98d4edc Quiet two little log annoyances. 2020-03-13 09:42:09 -07:00
Brad Fitzpatrick
db2436c7ff wgengine/magicsock: don't interrupt endpoint updates, merge all mutex into one
Before, endpoint updates were constantly being interrupted and resumed
on Linux due to tons of LinkChange messages from over-zealous Linux
netlink messages (from router_linux.go)

Now that endpoint updates are fast and bounded in time anyway, just
let them run to completion, but note that another needs to be
scheduled after.

Now logs went from pages of noise to just:

root@taildoc:~# grep -i -E 'stun|endpoint update' log
2020/03/13 08:51:29 magicsock.Conn: starting endpoint update (initial)
2020/03/13 08:51:30 magicsock.Conn.ReSTUN: endpoint update active, need another later ("link-change-minor")
2020/03/13 08:51:31 magicsock.Conn: starting endpoint update (link-change-minor)
2020/03/13 08:51:31 magicsock.Conn.ReSTUN: endpoint update active, need another later ("link-change-minor")
2020/03/13 08:51:33 magicsock.Conn: starting endpoint update (link-change-minor)
2020/03/13 08:51:33 magicsock.Conn.ReSTUN: endpoint update active, need another later ("link-change-minor")
2020/03/13 08:51:35 magicsock.Conn: starting endpoint update (link-change-minor)
2020/03/13 08:51:35 magicsock.Conn.ReSTUN: endpoint update active, need another later ("link-change-minor")

Or, seen in another run:

2020/03/13 08:45:41 magicsock.Conn: starting endpoint update (periodic)
2020/03/13 08:46:09 magicsock.Conn: starting endpoint update (periodic)
2020/03/13 08:46:21 magicsock.Conn: starting endpoint update (link-change-major)
2020/03/13 08:46:37 magicsock.Conn: starting endpoint update (periodic)
2020/03/13 08:47:05 magicsock.Conn: starting endpoint update (periodic)

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-13 09:34:11 -07:00
Brad Fitzpatrick
db31550854 wgengine: don't Reconfig on boring link changes
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-13 07:45:59 -07:00
Avery Pennarun
7dd63abaed tailcfg.NetInfo: add a .String() renderer.
For pretty printing purposes in logs.
2020-03-13 01:29:47 -04:00
Avery Pennarun
b23cb11eaf ipn: Prefs.String(): print the current derp setting. 2020-03-13 00:43:19 -04:00
David Anderson
aeb88864e0 ipn: don't clobber netinfo in Start(). 2020-03-12 21:39:01 -07:00
Avery Pennarun
8b8e3f08a0 Fix staticcheck complaint. 2020-03-12 23:33:51 -04:00
Avery Pennarun
b4897e7de8 controlclient/netmap: write our own b.ConciseDiffFrom(a) function.
This removes the need for go-cmp, which is extremely bloaty so we had
to leave it out of iOS. As a result, we had also left it out of macOS,
and so we didn't print netmap diffs at all on darwin-based platforms.
Oops.

As a bonus, the output format of the new function is way better.

Minor oddity: because I used the dumbest possible diff algorithm, the
sort order is a bit dumb. We print all "removed" lines and then print
all "added" lines, rather than doing the usual diff-like thing of
interspersing them. This probably doesn't matter (maybe it's an
improvement).
2020-03-12 23:01:08 -04:00
Avery Pennarun
96bb05ce2f controlclient: reformat netmap.Concise() and add DERP server info.
The .Concise() view had grown hard to read over time. Originally, we
assumed a peer almost always had just one endpoint and one-or-more
allowedips. With magicsock, we now almost always have multiple
endpoints per peer. And empirically, almost every peer has only one
allowedip.

Change their order so we can line up allowedips vertically. Also do
some tweaking to make multiple endpoints easier to read.

While we're here, add a column to show the home DERP server of each
peer, if any.
2020-03-12 22:29:24 -04:00
Avery Pennarun
f2e2ffa423 controlclient: log the entire netmap up to every 5 minutes.
We log it once upon receiving the first copy of the map, then
subsequently when a new one appears, but only if we haven't logged one
less than 5 minutes ago.

This avoids overly cluttering the log (as we did before, logging the
netmap every time one appeared, which could be hundreds of lines every
few seconds), but still gives the log enough context to help in
diagnosing problems retroactively.
2020-03-12 22:28:11 -04:00
Brad Fitzpatrick
b9c6d3ceb8 netcheck: work behind UDP-blocked networks again, add tests
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-12 14:49:06 -07:00
Brad Fitzpatrick
a87ee4168a stunner: quiet a harmless log warning 2020-03-12 14:14:23 -07:00
Brad Fitzpatrick
bc73dcf204 wgengine/magicsock: don't block in Send waiting for derphttp.Send
Fixes #137
Updates #109
Updates #162
Updates #163

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-12 12:19:12 -07:00
Brad Fitzpatrick
8807913be9 wgengine/magicsock: wait for previous DERP goroutines to end before new ones
Updates #109 (hopefully fixes, will wait for graphs to be happy)

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-12 12:19:12 -07:00
Brad Fitzpatrick
eff6dcdb4e wgengine/magicsock: log more about why we're re-STUNing 2020-03-12 12:09:25 -07:00
David Crawshaw
5ad947c761 cmd/derper: set a write timeout
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-03-12 14:42:48 -04:00
David Crawshaw
72dbf26f63 derp: test that client a->b and a->c relaying do not interfere
Without the recent write deadline introduction, this test fails.

They still do interfere, but the interference is now bound by
the write deadline. Many improvements are possible.

Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-03-12 14:42:48 -04:00
David Crawshaw
e838b3fb59 derp: use a write timeout when sending to clients
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-03-12 14:42:48 -04:00
David Crawshaw
3df1b97ea8 derp: do not treat failure to relay as the fault of the sender
If Alice attempts to send a packet to Bob and the DERP server
encounters an error on the socket to Bob, we should not disconnect
Alice for that.

Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-03-12 14:42:48 -04:00
David Crawshaw
43aa8595dd derp: introduce Conn interface
This lets us test with something other than a net.Conn.

Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-03-12 14:42:48 -04:00
David Crawshaw
41ac4a79d6 net/nettest: new package with net-like testing primitives
This is a lot like wiring up a local UDP socket, read and write
deadlines work. The big difference is the Block feature, which
lets you stop the packet flow without breaking the connection.
This lets you emulate broken sockets and test timeouts actually
work.

Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-03-12 14:42:48 -04:00
Brad Fitzpatrick
52c0cb12fb stunner: return wrapped error (currently unused) 2020-03-12 11:21:19 -07:00
Brad Fitzpatrick
b4d02a251a syncs: add new package for extra sync types 2020-03-12 11:13:33 -07:00
David Crawshaw
57f220656c ipn: search for ErrStateNotExist with errors.Is
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-03-12 08:44:24 -04:00
Avery Pennarun
40c6f952c5 Merge branch 'master' of github.com:tailscale/tailscale into HEAD
* 'master' of github.com:tailscale/tailscale:
  netcheck: fix data races for staggler STUN packets arriving after GetReport
  wgengine/magicsock: add a pointer value for logging
  netcheck: ignore IPv4 STUN failures if we saw at least one reply
  netcheck: ignore IPv6 STUN failures
  derp: add clients_replaced counter
  version: bump OSS version datestamp.
2020-03-11 21:01:18 -04:00
Avery Pennarun
509247bf42 tailscale, tailscaled: update safesocket port number.
This makes them able to connect to each other on Windows.
2020-03-11 21:00:25 -04:00
Brad Fitzpatrick
afc3479d04 netcheck: fix data races for staggler STUN packets arriving after GetReport
Fixes #179
2020-03-11 15:35:12 -07:00
Brad Fitzpatrick
b3ddf51a15 wgengine/magicsock: add a pointer value for logging
Updates #109

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-11 15:12:19 -07:00
Brad Fitzpatrick
0d3f42e1d8 netcheck: ignore IPv4 STUN failures if we saw at least one reply
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-11 13:57:23 -07:00
Brad Fitzpatrick
ed7e088729 netcheck: ignore IPv6 STUN failures
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-11 12:44:59 -07:00
Brad Fitzpatrick
4fd29349b9 derp: add clients_replaced counter
Updates #109
2020-03-11 11:55:43 -07:00
David Anderson
b364a871bf version: bump OSS version datestamp. 2020-03-11 10:47:37 -07:00
David Anderson
72d9e1d633 go.mod: bump wireguard-go version. 2020-03-11 10:32:50 -07:00
Brad Fitzpatrick
b0f8931d26 wgengine/magicsock: make a test signature a bit more explicit 2020-03-11 09:51:33 -07:00
David Crawshaw
7ec54e0064 wgengine/magicsock: remove TODO
The TODO above derphttp.NewClient suggests it does network I/O,
but the derphttp client connects lazily and so creating one is
very cheap.

Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-03-11 12:17:37 -04:00
David Crawshaw
af58cfc476 go.mod: bump wireguard-go version
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-03-11 11:29:14 -04:00
Brad Fitzpatrick
01b4bec33f stunner: re-do how Stunner works
It used to make assumptions based on having Anycast IPs that are super
near. Now we're intentionally going to a bunch of different distant
IPs to measure latency.

Also, optimize how the hairpin detection works. No need to STUN on
that socket. Just use that separate socket for sending, once we know
the other UDP4 socket's endpoint. The trick is: make our test probe
also a STUN packet, so it fits through magicsock's existing STUN
routing.

This drops netcheck from ~5 seconds to ~250-500ms.

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-11 08:08:48 -07:00
David Anderson
4affea2691 go.mod: bump wireguard-go version.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-03-10 18:00:37 -07:00
David Anderson
77af7e5436 wgengine/magicsock: mark test logfunc as a helper.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-03-10 18:00:37 -07:00
David Anderson
7eda3af034 wgengine/magicsock: clean up derp http servers on shutdown.
Failure to do this leads to fd exhaustion at -count=10000,
and increasingly poor execution north of -count=100.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-03-10 18:00:37 -07:00
David Anderson
d651715528 wgengine/magicsock: synchronize test STUN shutdown.
Failure to do so triggers either a data race or a panic
in the testing package, due to racey use of t.Logf.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-03-10 18:00:37 -07:00
David Anderson
86baf60bd4 wgengine/magicsock: synchronize epUpdate cleanup on shutdown.
Signed-off-by: David Anderson <danderson@tailscale.com>
2020-03-10 18:00:37 -07:00
Brad Fitzpatrick
023df9239e Move linkstate boring change filtering to magicsock
So we can at least re-STUN on boring updates.

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-10 12:50:03 -07:00
David Anderson
592fec7606 wgengine/magicsock: move device close to uncursed portion of test.
Device close used to suffer from deadlocks, but no longer.

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-03-10 11:57:57 -07:00
Brad Fitzpatrick
a265d7cbff wgengine/magicsock: in STUN-disabled test mode, let endpoint discovery proceed 2020-03-10 11:35:43 -07:00
Brad Fitzpatrick
5c1e443d34 wgengine/monitor: don't call LinkChange when interfaces look unchanged
Basically, don't trust the OS-level link monitor to only tell you
interesting things. Sanity check it.

Also, move the interfaces package into the net directory now that we
have it.
2020-03-10 11:03:19 -07:00
Brad Fitzpatrick
39c0ae1dba derp/derpmap: new DERP config package, merge netcheck into magicsock more
Fixes #153
Updates #162
Updates #163

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2020-03-10 10:37:25 -07:00
Brad Fitzpatrick
bd0e20f351 net/dnscache: ignore annoying staticcheck check 2020-03-09 22:12:22 -07:00
Brad Fitzpatrick
d44325295e net/dnscache: initialize the single Resolver more directly 2020-03-09 21:05:01 -07:00
Brad Fitzpatrick
d07146aafb go.mod, go.sum: update 2020-03-09 21:01:08 -07:00
David Crawshaw
5f2a17482b ipn: when enforcing defaults, set UsePacketFilter=true
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2020-03-09 14:58:20 -04:00
268 changed files with 27923 additions and 7289 deletions

View File

@@ -3,7 +3,7 @@ name: Darwin-Cross
on:
push:
branches:
- master
- main
pull_request:
branches:
- '*'
@@ -16,10 +16,10 @@ jobs:
steps:
- name: Set up Go 1.13
- name: Set up Go
uses: actions/setup-go@v1
with:
go-version: 1.13
go-version: 1.14
id: go
- name: Check out code into the Go module directory

View File

@@ -3,7 +3,7 @@ name: FreeBSD-Cross
on:
push:
branches:
- master
- main
pull_request:
branches:
- '*'
@@ -16,10 +16,10 @@ jobs:
steps:
- name: Set up Go 1.13
- name: Set up Go
uses: actions/setup-go@v1
with:
go-version: 1.13
go-version: 1.14
id: go
- name: Check out code into the Go module directory

View File

@@ -3,7 +3,7 @@ name: OpenBSD-Cross
on:
push:
branches:
- master
- main
pull_request:
branches:
- '*'
@@ -16,10 +16,10 @@ jobs:
steps:
- name: Set up Go 1.13
- name: Set up Go
uses: actions/setup-go@v1
with:
go-version: 1.13
go-version: 1.14
id: go
- name: Check out code into the Go module directory

View File

@@ -3,7 +3,7 @@ name: Windows-Cross
on:
push:
branches:
- master
- main
pull_request:
branches:
- '*'
@@ -16,10 +16,10 @@ jobs:
steps:
- name: Set up Go 1.13
- name: Set up Go
uses: actions/setup-go@v1
with:
go-version: 1.13
go-version: 1.14
id: go
- name: Check out code into the Go module directory

40
.github/workflows/license.yml vendored Normal file
View File

@@ -0,0 +1,40 @@
name: license
on:
push:
branches:
- main
pull_request:
branches:
- '*'
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Set up Go
uses: actions/setup-go@v1
with:
go-version: 1.14
- name: Check out code
uses: actions/checkout@v1
- name: Run license checker
run: ./scripts/check_license_headers.sh .
- uses: k0kubun/action-slack@v2.0.0
with:
payload: |
{
"attachments": [{
"text": "${{ job.status }}: ${{ github.workflow }} <https://github.com/${{ github.repository }}/commit/${{ github.sha }}/checks|${{ env.COMMIT_DATE }} #${{ env.COMMIT_NUMBER_OF_DAY }}> " +
"(<https://github.com/${{ github.repository }}/commit/${{ github.sha }}|" + "${{ github.sha }}".substring(0, 10) + ">) " +
"of ${{ github.repository }}@" + "${{ github.ref }}".split('/').reverse()[0] + " by ${{ github.event.head_commit.committer.name }}",
"color": "danger"
}]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
if: failure() && github.event_name == 'push'

View File

@@ -3,7 +3,7 @@ name: Linux
on:
push:
branches:
- master
- main
pull_request:
branches:
- '*'
@@ -16,10 +16,10 @@ jobs:
steps:
- name: Set up Go 1.13
- name: Set up Go
uses: actions/setup-go@v1
with:
go-version: 1.13
go-version: 1.14
id: go
- name: Check out code into the Go module directory

48
.github/workflows/linux32.yml vendored Normal file
View File

@@ -0,0 +1,48 @@
name: Linux 32-bit
on:
push:
branches:
- main
pull_request:
branches:
- '*'
jobs:
build:
runs-on: ubuntu-latest
if: "!contains(github.event.head_commit.message, '[ci skip]')"
steps:
- name: Set up Go
uses: actions/setup-go@v1
with:
go-version: 1.14
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@v1
- name: Basic build
run: GOARCH=386 go build ./cmd/...
- name: Run tests on linux
run: GOARCH=386 go test ./...
- uses: k0kubun/action-slack@v2.0.0
with:
payload: |
{
"attachments": [{
"text": "${{ job.status }}: ${{ github.workflow }} <https://github.com/${{ github.repository }}/commit/${{ github.sha }}/checks|${{ env.COMMIT_DATE }} #${{ env.COMMIT_NUMBER_OF_DAY }}> " +
"(<https://github.com/${{ github.repository }}/commit/${{ github.sha }}|" + "${{ github.sha }}".substring(0, 10) + ">) " +
"of ${{ github.repository }}@" + "${{ github.ref }}".split('/').reverse()[0] + " by ${{ github.event.head_commit.committer.name }}",
"color": "danger"
}]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
if: failure() && github.event_name == 'push'

View File

@@ -3,7 +3,7 @@ name: staticcheck
on:
push:
branches:
- master
- main
pull_request:
branches:
- '*'
@@ -13,19 +13,22 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Set up Go 1.13
- name: Set up Go
uses: actions/setup-go@v1
with:
go-version: 1.13
go-version: 1.14
- name: Check out code
uses: actions/checkout@v1
- name: Run go vet
run: go vet ./...
- name: Print staticcheck version
run: go run honnef.co/go/tools/cmd/staticcheck -version
- name: Run staticcheck
run: go run honnef.co/go/tools/cmd/staticcheck -- ./...
run: "go run honnef.co/go/tools/cmd/staticcheck -- $(go list ./... | grep -v tempfork)"
- uses: k0kubun/action-slack@v2.0.0
with:

View File

@@ -2,7 +2,26 @@
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
FROM golang:1.13-alpine AS build-env
# This Dockerfile includes all the tailscale binaries.
#
# To build the Dockerfile:
#
# $ docker build -t tailscale:tailscale .
#
# To run the tailscaled agent:
#
# $ docker run -d --name=tailscaled -v /var/lib:/var/lib -v /dev/net/tun:/dev/net/tun --network=host --privileged tailscale:tailscale tailscaled
#
# To then log in:
#
# $ docker exec tailscaled tailscale up
#
# To see status:
#
# $ docker exec tailscaled tailscale status
FROM golang:1.14-alpine AS build-env
WORKDIR /go/src/tailscale
@@ -15,5 +34,5 @@ COPY . .
RUN go install -v ./cmd/...
FROM alpine:3.11
RUN apk add --no-cache ca-certificates iptables
RUN apk add --no-cache ca-certificates iptables iproute2
COPY --from=build-env /go/bin/* /usr/local/bin/

7
Makefile Normal file
View File

@@ -0,0 +1,7 @@
usage:
echo "See Makefile"
check: staticcheck
staticcheck:
go run honnef.co/go/tools/cmd/staticcheck -- $$(go list ./... | grep -v tempfork)

View File

@@ -23,10 +23,10 @@ https://pkgs.tailscale.com .
go install tailscale.com/cmd/tailscale{,d}
```
We only support the latest Go release and any Go beta or release
candidate builds (currently Go 1.13.x or Go 1.14) in module mode. It
might work in earlier Go versions or in GOPATH mode, but we're making
no effort to keep those working.
We only guarantee to support the latest Go release and any Go beta or
release candidate builds (currently Go 1.14) in module mode. It might
work in earlier Go versions or in GOPATH mode, but we're making no
effort to keep those working.
## Bugs

View File

@@ -1,4 +1,4 @@
// Copyright 2019 Tailscale & AUTHORS. All rights reserved.
// Copyright (c) 2019 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
@@ -9,20 +9,39 @@
package atomicfile // import "tailscale.com/atomicfile"
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"runtime"
)
// WriteFile writes data to filename+some suffix, then renames it
// into filename.
func WriteFile(filename string, data []byte, perm os.FileMode) error {
tmpname := filename + ".new.tmp"
if err := ioutil.WriteFile(tmpname, data, perm); err != nil {
return fmt.Errorf("%#v: %v", tmpname, err)
func WriteFile(filename string, data []byte, perm os.FileMode) (err error) {
f, err := ioutil.TempFile(filepath.Dir(filename), filepath.Base(filename)+".tmp")
if err != nil {
return err
}
if err := os.Rename(tmpname, filename); err != nil {
return fmt.Errorf("%#v->%#v: %v", tmpname, filename, err)
tmpName := f.Name()
defer func() {
if err != nil {
f.Close()
os.Remove(tmpName)
}
}()
if _, err := f.Write(data); err != nil {
return err
}
return nil
if runtime.GOOS != "windows" {
if err := f.Chmod(perm); err != nil {
return err
}
}
if err := f.Sync(); err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
return os.Rename(tmpName, filename)
}

264
cmd/cloner/cloner.go Normal file
View File

@@ -0,0 +1,264 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Cloner is a tool to automate the creation of a Clone method.
//
// The result of the Clone method aliases no memory that can be edited
// with the original.
//
// This tool makes lots of implicit assumptions about the types you feed it.
// In particular, it can only write relatively "shallow" Clone methods.
// That is, if a type contains another named struct type, cloner assumes that
// named type will also have a Clone method.
package main
import (
"bytes"
"flag"
"fmt"
"go/ast"
"go/format"
"go/token"
"go/types"
"io/ioutil"
"log"
"os"
"strings"
"golang.org/x/tools/go/packages"
)
var (
flagTypes = flag.String("type", "", "comma-separated list of types; required")
flagOutput = flag.String("output", "", "output file; required")
flagBuildTags = flag.String("tags", "", "compiler build tags to apply")
)
func main() {
log.SetFlags(0)
log.SetPrefix("cloner: ")
flag.Parse()
if len(*flagTypes) == 0 {
flag.Usage()
os.Exit(2)
}
typeNames := strings.Split(*flagTypes, ",")
cfg := &packages.Config{
Mode: packages.NeedTypes | packages.NeedTypesInfo | packages.NeedSyntax | packages.NeedName,
Tests: false,
}
if *flagBuildTags != "" {
cfg.BuildFlags = []string{"-tags=" + *flagBuildTags}
}
pkgs, err := packages.Load(cfg, ".")
if err != nil {
log.Fatal(err)
}
if len(pkgs) != 1 {
log.Fatalf("wrong number of packages: %d", len(pkgs))
}
pkg := pkgs[0]
buf := new(bytes.Buffer)
imports := make(map[string]struct{})
for _, typeName := range typeNames {
found := false
for _, file := range pkg.Syntax {
//var fbuf bytes.Buffer
//ast.Fprint(&fbuf, pkg.Fset, file, nil)
//fmt.Println(fbuf.String())
for _, d := range file.Decls {
decl, ok := d.(*ast.GenDecl)
if !ok || decl.Tok != token.TYPE {
continue
}
for _, s := range decl.Specs {
spec, ok := s.(*ast.TypeSpec)
if !ok || spec.Name.Name != typeName {
continue
}
typeNameObj := pkg.TypesInfo.Defs[spec.Name]
typ, ok := typeNameObj.Type().(*types.Named)
if !ok {
continue
}
pkg := typeNameObj.Pkg()
gen(buf, imports, typeName, typ, pkg)
}
found = true
}
}
if !found {
log.Fatalf("could not find type %s", typeName)
}
}
contents := new(bytes.Buffer)
fmt.Fprintf(contents, header, *flagTypes, pkg.Name)
fmt.Fprintf(contents, "import (\n")
for s := range imports {
fmt.Fprintf(contents, "\t%q\n", s)
}
fmt.Fprintf(contents, ")\n\n")
contents.Write(buf.Bytes())
out, err := format.Source(contents.Bytes())
if err != nil {
log.Fatalf("%s, in source:\n%s", err, contents.Bytes())
}
output := *flagOutput
if output == "" {
flag.Usage()
os.Exit(2)
}
if err := ioutil.WriteFile(output, out, 0666); err != nil {
log.Fatal(err)
}
}
const header = `// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Code generated by tailscale.com/cmd/cloner -type %s; DO NOT EDIT.
package %s
`
func gen(buf *bytes.Buffer, imports map[string]struct{}, name string, typ *types.Named, thisPkg *types.Package) {
pkgQual := func(pkg *types.Package) string {
if thisPkg == pkg {
return ""
}
imports[pkg.Path()] = struct{}{}
return pkg.Name()
}
importedName := func(t types.Type) string {
return types.TypeString(t, pkgQual)
}
switch t := typ.Underlying().(type) {
case *types.Struct:
_ = t
name := typ.Obj().Name()
fmt.Fprintf(buf, "// Clone makes a deep copy of %s.\n", name)
fmt.Fprintf(buf, "// The result aliases no memory with the original.\n")
fmt.Fprintf(buf, "func (src *%s) Clone() *%s {\n", name, name)
writef := func(format string, args ...interface{}) {
fmt.Fprintf(buf, "\t"+format+"\n", args...)
}
writef("if src == nil {")
writef("\treturn nil")
writef("}")
writef("dst := new(%s)", name)
writef("*dst = *src")
for i := 0; i < t.NumFields(); i++ {
fname := t.Field(i).Name()
ft := t.Field(i).Type()
if !containsPointers(ft) {
continue
}
if named, _ := ft.(*types.Named); named != nil && !hasBasicUnderlying(ft) {
writef("dst.%s = *src.%s.Clone()", fname, fname)
continue
}
switch ft := ft.Underlying().(type) {
case *types.Slice:
if containsPointers(ft.Elem()) {
n := importedName(ft.Elem())
writef("dst.%s = make([]%s, len(src.%s))", fname, n, fname)
writef("for i := range dst.%s {", fname)
if _, isPtr := ft.Elem().(*types.Pointer); isPtr {
writef("\tdst.%s[i] = src.%s[i].Clone()", fname, fname)
} else {
writef("\tdst.%s[i] = *src.%s[i].Clone()", fname, fname)
}
writef("}")
} else {
writef("dst.%s = append(src.%s[:0:0], src.%s...)", fname, fname, fname)
}
case *types.Pointer:
if named, _ := ft.Elem().(*types.Named); named != nil && containsPointers(ft.Elem()) {
writef("dst.%s = src.%s.Clone()", fname, fname)
continue
}
n := importedName(ft.Elem())
writef("if dst.%s != nil {", fname)
writef("\tdst.%s = new(%s)", fname, n)
writef("\t*dst.%s = *src.%s", fname, fname)
if containsPointers(ft.Elem()) {
writef("\t" + `panic("TODO pointers in pointers")`)
}
writef("}")
case *types.Map:
writef("if dst.%s != nil {", fname)
writef("\tdst.%s = map[%s]%s{}", fname, importedName(ft.Key()), importedName(ft.Elem()))
if sliceType, isSlice := ft.Elem().(*types.Slice); isSlice {
n := importedName(sliceType.Elem())
writef("\tfor k := range src.%s {", fname)
// use zero-length slice instead of nil to ensure
// the key is always copied.
writef("\t\tdst.%s[k] = append([]%s{}, src.%s[k]...)", fname, n, fname)
writef("\t}")
} else if containsPointers(ft.Elem()) {
writef("\t\t" + `panic("TODO map value pointers")`)
} else {
writef("\tfor k, v := range src.%s {", fname)
writef("\t\tdst.%s[k] = v", fname)
writef("\t}")
}
writef("}")
case *types.Struct:
writef(`panic("TODO struct %s")`, fname)
default:
writef(`panic(fmt.Sprintf("TODO: %T", ft))`)
}
}
writef("return dst")
fmt.Fprintf(buf, "}\n\n")
}
}
func hasBasicUnderlying(typ types.Type) bool {
switch typ.Underlying().(type) {
case *types.Slice, *types.Map:
return true
default:
return false
}
}
func containsPointers(typ types.Type) bool {
switch typ.String() {
case "time.Time":
// time.Time contains a pointer that does not need copying
return false
case "inet.af/netaddr.IP":
return false
}
switch ft := typ.Underlying().(type) {
case *types.Array:
return containsPointers(ft.Elem())
case *types.Chan:
return true
case *types.Interface:
return true // a little too broad
case *types.Map:
return true
case *types.Pointer:
return true
case *types.Slice:
return true
case *types.Struct:
for i := 0; i < ft.NumFields(); i++ {
if containsPointers(ft.Field(i).Type()) {
return true
}
}
}
return false
}

View File

@@ -20,6 +20,7 @@ import (
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/tailscale/wireguard-go/wgcfg"
@@ -29,7 +30,7 @@ import (
"tailscale.com/derp/derphttp"
"tailscale.com/logpolicy"
"tailscale.com/metrics"
"tailscale.com/stun"
"tailscale.com/net/stun"
"tailscale.com/tsweb"
"tailscale.com/types/key"
)
@@ -40,9 +41,10 @@ var (
configPath = flag.String("c", "", "config file path")
certDir = flag.String("certdir", tsweb.DefaultCertDir("derper-certs"), "directory to store LetsEncrypt certs, if addr's port is :443")
hostname = flag.String("hostname", "derp.tailscale.com", "LetsEncrypt host name, if addr's port is :443")
mbps = flag.Int("mbps", 5, "Mbps (mebibit/s) per-client rate limit; 0 means unlimited")
logCollection = flag.String("logcollection", "", "If non-empty, logtail collection to log to")
runSTUN = flag.Bool("stun", false, "also run a STUN server")
meshPSKFile = flag.String("mesh-psk-file", defaultMeshPSKFile(), "if non-empty, path to file containing the mesh pre-shared key file. It should contain some hex string; whitespace is trimmed.")
meshWith = flag.String("mesh-with", "", "optional comma-separated list of hostnames to mesh with; the server's own hostname can be in the list")
)
type config struct {
@@ -119,8 +121,21 @@ func main() {
letsEncrypt := tsweb.IsProd443(*addr)
s := derp.NewServer(key.Private(cfg.PrivateKey), log.Printf)
if *mbps != 0 {
s.BytesPerSecond = (*mbps << 20) / 8
if *meshPSKFile != "" {
b, err := ioutil.ReadFile(*meshPSKFile)
if err != nil {
log.Fatal(err)
}
key := strings.TrimSpace(string(b))
if matched, _ := regexp.MatchString(`(?i)^[0-9a-f]{64,}$`, key); !matched {
log.Fatalf("key in %s must contain 64+ hex digits", *meshPSKFile)
}
s.SetMeshKey(key)
log.Printf("DERP mesh key configured")
}
if err := startMesh(s); err != nil {
log.Fatalf("startMesh: %v", err)
}
expvar.Publish("derp", s.ExpVar())
@@ -170,7 +185,7 @@ func main() {
}
httpsrv.TLSConfig = certManager.TLSConfig()
go func() {
err := http.ListenAndServe(":80", certManager.HTTPHandler(tsweb.Port80Handler{mux}))
err := http.ListenAndServe(":80", certManager.HTTPHandler(tsweb.Port80Handler{Main: mux}))
if err != nil {
if err != http.ErrServerClosed {
log.Fatal(err)
@@ -189,20 +204,30 @@ func main() {
func debugHandler(s *derp.Server) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.RequestURI == "/debug/check" {
err := s.ConsistencyCheck()
if err != nil {
http.Error(w, err.Error(), 500)
} else {
io.WriteString(w, "derp.Server ConsistencyCheck okay")
}
return
}
f := func(format string, args ...interface{}) { fmt.Fprintf(w, format, args...) }
f(`<html><body>
<h1>DERP debug</h1>
<ul>
`)
f("<li><b>Hostname:</b> %v</li>\n", *hostname)
f("<li><b>Rate Limit:</b> %v Mbps</li>\n", *mbps)
f("<li><b>Uptime:</b> %v</li>\n", tsweb.Uptime())
f("<li><b>Mesh Key:</b> %v</li>\n", s.HasMeshKey())
f(`<li><a href="/debug/vars">/debug/vars</a> (Go)</li>
<li><a href="/debug/varz">/debug/varz</a> (Prometheus)</li>
<li><a href="/debug/pprof/">/debug/pprof/</a></li>
<li><a href="/debug/pprof/goroutine?debug=1">/debug/pprof/goroutine</a> (collapsed)</li>
<li><a href="/debug/pprof/goroutine?debug=2">/debug/pprof/goroutine</a> (full)</li>
<li><a href="/debug/check">/debug/check</a> internal consistency check</li>
<ul>
</html>
`)
@@ -273,7 +298,7 @@ func serveSTUN() {
}
}
var validProdHostname = regexp.MustCompile(`^derp(\d+|\-\w+)?\.tailscale\.com\.?$`)
var validProdHostname = regexp.MustCompile(`^derp([^.]*)\.tailscale\.com\.?$`)
func prodAutocertHostPolicy(_ context.Context, host string) error {
if validProdHostname.MatchString(host) {
@@ -281,3 +306,16 @@ func prodAutocertHostPolicy(_ context.Context, host string) error {
}
return errors.New("invalid hostname")
}
func defaultMeshPSKFile() string {
try := []string{
"/home/derp/keys/derp-mesh.key",
filepath.Join(os.Getenv("HOME"), "keys", "derp-mesh.key"),
}
for _, p := range try {
if _, err := os.Stat(p); err == nil {
return p
}
}
return ""
}

View File

@@ -17,10 +17,11 @@ func TestProdAutocertHostPolicy(t *testing.T) {
{"derp.tailscale.com", true},
{"derp.tailscale.com.", true},
{"derp1.tailscale.com", true},
{"derp1b.tailscale.com", true},
{"derp2.tailscale.com", true},
{"derp02.tailscale.com", true},
{"derp-nyc.tailscale.com", true},
{"derpfoo.tailscale.com", false},
{"derpfoo.tailscale.com", true},
{"derp02.bar.tailscale.com", false},
{"example.net", false},
}

45
cmd/derper/mesh.go Normal file
View File

@@ -0,0 +1,45 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"errors"
"fmt"
"log"
"strings"
"tailscale.com/derp"
"tailscale.com/derp/derphttp"
"tailscale.com/types/key"
"tailscale.com/types/logger"
)
func startMesh(s *derp.Server) error {
if *meshWith == "" {
return nil
}
if !s.HasMeshKey() {
return errors.New("--mesh-with requires --mesh-psk-file")
}
for _, host := range strings.Split(*meshWith, ",") {
if err := startMeshWithHost(s, host); err != nil {
return err
}
}
return nil
}
func startMeshWithHost(s *derp.Server, host string) error {
logf := logger.WithPrefix(log.Printf, fmt.Sprintf("mesh(%q): ", host))
c, err := derphttp.NewClient(s.PrivateKey(), "https://"+host+"/derp", logf)
if err != nil {
return err
}
c.MeshKey = s.MeshKey()
add := func(k key.Public) { s.AddPacketForwarder(k, c) }
remove := func(k key.Public) { s.RemovePacketForwarder(k, c) }
go c.RunWatchConnectionLoop(s.PublicKey(), add, remove)
return nil
}

View File

@@ -0,0 +1,175 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// microproxy proxies incoming HTTPS connections to another
// destination. Instead of managing its own TLS certificates, it
// borrows issued certificates and keys from an autocert directory.
package main
import (
"crypto/tls"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"net/url"
"path/filepath"
"sync"
"time"
"tailscale.com/logpolicy"
"tailscale.com/tsweb"
)
var (
addr = flag.String("addr", ":4430", "server address")
certdir = flag.String("certdir", "", "directory to borrow LetsEncrypt certificates from")
hostname = flag.String("hostname", "", "hostname to serve")
logCollection = flag.String("logcollection", "", "If non-empty, logtail collection to log to")
nodeExporter = flag.String("node-exporter", "http://localhost:9100", "URL of the local prometheus node exporter")
goVarsURL = flag.String("go-vars-url", "http://localhost:8383/debug/vars", "URL of a local Go server's /debug/vars endpoint")
)
func main() {
flag.Parse()
if *logCollection != "" {
logpolicy.New(*logCollection)
}
ne, err := url.Parse(*nodeExporter)
if err != nil {
log.Fatalf("Couldn't parse URL %q: %v", *nodeExporter, err)
}
proxy := httputil.NewSingleHostReverseProxy(ne)
proxy.FlushInterval = time.Second
if _, err = url.Parse(*goVarsURL); err != nil {
log.Fatalf("Couldn't parse URL %q: %v", *goVarsURL, err)
}
mux := tsweb.NewMux(http.HandlerFunc(debugHandler))
mux.Handle("/metrics", tsweb.Protected(proxy))
mux.Handle("/varz", tsweb.Protected(tsweb.StdHandler(&goVarsHandler{*goVarsURL}, log.Printf)))
ch := &certHolder{
hostname: *hostname,
path: filepath.Join(*certdir, *hostname),
}
httpsrv := &http.Server{
Addr: *addr,
Handler: mux,
TLSConfig: &tls.Config{
GetCertificate: ch.GetCertificate,
},
}
if err := httpsrv.ListenAndServeTLS("", ""); err != nil && err != http.ErrServerClosed {
log.Fatal(err)
}
}
type goVarsHandler struct {
url string
}
func promPrint(w io.Writer, prefix string, obj map[string]interface{}) {
for k, i := range obj {
if prefix != "" {
k = prefix + "_" + k
}
switch v := i.(type) {
case map[string]interface{}:
promPrint(w, k, v)
case float64:
fmt.Fprintf(w, "%s %f\n", k, v)
default:
fmt.Fprintf(w, "# Skipping key %q, unhandled type %T\n", k, v)
}
}
}
func (h *goVarsHandler) ServeHTTPReturn(w http.ResponseWriter, r *http.Request) error {
resp, err := http.Get(h.url)
if err != nil {
return tsweb.Error(http.StatusInternalServerError, "fetch failed", err)
}
defer resp.Body.Close()
var mon map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&mon); err != nil {
return tsweb.Error(http.StatusInternalServerError, "fetch failed", err)
}
w.WriteHeader(http.StatusOK)
promPrint(w, "", mon)
return nil
}
// certHolder loads and caches a TLS certificate from disk, reloading
// it every hour.
type certHolder struct {
hostname string // only hostname allowed in SNI
path string // path of certificate+key combined PEM file
mu sync.Mutex
cert *tls.Certificate // cached parsed cert+key
loaded time.Time
}
func (c *certHolder) GetCertificate(ch *tls.ClientHelloInfo) (*tls.Certificate, error) {
if ch.ServerName != c.hostname {
return nil, fmt.Errorf("wrong client SNI %q", ch.ServerName)
}
c.mu.Lock()
defer c.mu.Unlock()
if time.Since(c.loaded) > time.Hour {
if err := c.loadLocked(); err != nil {
log.Printf("Reloading cert %q: %v", c.path, err)
// continue anyway, we might be able to serve off the stale cert.
}
}
return c.cert, nil
}
// load reloads the TLS certificate and key from disk. Caller must
// hold mu.
func (c *certHolder) loadLocked() error {
bs, err := ioutil.ReadFile(c.path)
if err != nil {
return fmt.Errorf("reading %q: %v", c.path, err)
}
cert, err := tls.X509KeyPair(bs, bs)
if err != nil {
return fmt.Errorf("parsing %q: %v", c.path, err)
}
c.cert = &cert
c.loaded = time.Now()
return nil
}
// debugHandler serves a page with links to tsweb-managed debug URLs
// at /debug/.
func debugHandler(w http.ResponseWriter, r *http.Request) {
f := func(format string, args ...interface{}) { fmt.Fprintf(w, format, args...) }
f(`<html><body>
<h1>microproxy debug</h1>
<ul>
`)
f("<li><b>Hostname:</b> %v</li>\n", *hostname)
f("<li><b>Uptime:</b> %v</li>\n", tsweb.Uptime())
f(`<li><a href="/debug/vars">/debug/vars</a> (Go)</li>
<li><a href="/debug/varz">/debug/varz</a> (Prometheus)</li>
<li><a href="/debug/pprof/">/debug/pprof/</a></li>
<li><a href="/debug/pprof/goroutine?debug=1">/debug/pprof/goroutine</a> (collapsed)</li>
<li><a href="/debug/pprof/goroutine?debug=2">/debug/pprof/goroutine</a> (full)</li>
<ul>
</html>
`)
}

View File

@@ -31,17 +31,28 @@ func parseFiles(s string) (map[string]string, error) {
return ret, nil
}
func parseEmptyDirs(s string) []string {
// strings.Split("", ",") would return []string{""}, which is not suitable:
// this would create an empty dir record with path "", breaking the package
if s == "" {
return nil
}
return strings.Split(s, ",")
}
func main() {
out := getopt.StringLong("out", 'o', "", "output file to write")
goarch := getopt.StringLong("arch", 'a', "amd64", "GOARCH this package is for")
pkgType := getopt.StringLong("type", 't', "deb", "type of package to build (deb or rpm)")
files := getopt.StringLong("files", 'F', "", "comma-separated list of files in src:dst form")
configFiles := getopt.StringLong("configs", 'C', "", "like --files, but for files marked as user-editable config files")
emptyDirs := getopt.StringLong("emptydirs", 'E', "", "comma-separated list of empty directories")
version := getopt.StringLong("version", 0, "0.0.0", "version of the package")
postinst := getopt.StringLong("postinst", 0, "", "debian postinst script path")
prerm := getopt.StringLong("prerm", 0, "", "debian prerm script path")
postrm := getopt.StringLong("postrm", 0, "", "debian postrm script path")
replaces := getopt.StringLong("replaces", 0, "", "package which this package replaces, if any")
depends := getopt.StringLong("depends", 0, "", "comma-separated list of packages this package depends on")
getopt.Parse()
filesMap, err := parseFiles(*files)
@@ -52,6 +63,7 @@ func main() {
if err != nil {
log.Fatalf("Parsing --configs: %v", err)
}
emptyDirList := parseEmptyDirs(*emptyDirs)
info := nfpm.WithDefaults(&nfpm.Info{
Name: "tailscale",
Arch: *goarch,
@@ -62,8 +74,9 @@ func main() {
Homepage: "https://www.tailscale.com",
License: "MIT",
Overridables: nfpm.Overridables{
Files: filesMap,
ConfigFiles: configsMap,
EmptyFolders: emptyDirList,
Files: filesMap,
ConfigFiles: configsMap,
Scripts: nfpm.Scripts{
PostInstall: *postinst,
PreRemove: *prerm,
@@ -72,6 +85,9 @@ func main() {
},
})
if len(*depends) != 0 {
info.Overridables.Depends = strings.Split(*depends, ",")
}
if *replaces != "" {
info.Overridables.Replaces = []string{*replaces}
info.Overridables.Conflicts = []string{*replaces}

View File

@@ -1,14 +0,0 @@
/*.tar.gz
/*.deb
/*.rpm
/*.spec
/pkgver
debian/changelog
debian/debhelper-build-stamp
debian/files
debian/*.log
debian/*.substvars
debian/*.debhelper
debian/tailscale-relay
/tailscale-relay/
/tailscale-relay-*

View File

@@ -1 +0,0 @@
rm -f debian/changelog *~ debian/*~

View File

@@ -1,13 +0,0 @@
exec >&2
read -r package <package
rm -f *~ .*~ \
debian/*~ debian/changelog debian/debhelper-build-stamp \
debian/*.log debian/files debian/*.substvars debian/*.debhelper \
*.tar.gz *.deb *.rpm *.spec pkgver relaynode *.exe
[ -n "$package" ] && rm -rf "debian/$package"
for d in */.stamp; do
if [ -e "$d" ]; then
dir=$(dirname "$d")
rm -rf "$dir"
fi
done

View File

@@ -1,10 +0,0 @@
exec >&2
dir=${1%/*}
redo-ifchange "$S/$dir/package" "$S/oss/version/short.txt"
read -r package <"$S/$dir/package"
read -r version <"$S/oss/version/short.txt"
arch=$(dpkg --print-architecture)
redo-ifchange "$dir/${package}_$arch.deb"
rm -f "$dir/${package}"_*_"$arch.deb"
ln -sf "${package}_$arch.deb" "$dir/${package}_${version}_$arch.deb"

View File

@@ -1 +0,0 @@
Tailscale IPN relay daemon.

View File

@@ -1,5 +0,0 @@
redo-ifchange ../../../version/short.txt gen-changelog
(
cd ..
debian/gen-changelog
) >$3

View File

@@ -1 +0,0 @@
9

View File

@@ -1,14 +0,0 @@
Source: tailscale-relay
Section: net
Priority: extra
Maintainer: Avery Pennarun <apenwarr@tailscale.com>
Build-Depends: debhelper (>= 10.2.5), dh-systemd (>= 1.5)
Standards-Version: 3.9.2
Homepage: https://tailscale.com/
Vcs-Git: https://github.com/tailscale/tailscale
Vcs-Browser: https://github.com/tailscale/tailscale
Package: tailscale-relay
Architecture: any
Depends: ${shlibs:Depends}, ${misc:Depends}
Description: Traffic relay node for Tailscale IPN

View File

@@ -1,11 +0,0 @@
Format: http://svn.debian.org/wsvn/dep/web/deps/dep5.mdwn?op=file&rev=173
Upstream-Name: tailscale-relay
Upstream-Contact: Avery Pennarun <apenwarr@tailscale.com>
Source: https://github.com/tailscale/tailscale/
Files: *
Copyright: © 2019 Tailscale Inc. <info@tailscale.com>
License: Proprietary
*
* Copyright 2019 Tailscale Inc. All rights reserved.
*

View File

@@ -1,25 +0,0 @@
#!/bin/sh
read junk pkgname <debian/control
read shortver <../../version/short.txt
git log --pretty='format:'"$pkgname"' (SHA:%H) unstable; urgency=low
* %s
-- %aN <%aE> %aD
' . |
python -Sc '
import os, re, subprocess, sys
first = True
def Describe(g):
global first
if first:
s = sys.argv[1]
first = False
else:
sha = g.group(1)
s = subprocess.check_output(["git", "describe", "--always", "--", sha]).strip().decode("utf-8")
return re.sub(r"^\D*", "", s)
print(re.sub(r"SHA:([0-9a-f]+)", Describe, sys.stdin.read()))
' "$shortver"

View File

@@ -1,3 +0,0 @@
relaynode /usr/sbin
tailscale-login /usr/sbin
taillogin /usr/sbin

View File

@@ -1,8 +0,0 @@
#DEBHELPER#
f=/var/lib/tailscale/relay.conf
if ! [ -e "$f" ]; then
echo
echo "Note: Run tailscale-login to configure $f." >&2
echo
fi

View File

@@ -1,10 +0,0 @@
#!/usr/bin/make -f
DESTDIR=debian/tailscale-relay
override_dh_auto_test:
override_dh_auto_install:
mkdir -p "${DESTDIR}/etc/default"
cp tailscale-relay.defaults "${DESTDIR}/etc/default/tailscale-relay"
%:
dh $@ --with=systemd

View File

@@ -1,12 +0,0 @@
[Unit]
Description=Traffic relay node for Tailscale IPN
After=network.target
ConditionPathExists=/var/lib/tailscale/relay.conf
[Service]
EnvironmentFile=/etc/default/tailscale-relay
ExecStart=/usr/sbin/relaynode --config=/var/lib/tailscale/relay.conf --tun=wg0 $PORT $FLAGS
Restart=on-failure
[Install]
WantedBy=multi-user.target

View File

@@ -1,21 +0,0 @@
exec >&2
dir=${1%/*}
redo-ifchange "$S/oss/version/short.txt" "$S/$dir/package" "$dir/debtmp.dir"
read -r package <"$S/$dir/package"
read -r version <"$S/oss/version/short.txt"
arch=$(dpkg --print-architecture)
(
cd "$S/$dir"
git ls-files debian | xargs redo-ifchange debian/changelog
)
cp -a "$S/$dir/debian" "$dir/debtmp/"
rm -f "$dir/debtmp/debian/$package.debhelper.log"
rm -f "$dir/${package}_${version}_${arch}.deb"
(
cd "$dir/debtmp" &&
debian/rules build &&
fakeroot debian/rules binary
)
mv "$dir/${package}_${version}_${arch}.deb" "$3"

View File

@@ -1,20 +0,0 @@
# Generate a directory tree suitable for forming a tarball of
# this package.
exec >&2
dir=${1%/*}
outdir=$PWD/${1%.dir}
rm -rf "$outdir"
mkdir "$outdir"
touch $outdir/.stamp
sfiles="
tailscale-login
debian/*.service
*.defaults
"
ofiles="
relaynode
../taillogin/taillogin
"
redo-ifchange "$outdir/.stamp"
(cd "$S/$dir" && redo-ifchange $sfiles && cp $sfiles "$outdir/")
(cd "$dir" && redo-ifchange $ofiles && cp $ofiles "$outdir/")

View File

@@ -1,15 +0,0 @@
exec >&2
dir=${1%/*}
pkg=${1##*/}
pkg=${pkg%.rpm}
redo-ifchange "$S/oss/version/short.txt" "$dir/$pkg.tar.gz" "$dir/$pkg.spec"
read -r pkgver junk <"$S/oss/version/short.txt"
machine=$(uname -m)
rpmbase=$HOME/rpmbuild
mkdir -p "$rpmbase/SOURCES/"
cp "$dir/$pkg.tar.gz" "$rpmbase/SOURCES/"
rm -f "$rpmbase/RPMS/$machine/$pkg-$pkgver.$machine.rpm"
rpmbuild -bb "$dir/$pkg.spec"
mv "$rpmbase/RPMS/$machine/$pkg-$pkgver.$machine.rpm" $3

View File

@@ -1,7 +0,0 @@
redo-ifchange "$S/$1.in" "$S/oss/version/short.txt"
read -r pkgver junk <"$S/oss/version/short.txt"
basever=${pkgver%-*}
subver=${pkgver#*-}
sed -e "s/Version: 0.00$/Version: $basever/" \
-e "s/Release: 0$/Release: $subver/" \
<"$S/$1.in" >"$3"

View File

@@ -1,8 +0,0 @@
exec >&2
xdir=${1%.tar.gz}
base=${xdir##*/}
updir=${xdir%/*}
redo-ifchange "$xdir.dir"
OUT="$PWD/$3"
cd "$updir" && tar -czvf "$OUT" --exclude "$base/.stamp" "$base"

View File

@@ -1,15 +0,0 @@
# Build packages for customer distribution.
dir=${1%/*}
cd "$dir"
targets="tarball"
if which dh_clean fakeroot dpkg >/dev/null; then
targets="$targets deb"
else
echo "Skipping debian packages: debhelper and/or dpkg build tools missing." >&2
fi
if which rpm >/dev/null; then
targets="$targets rpm"
else
echo "Skipping rpm packages: rpm build tools missing." >&2
fi
redo-ifchange $targets

View File

@@ -1 +0,0 @@
/relaynode

View File

@@ -1,17 +0,0 @@
# Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
# Build with: docker build -t tailcontrol-alpine .
# Run with: docker run --cap-add=NET_ADMIN --device=/dev/net/tun:/dev/net/tun -it tailcontrol-alpine
FROM debian:stretch-slim
RUN apt-get update && apt-get -y install iproute2 iptables
RUN apt-get -y install ca-certificates
RUN apt-get -y install nginx-light
COPY relaynode /
# tailcontrol -tun=wg0 -dbdir=$HOME/taildb >> tailcontrol.log 2>&1 &
CMD ["/relaynode", "-R", "--config", "relay.conf"]

View File

@@ -1 +0,0 @@
redo-ifchange build

View File

@@ -1,3 +0,0 @@
exec >&2
redo-ifchange Dockerfile relaynode
docker build -t tailscale .

View File

@@ -1,2 +0,0 @@
redo-ifchange ../relaynode
cp ../relaynode $3

View File

@@ -1,10 +0,0 @@
#!/bin/sh
# Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
set -e
redo-ifchange build
docker run --cap-add=NET_ADMIN \
--device=/dev/net/tun:/dev/net/tun \
-it tailscale

View File

@@ -1 +0,0 @@
tailscale-relay

View File

@@ -1,239 +0,0 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Relaynode is the old Linux Tailscale daemon.
//
// Deprecated: this program will be soon deleted. The replacement is
// cmd/tailscaled.
package main // import "tailscale.com/cmd/relaynode"
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/pprof"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/apenwarr/fixconsole"
"github.com/google/go-cmp/cmp"
"github.com/klauspost/compress/zstd"
"github.com/pborman/getopt/v2"
"github.com/tailscale/wireguard-go/wgcfg"
"tailscale.com/atomicfile"
"tailscale.com/control/controlclient"
"tailscale.com/logpolicy"
"tailscale.com/version"
"tailscale.com/wgengine"
"tailscale.com/wgengine/filter"
"tailscale.com/wgengine/magicsock"
)
func main() {
err := fixconsole.FixConsoleIfNeeded()
if err != nil {
log.Printf("fixConsoleOutput: %v\n", err)
}
config := getopt.StringLong("config", 'f', "", "path to config file")
server := getopt.StringLong("server", 's', "https://login.tailscale.com", "URL to tailcontrol server")
listenport := getopt.Uint16Long("port", 'p', magicsock.DefaultPort, "WireGuard port (0=autoselect)")
tunname := getopt.StringLong("tun", 0, "wg0", "tunnel interface name")
alwaysrefresh := getopt.BoolLong("always-refresh", 0, "force key refresh at startup")
fake := getopt.BoolLong("fake", 0, "fake tunnel+routing instead of tuntap")
nuroutes := getopt.BoolLong("no-single-routes", 'N', "disallow (non-subnet) routes to single nodes")
rroutes := getopt.BoolLong("remote-routes", 'R', "allow routing subnets to remote nodes")
droutes := getopt.BoolLong("default-routes", 'D', "allow default route on remote node")
routes := getopt.StringLong("routes", 0, "", "list of IP ranges this node can relay")
debug := getopt.StringLong("debug", 0, "", "Address of debug server")
getopt.Parse()
if len(getopt.Args()) > 0 {
log.Fatalf("too many non-flag arguments: %#v", getopt.Args()[0])
}
uflags := controlclient.UFlagsHelper(!*nuroutes, *rroutes, *droutes)
if *config == "" {
log.Fatal("no --config file specified")
}
if *tunname == "" {
log.Printf("Warning: no --tun device specified; routing disabled.\n")
}
pol := logpolicy.New("tailnode.log.tailscale.io")
logf := wgengine.RusagePrefixLog(log.Printf)
// The wgengine takes a wireguard configuration produced by the
// controlclient, and runs the actual tunnels and packets.
var e wgengine.Engine
if *fake {
e, err = wgengine.NewFakeUserspaceEngine(logf, *listenport)
} else {
e, err = wgengine.NewUserspaceEngine(logf, *tunname, *listenport)
}
if err != nil {
log.Fatalf("Error starting wireguard engine: %v\n", err)
}
e = wgengine.NewWatchdog(e)
// Default filter blocks everything, until Start() is called.
e.SetFilter(filter.NewAllowNone())
var lastNetMap *controlclient.NetworkMap
statusFunc := func(new controlclient.Status) {
if new.URL != "" {
fmt.Fprintf(os.Stderr, "To authenticate, visit:\n\n\t%s\n\n", new.URL)
return
}
if new.Err != "" {
log.Print(new.Err)
return
}
if new.Persist != nil {
if err := saveConfig(*config, *new.Persist); err != nil {
log.Println(err)
}
}
if m := new.NetMap; m != nil {
if lastNetMap != nil {
s1 := strings.Split(lastNetMap.Concise(), "\n")
s2 := strings.Split(new.NetMap.Concise(), "\n")
logf("netmap diff:\n%v\n", cmp.Diff(s1, s2))
}
lastNetMap = m
if m.Equal(&controlclient.NetworkMap{}) {
return
}
log.Printf("packet filter: %v\n", m.PacketFilter)
e.SetFilter(filter.New(m.PacketFilter))
wgcfg, err := m.WGCfg(uflags, m.DNS)
if err != nil {
log.Fatalf("Error getting wg config: %v\n", err)
}
err = e.Reconfig(wgcfg, m.DNSDomains)
if err != nil {
log.Fatalf("Error reconfiguring engine: %v\n", err)
}
}
}
cfg, err := loadConfig(*config)
if err != nil {
log.Fatal(err)
}
hi := controlclient.NewHostinfo()
hi.FrontendLogID = pol.PublicID.String()
hi.BackendLogID = pol.PublicID.String()
if *routes != "" {
for _, routeStr := range strings.Split(*routes, ",") {
cidr, err := wgcfg.ParseCIDR(routeStr)
if err != nil {
log.Fatalf("--routes: not an IP range: %s", routeStr)
}
hi.RoutableIPs = append(hi.RoutableIPs, *cidr)
}
}
c, err := controlclient.New(controlclient.Options{
Persist: cfg,
ServerURL: *server,
Hostinfo: hi,
NewDecompressor: func() (controlclient.Decompressor, error) {
return zstd.NewReader(nil)
},
KeepAlive: true,
})
c.SetStatusFunc(statusFunc)
if err != nil {
log.Fatal(err)
}
lf := controlclient.LoginDefault
if *alwaysrefresh {
lf |= controlclient.LoginInteractive
}
c.Login(nil, lf)
// Print the wireguard status when we get an update.
e.SetStatusCallback(func(s *wgengine.Status, err error) {
if err != nil {
log.Fatalf("Wireguard engine status error: %v\n", err)
}
var ss []string
for _, p := range s.Peers {
if p.LastHandshake.IsZero() {
ss = append(ss, "x")
} else {
ss = append(ss, fmt.Sprintf("%d/%d", p.RxBytes, p.TxBytes))
}
}
logf("v%v peers: %v\n", version.LONG, strings.Join(ss, " "))
c.UpdateEndpoints(0, s.LocalAddrs)
})
if *debug != "" {
go runDebugServer(*debug)
}
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt)
signal.Notify(sigCh, syscall.SIGTERM)
<-sigCh
logf("signal received, exiting")
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
e.Close()
pol.Shutdown(ctx)
}
func loadConfig(path string) (cfg controlclient.Persist, err error) {
b, err := ioutil.ReadFile(path)
if os.IsNotExist(err) {
log.Printf("config %s does not exist", path)
return controlclient.Persist{}, nil
}
if err := json.Unmarshal(b, &cfg); err != nil {
return controlclient.Persist{}, fmt.Errorf("load config: %v", err)
}
return cfg, nil
}
func saveConfig(path string, cfg controlclient.Persist) error {
b, err := json.MarshalIndent(cfg, "", "\t")
if err != nil {
return fmt.Errorf("save config: %v", err)
}
if err := atomicfile.WriteFile(path, b, 0666); err != nil {
return fmt.Errorf("save config: %v", err)
}
return nil
}
func runDebugServer(addr string) {
mux := http.NewServeMux()
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
srv := http.Server{
Addr: addr,
Handler: mux,
}
if err := srv.ListenAndServe(); err != nil {
log.Fatal(err)
}
}

View File

@@ -0,0 +1 @@
# placeholder to work around redo bug

View File

@@ -1,9 +0,0 @@
exec >&2
dir=${2%/*}
redo-ifchange "$S/$dir/package" "$S/oss/version/short.txt"
read -r package <"$S/$dir/package"
read -r pkgver <"$S/oss/version/short.txt"
machine=$(uname -m)
redo-ifchange "$dir/$package.rpm"
rm -f "$dir/${package}"-*."$machine.rpm"
ln -sf "$package.rpm" "$dir/$package-$pkgver.$machine.rpm"

View File

@@ -1,4 +0,0 @@
#!/bin/sh
cfg=/var/lib/tailscale/relay.conf
dir=$(dirname "$0")
"$dir/taillogin" --config="$cfg"

View File

@@ -1,8 +0,0 @@
# Set the port to listen on for incoming VPN packets.
# Remote nodes will automatically be informed about the new port number,
# but you might want to configure this in order to set external firewall
# settings.
PORT="--port=41641"
# Extra flags you might want to pass to relaynode.
FLAGS=""

View File

@@ -1,40 +0,0 @@
Name: tailscale-relay
Version: 0.00
Release: 0
Summary: Traffic relay node for Tailscale
Group: Network
License: Proprietary
URL: https://tailscale.com/
Vendor: Tailscale Inc.
#Source: https://github.com/tailscale/tailscale
Source0: tailscale-relay.tar.gz
#Prefix: %{_prefix}
Packager: Avery Pennarun <apenwarr@tailscale.com>
BuildRoot: %{_tmppath}/%{name}-root
%description
Traffic relay node for Tailscale.
%prep
%setup -n tailscale-relay
%build
%install
D=$RPM_BUILD_ROOT
[ "$D" = "/" -o -z "$D" ] && exit 99
rm -rf "$D"
mkdir -p $D/usr/sbin $D/lib/systemd/system $D/etc/default $D/etc/tailscale
cp taillogin tailscale-login relaynode $D/usr/sbin
cp tailscale-relay.service $D/lib/systemd/system/
cp tailscale-relay.defaults $D/etc/default/tailscale-relay
%clean
%files
%defattr(-,root,root)
%config(noreplace) /etc/default/tailscale-relay
/lib/systemd/system/tailscale-relay.service
/usr/sbin/taillogin
/usr/sbin/tailscale-login
/usr/sbin/relaynode

View File

@@ -1,7 +0,0 @@
dir=${1%/*}
redo-ifchange "$S/$dir/package" "$S/oss/version/short.txt"
read -r package <"$S/$dir/package"
read -r version <"$S/oss/version/short.txt"
redo-ifchange "$dir/$package.tar.gz"
rm -f "$dir/$package"-*.tar.gz
ln -sf "$package.tar.gz" "$dir/$package-$version.tar.gz"

View File

@@ -1,99 +0,0 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The taillogin command, invoked via the tailscale-login shell script, is shipped
// with the current (old) Linux client, to log in to Tailscale on a Linux box.
//
// Deprecated: this will be deleted, to be replaced by cmd/tailscale.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"github.com/pborman/getopt/v2"
"tailscale.com/atomicfile"
"tailscale.com/control/controlclient"
"tailscale.com/logpolicy"
)
func main() {
config := getopt.StringLong("config", 'f', "", "path to config file")
server := getopt.StringLong("server", 's', "https://login.tailscale.com", "URL to tailgate server")
getopt.Parse()
if len(getopt.Args()) > 0 {
log.Fatal("too many non-flag arguments")
}
if *config == "" {
log.Fatal("no --config file specified")
}
pol := logpolicy.New("tailnode.log.tailscale.io")
defer pol.Close()
cfg, err := loadConfig(*config)
if err != nil {
log.Fatal(err)
}
hi := controlclient.NewHostinfo()
hi.FrontendLogID = pol.PublicID.String()
hi.BackendLogID = pol.PublicID.String()
done := make(chan struct{}, 1)
c, err := controlclient.New(controlclient.Options{
Persist: cfg,
ServerURL: *server,
Hostinfo: hi,
})
if err != nil {
log.Fatal(err)
}
c.SetStatusFunc(func(new controlclient.Status) {
if new.URL != "" {
fmt.Fprintf(os.Stderr, "To authenticate, visit:\n\n\t%s\n\n", new.URL)
return
}
if new.Err != "" {
log.Print(new.Err)
return
}
if new.Persist != nil {
if err := saveConfig(*config, *new.Persist); err != nil {
log.Println(err)
}
}
if new.NetMap != nil {
done <- struct{}{}
}
})
c.Login(nil, 0)
<-done
log.Printf("Success.\n")
}
func loadConfig(path string) (cfg controlclient.Persist, err error) {
b, err := ioutil.ReadFile(path)
if os.IsNotExist(err) {
log.Printf("config %s does not exist", path)
return controlclient.Persist{}, nil
}
if err := json.Unmarshal(b, &cfg); err != nil {
return controlclient.Persist{}, fmt.Errorf("load config: %v", err)
}
return cfg, nil
}
func saveConfig(path string, cfg controlclient.Persist) error {
b, err := json.MarshalIndent(cfg, "", "\t")
if err != nil {
return fmt.Errorf("save config: %v", err)
}
if err := atomicfile.WriteFile(path, b, 0666); err != nil {
return fmt.Errorf("save config: %v", err)
}
return nil
}

123
cmd/tailscale/cli/cli.go Normal file
View File

@@ -0,0 +1,123 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package cli contains the cmd/tailscale CLI code in a package that can be included
// in other wrapper binaries such as the Mac and Windows clients.
package cli
import (
"context"
"flag"
"log"
"net"
"os"
"os/signal"
"runtime"
"strings"
"syscall"
"github.com/peterbourgon/ff/v2/ffcli"
"tailscale.com/ipn"
"tailscale.com/paths"
"tailscale.com/safesocket"
)
// ActLikeCLI reports whether a GUI application should act like the
// CLI based on os.Args, GOOS, the context the process is running in
// (pty, parent PID), etc.
func ActLikeCLI() bool {
if len(os.Args) < 2 {
return false
}
switch os.Args[1] {
case "up", "status", "netcheck", "version",
"-V", "--version", "-h", "--help":
return true
}
return false
}
// Run runs the CLI. The args do not include the binary name.
func Run(args []string) error {
if len(args) == 1 && (args[0] == "-V" || args[0] == "--version") {
args = []string{"version"}
}
rootfs := flag.NewFlagSet("tailscale", flag.ExitOnError)
rootfs.StringVar(&rootArgs.socket, "socket", paths.DefaultTailscaledSocket(), "path to tailscaled's unix socket")
rootCmd := &ffcli.Command{
Name: "tailscale",
ShortUsage: "tailscale subcommand [flags]",
ShortHelp: "The easiest, most secure way to use WireGuard.",
LongHelp: strings.TrimSpace(`
This CLI is still under active development. Commands and flags will
change in the future.
`),
Subcommands: []*ffcli.Command{
upCmd,
netcheckCmd,
statusCmd,
versionCmd,
},
FlagSet: rootfs,
Exec: func(context.Context, []string) error { return flag.ErrHelp },
}
if err := rootCmd.Parse(args); err != nil {
return err
}
err := rootCmd.Run(context.Background())
if err == flag.ErrHelp {
return nil
}
return err
}
var rootArgs struct {
socket string
}
func connect(ctx context.Context) (net.Conn, *ipn.BackendClient, context.Context, context.CancelFunc) {
c, err := safesocket.Connect(rootArgs.socket, 41112)
if err != nil {
if runtime.GOOS != "windows" && rootArgs.socket == "" {
log.Fatalf("--socket cannot be empty")
}
log.Fatalf("Failed to connect to connect to tailscaled. (safesocket.Connect: %v)\n", err)
}
clientToServer := func(b []byte) {
ipn.WriteMsg(c, b)
}
ctx, cancel := context.WithCancel(ctx)
go func() {
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, syscall.SIGINT, syscall.SIGTERM)
<-interrupt
c.Close()
cancel()
}()
bc := ipn.NewBackendClient(log.Printf, clientToServer)
return c, bc, ctx, cancel
}
// pump receives backend messages on conn and pushes them into bc.
func pump(ctx context.Context, bc *ipn.BackendClient, conn net.Conn) {
defer conn.Close()
for ctx.Err() == nil {
msg, err := ipn.ReadMsg(conn)
if err != nil {
if ctx.Err() != nil {
return
}
log.Printf("ReadMsg: %v\n", err)
break
}
bc.GotNotifyMsg(msg)
}
}

View File

@@ -0,0 +1,162 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cli
import (
"context"
"encoding/json"
"flag"
"fmt"
"log"
"os"
"sort"
"strings"
"time"
"github.com/peterbourgon/ff/v2/ffcli"
"tailscale.com/derp/derpmap"
"tailscale.com/net/dnscache"
"tailscale.com/net/netcheck"
"tailscale.com/tailcfg"
"tailscale.com/types/logger"
)
var netcheckCmd = &ffcli.Command{
Name: "netcheck",
ShortUsage: "netcheck",
ShortHelp: "Print an analysis of local network conditions",
Exec: runNetcheck,
FlagSet: (func() *flag.FlagSet {
fs := flag.NewFlagSet("netcheck", flag.ExitOnError)
fs.StringVar(&netcheckArgs.format, "format", "", `output format; empty (for human-readable), "json" or "json-line"`)
fs.DurationVar(&netcheckArgs.every, "every", 0, "if non-zero, do an incremental report with the given frequency")
fs.BoolVar(&netcheckArgs.verbose, "verbose", false, "verbose logs")
return fs
})(),
}
var netcheckArgs struct {
format string
every time.Duration
verbose bool
}
func runNetcheck(ctx context.Context, args []string) error {
c := &netcheck.Client{
DNSCache: dnscache.Get(),
}
if netcheckArgs.verbose {
c.Logf = logger.WithPrefix(log.Printf, "netcheck: ")
c.Verbose = true
} else {
c.Logf = logger.Discard
}
if strings.HasPrefix(netcheckArgs.format, "json") {
fmt.Fprintln(os.Stderr, "# Warning: this JSON format is not yet considered a stable interface")
}
dm := derpmap.Prod()
for {
t0 := time.Now()
report, err := c.GetReport(ctx, dm)
d := time.Since(t0)
if netcheckArgs.verbose {
c.Logf("GetReport took %v; err=%v", d.Round(time.Millisecond), err)
}
if err != nil {
log.Fatalf("netcheck: %v", err)
}
if err := printReport(dm, report); err != nil {
return err
}
if netcheckArgs.every == 0 {
return nil
}
time.Sleep(netcheckArgs.every)
}
}
func printReport(dm *tailcfg.DERPMap, report *netcheck.Report) error {
var j []byte
var err error
switch netcheckArgs.format {
case "":
break
case "json":
j, err = json.MarshalIndent(report, "", "\t")
case "json-line":
j, err = json.Marshal(report)
default:
return fmt.Errorf("unknown output format %q", netcheckArgs.format)
}
if err != nil {
return err
}
if j != nil {
j = append(j, '\n')
os.Stdout.Write(j)
return nil
}
fmt.Printf("\nReport:\n")
fmt.Printf("\t* UDP: %v\n", report.UDP)
if report.GlobalV4 != "" {
fmt.Printf("\t* IPv4: yes, %v\n", report.GlobalV4)
} else {
fmt.Printf("\t* IPv4: (no addr found)\n")
}
if report.GlobalV6 != "" {
fmt.Printf("\t* IPv6: yes, %v\n", report.GlobalV6)
} else if report.IPv6 {
fmt.Printf("\t* IPv6: (no addr found)\n")
} else {
fmt.Printf("\t* IPv6: no\n")
}
fmt.Printf("\t* MappingVariesByDestIP: %v\n", report.MappingVariesByDestIP)
fmt.Printf("\t* HairPinning: %v\n", report.HairPinning)
fmt.Printf("\t* PortMapping: %v\n", portMapping(report))
// When DERP latency checking failed,
// magicsock will try to pick the DERP server that
// most of your other nodes are also using
if len(report.RegionLatency) == 0 {
fmt.Printf("\t* Nearest DERP: unknown (no response to latency probes)\n")
} else {
fmt.Printf("\t* Nearest DERP: %v (%v)\n", report.PreferredDERP, dm.Regions[report.PreferredDERP].RegionCode)
fmt.Printf("\t* DERP latency:\n")
var rids []int
for rid := range dm.Regions {
rids = append(rids, rid)
}
sort.Ints(rids)
for _, rid := range rids {
d, ok := report.RegionLatency[rid]
var latency string
if ok {
latency = d.Round(time.Millisecond / 10).String()
}
fmt.Printf("\t\t- %v, %3s = %s\n", rid, dm.Regions[rid].RegionCode, latency)
}
}
return nil
}
func portMapping(r *netcheck.Report) string {
if !r.AnyPortMappingChecked() {
return "not checked"
}
var got []string
if r.UPnP.EqualBool(true) {
got = append(got, "UPnP")
}
if r.PMP.EqualBool(true) {
got = append(got, "NAT-PMP")
}
if r.PCP.EqualBool(true) {
got = append(got, "PCP")
}
return strings.Join(got, ", ")
}

172
cmd/tailscale/cli/status.go Normal file
View File

@@ -0,0 +1,172 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cli
import (
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"log"
"net"
"net/http"
"os"
"time"
"github.com/peterbourgon/ff/v2/ffcli"
"github.com/toqueteos/webbrowser"
"tailscale.com/ipn"
"tailscale.com/ipn/ipnstate"
"tailscale.com/net/interfaces"
)
var statusCmd = &ffcli.Command{
Name: "status",
ShortUsage: "status [-active] [-web] [-json]",
ShortHelp: "Show state of tailscaled and its connections",
Exec: runStatus,
FlagSet: (func() *flag.FlagSet {
fs := flag.NewFlagSet("status", flag.ExitOnError)
fs.BoolVar(&statusArgs.json, "json", false, "output in JSON format (WARNING: format subject to change)")
fs.BoolVar(&statusArgs.web, "web", false, "run webserver with HTML showing status")
fs.BoolVar(&statusArgs.active, "active", false, "filter output to only peers with active sessions (not applicable to web mode)")
fs.StringVar(&statusArgs.listen, "listen", "127.0.0.1:8384", "listen address; use port 0 for automatic")
fs.BoolVar(&statusArgs.browser, "browser", true, "Open a browser in web mode")
return fs
})(),
}
var statusArgs struct {
json bool // JSON output mode
web bool // run webserver
listen string // in web mode, webserver address to listen on, empty means auto
browser bool // in web mode, whether to open browser
active bool // in CLI mode, filter output to only peers with active sessions
}
func runStatus(ctx context.Context, args []string) error {
c, bc, ctx, cancel := connect(ctx)
defer cancel()
bc.AllowVersionSkew = true
ch := make(chan *ipnstate.Status, 1)
bc.SetNotifyCallback(func(n ipn.Notify) {
if n.ErrMessage != nil {
log.Fatal(*n.ErrMessage)
}
if n.Status != nil {
ch <- n.Status
}
})
go pump(ctx, bc, c)
getStatus := func() (*ipnstate.Status, error) {
bc.RequestStatus()
select {
case st := <-ch:
return st, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
st, err := getStatus()
if err != nil {
return err
}
if statusArgs.json {
if statusArgs.active {
for peer, ps := range st.Peer {
if !peerActive(ps) {
delete(st.Peer, peer)
}
}
}
j, err := json.MarshalIndent(st, "", " ")
if err != nil {
return err
}
fmt.Printf("%s", j)
return nil
}
if statusArgs.web {
ln, err := net.Listen("tcp", statusArgs.listen)
if err != nil {
return err
}
statusURL := interfaces.HTTPOfListener(ln)
fmt.Printf("Serving Tailscale status at %v ...\n", statusURL)
go func() {
<-ctx.Done()
ln.Close()
}()
if statusArgs.browser {
go webbrowser.Open(statusURL)
}
err = http.Serve(ln, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.RequestURI != "/" {
http.NotFound(w, r)
return
}
st, err := getStatus()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
st.WriteHTML(w)
}))
if ctx.Err() != nil {
return ctx.Err()
}
return err
}
var buf bytes.Buffer
f := func(format string, a ...interface{}) { fmt.Fprintf(&buf, format, a...) }
for _, peer := range st.Peers() {
ps := st.Peer[peer]
active := peerActive(ps)
if statusArgs.active && !active {
continue
}
f("%s %-7s %-15s %-18s tx=%8d rx=%8d ",
peer.ShortString(),
ps.OS,
ps.TailAddr,
ps.SimpleHostName(),
ps.TxBytes,
ps.RxBytes,
)
relay := ps.Relay
if active && relay != "" && ps.CurAddr == "" {
relay = "*" + relay + "*"
} else {
relay = " " + relay
}
f("%-6s", relay)
for i, addr := range ps.Addrs {
if i != 0 {
f(", ")
}
if addr == ps.CurAddr {
f("*%s*", addr)
} else {
f("%s", addr)
}
}
f("\n")
}
os.Stdout.Write(buf.Bytes())
return nil
}
// peerActive reports whether ps has recent activity.
//
// TODO: have the server report this bool instead.
func peerActive(ps *ipnstate.PeerStatus) bool {
return !ps.LastWrite.IsZero() && time.Since(ps.LastWrite) < 2*time.Minute
}

252
cmd/tailscale/cli/up.go Normal file
View File

@@ -0,0 +1,252 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cli
import (
"bytes"
"context"
"flag"
"fmt"
"log"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
"github.com/peterbourgon/ff/v2/ffcli"
"github.com/tailscale/wireguard-go/wgcfg"
"tailscale.com/ipn"
"tailscale.com/tailcfg"
"tailscale.com/wgengine/router"
)
// globalStateKey is the ipn.StateKey that tailscaled loads on
// startup.
//
// We have to support multiple state keys for other OSes (Windows in
// particular), but right now Unix daemons run with a single
// node-global state. To keep open the option of having per-user state
// later, the global state key doesn't look like a username.
const globalStateKey = "_daemon"
var upCmd = &ffcli.Command{
Name: "up",
ShortUsage: "up [flags]",
ShortHelp: "Connect to your Tailscale network",
LongHelp: strings.TrimSpace(`
"tailscale up" connects this machine to your Tailscale network,
triggering authentication if necessary.
The flags passed to this command are specific to this machine. If you don't
specify any flags, options are reset to their default.
`),
FlagSet: (func() *flag.FlagSet {
upf := flag.NewFlagSet("up", flag.ExitOnError)
upf.StringVar(&upArgs.server, "login-server", "https://login.tailscale.com", "base URL of control server")
upf.BoolVar(&upArgs.acceptRoutes, "accept-routes", false, "accept routes advertised by other Tailscale nodes")
upf.BoolVar(&upArgs.acceptDNS, "accept-dns", true, "accept DNS configuration from the admin panel")
upf.BoolVar(&upArgs.singleRoutes, "host-routes", true, "install host routes to other Tailscale nodes")
upf.BoolVar(&upArgs.shieldsUp, "shields-up", false, "don't allow incoming connections")
upf.StringVar(&upArgs.advertiseTags, "advertise-tags", "", "ACL tags to request (comma-separated, e.g. eng,montreal,ssh)")
upf.StringVar(&upArgs.authKey, "authkey", "", "node authorization key")
upf.StringVar(&upArgs.hostname, "hostname", "", "hostname to use instead of the one provided by the OS")
upf.BoolVar(&upArgs.enableDERP, "enable-derp", true, "enable the use of DERP servers")
if runtime.GOOS == "linux" || isBSD(runtime.GOOS) {
upf.StringVar(&upArgs.advertiseRoutes, "advertise-routes", "", "routes to advertise to other nodes (comma-separated, e.g. 10.0.0.0/8,192.168.0.0/24)")
}
if runtime.GOOS == "linux" {
upf.BoolVar(&upArgs.snat, "snat-subnet-routes", true, "source NAT traffic to local routes advertised with -advertise-routes")
upf.StringVar(&upArgs.netfilterMode, "netfilter-mode", "on", "netfilter mode (one of on, nodivert, off)")
}
return upf
})(),
Exec: runUp,
}
var upArgs struct {
server string
acceptRoutes bool
acceptDNS bool
singleRoutes bool
shieldsUp bool
advertiseRoutes string
advertiseTags string
enableDERP bool
snat bool
netfilterMode string
authKey string
hostname string
}
// parseIPOrCIDR parses an IP address or a CIDR prefix. If the input
// is an IP address, it is returned in CIDR form with a /32 mask for
// IPv4 or a /128 mask for IPv6.
func parseIPOrCIDR(s string) (wgcfg.CIDR, bool) {
if strings.Contains(s, "/") {
ret, err := wgcfg.ParseCIDR(s)
if err != nil {
return wgcfg.CIDR{}, false
}
return ret, true
}
ip, ok := wgcfg.ParseIP(s)
if !ok {
return wgcfg.CIDR{}, false
}
if ip.Is4() {
return wgcfg.CIDR{IP: ip, Mask: 32}, true
} else {
return wgcfg.CIDR{IP: ip, Mask: 128}, true
}
}
func isBSD(s string) bool {
return s == "dragonfly" || s == "freebsd" || s == "netbsd" || s == "openbsd"
}
func warning(format string, args ...interface{}) {
fmt.Printf("Warning: "+format+"\n", args...)
}
// checkIPForwarding prints warnings on linux if IP forwarding is not
// enabled, or if we were unable to verify the state of IP forwarding.
func checkIPForwarding() {
var key string
if runtime.GOOS == "linux" {
key = "net.ipv4.ip_forward"
} else if isBSD(runtime.GOOS) {
key = "net.inet.ip.forwarding"
} else {
return
}
bs, err := exec.Command("sysctl", "-n", key).Output()
if err != nil {
warning("couldn't check %s (%v).\nSubnet routes won't work without IP forwarding.", key, err)
return
}
on, err := strconv.ParseBool(string(bytes.TrimSpace(bs)))
if err != nil {
warning("couldn't parse %s (%v).\nSubnet routes won't work without IP forwarding.", key, err)
return
}
if !on {
warning("%s is disabled. Subnet routes won't work.", key)
}
}
func runUp(ctx context.Context, args []string) error {
if len(args) > 0 {
log.Fatalf("too many non-flag arguments: %q", args)
}
var routes []wgcfg.CIDR
if upArgs.advertiseRoutes != "" {
checkIPForwarding()
advroutes := strings.Split(upArgs.advertiseRoutes, ",")
for _, s := range advroutes {
cidr, ok := parseIPOrCIDR(s)
if !ok {
log.Fatalf("%q is not a valid IP address or CIDR prefix", s)
}
routes = append(routes, cidr)
}
}
var tags []string
if upArgs.advertiseTags != "" {
tags = strings.Split(upArgs.advertiseTags, ",")
for _, tag := range tags {
err := tailcfg.CheckTag(tag)
if err != nil {
log.Fatalf("tag: %q: %s", tag, err)
}
}
}
if len(upArgs.hostname) > 256 {
log.Fatalf("hostname too long: %d bytes (max 256)", len(upArgs.hostname))
}
// TODO(apenwarr): fix different semantics between prefs and uflags
// TODO(apenwarr): allow setting/using CorpDNS
prefs := ipn.NewPrefs()
prefs.ControlURL = upArgs.server
prefs.WantRunning = true
prefs.RouteAll = upArgs.acceptRoutes
prefs.CorpDNS = upArgs.acceptDNS
prefs.AllowSingleHosts = upArgs.singleRoutes
prefs.ShieldsUp = upArgs.shieldsUp
prefs.AdvertiseRoutes = routes
prefs.AdvertiseTags = tags
prefs.NoSNAT = !upArgs.snat
prefs.DisableDERP = !upArgs.enableDERP
prefs.Hostname = upArgs.hostname
if runtime.GOOS == "linux" {
switch upArgs.netfilterMode {
case "on":
prefs.NetfilterMode = router.NetfilterOn
case "nodivert":
prefs.NetfilterMode = router.NetfilterNoDivert
warning("netfilter=nodivert; add iptables calls to ts-* chains manually.")
case "off":
prefs.NetfilterMode = router.NetfilterOff
warning("netfilter=off; configure iptables yourself.")
default:
log.Fatalf("invalid value --netfilter-mode: %q", upArgs.netfilterMode)
}
}
c, bc, ctx, cancel := connect(ctx)
defer cancel()
var printed bool
bc.SetPrefs(prefs)
opts := ipn.Options{
StateKey: globalStateKey,
AuthKey: upArgs.authKey,
Notify: func(n ipn.Notify) {
if n.ErrMessage != nil {
log.Fatalf("backend error: %v\n", *n.ErrMessage)
}
if s := n.State; s != nil {
switch *s {
case ipn.NeedsLogin:
printed = true
bc.StartLoginInteractive()
case ipn.NeedsMachineAuth:
printed = true
fmt.Fprintf(os.Stderr, "\nTo authorize your machine, visit (as admin):\n\n\t%s/admin/machines\n\n", upArgs.server)
case ipn.Starting, ipn.Running:
// Done full authentication process
if printed {
// Only need to print an update if we printed the "please click" message earlier.
fmt.Fprintf(os.Stderr, "Success.\n")
}
cancel()
}
}
if url := n.BrowseToURL; url != nil {
fmt.Fprintf(os.Stderr, "\nTo authenticate, visit:\n\n\t%s\n\n", *url)
}
},
}
// We still have to Start right now because it's the only way to
// set up notifications and whatnot. This causes a bunch of churn
// every time the CLI touches anything.
//
// TODO(danderson): redo the frontend/backend API to assume
// ephemeral frontends that read/modify/write state, once
// Windows/Mac state is moved into backend.
bc.Start(opts)
pump(ctx, bc, c)
return nil
}

View File

@@ -0,0 +1,69 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cli
import (
"context"
"flag"
"fmt"
"log"
"github.com/peterbourgon/ff/v2/ffcli"
"tailscale.com/ipn"
"tailscale.com/version"
)
var versionCmd = &ffcli.Command{
Name: "version",
ShortUsage: "version [flags]",
ShortHelp: "Print Tailscale version",
FlagSet: (func() *flag.FlagSet {
fs := flag.NewFlagSet("version", flag.ExitOnError)
fs.BoolVar(&versionArgs.daemon, "daemon", false, "also print local node's daemon version")
return fs
})(),
Exec: runVersion,
}
var versionArgs struct {
daemon bool // also check local node's daemon version
}
func runVersion(ctx context.Context, args []string) error {
if len(args) > 0 {
log.Fatalf("too many non-flag arguments: %q", args)
}
if !versionArgs.daemon {
fmt.Println(version.LONG)
return nil
}
fmt.Printf("Client: %s\n", version.LONG)
c, bc, ctx, cancel := connect(ctx)
defer cancel()
bc.AllowVersionSkew = true
done := make(chan struct{})
bc.SetNotifyCallback(func(n ipn.Notify) {
if n.ErrMessage != nil {
log.Fatal(*n.ErrMessage)
}
if n.Status != nil {
fmt.Printf("Daemon: %s\n", n.Version)
close(done)
}
})
go pump(ctx, bc, c)
bc.RequestStatus()
select {
case <-done:
return nil
case <-ctx.Done():
return ctx.Err()
}
}

View File

@@ -1,40 +0,0 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main // import "tailscale.com/cmd/tailscale"
import (
"context"
"fmt"
"log"
"sort"
"time"
"tailscale.com/netcheck"
)
func runNetcheck(ctx context.Context, args []string) error {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
report, err := netcheck.GetReport(ctx, log.Printf)
if err != nil {
log.Fatalf("netcheck: %v", err)
}
fmt.Printf("\nReport:\n")
fmt.Printf("\t* UDP: %v\n", report.UDP)
fmt.Printf("\t* IPv6: %v\n", report.IPv6)
fmt.Printf("\t* MappingVariesByDestIP: %v\n", report.MappingVariesByDestIP)
fmt.Printf("\t* HairPinning: %v\n", report.HairPinning)
fmt.Printf("\t* Nearest DERP: %v (%v)\n", report.PreferredDERP, netcheck.DERPNodeLocation(report.PreferredDERP))
fmt.Printf("\t* DERP latency:\n")
var ss []string
for s := range report.DERPLatency {
ss = append(ss, s)
}
sort.Strings(ss)
for _, s := range ss {
fmt.Printf("\t\t- %s = %v\n", s, report.DERPLatency[s])
}
return nil
}

View File

@@ -7,198 +7,22 @@
package main // import "tailscale.com/cmd/tailscale"
import (
"context"
"flag"
"fmt"
"log"
"net"
"os"
"os/signal"
"strings"
"syscall"
"github.com/apenwarr/fixconsole"
"github.com/pborman/getopt/v2"
"github.com/peterbourgon/ff/v2/ffcli"
"github.com/tailscale/wireguard-go/wgcfg"
"tailscale.com/ipn"
"tailscale.com/logpolicy"
"tailscale.com/paths"
"tailscale.com/safesocket"
"tailscale.com/cmd/tailscale/cli"
)
// globalStateKey is the ipn.StateKey that tailscaled loads on
// startup.
//
// We have to support multiple state keys for other OSes (Windows in
// particular), but right now Unix daemons run with a single
// node-global state. To keep open the option of having per-user state
// later, the global state key doesn't look like a username.
const globalStateKey = "_daemon"
// pump receives backend messages on conn and pushes them into bc.
func pump(ctx context.Context, bc *ipn.BackendClient, conn net.Conn) {
defer log.Printf("Control connection done.\n")
defer conn.Close()
for ctx.Err() == nil {
msg, err := ipn.ReadMsg(conn)
if err != nil {
log.Printf("ReadMsg: %v\n", err)
break
}
bc.GotNotifyMsg(msg)
}
}
func main() {
err := fixconsole.FixConsoleIfNeeded()
if err != nil {
log.Printf("fixConsoleOutput: %v\n", err)
}
upf := flag.NewFlagSet("up", flag.ExitOnError)
upf.StringVar(&upArgs.socket, "socket", paths.DefaultTailscaledSocket(), "path to tailscaled's unix socket")
upf.StringVar(&upArgs.server, "login-server", "https://login.tailscale.com", "base URL of control server")
upf.BoolVar(&upArgs.acceptRoutes, "accept-routes", false, "accept routes advertised by other Tailscale nodes")
upf.BoolVar(&upArgs.noSingleRoutes, "no-single-routes", false, "don't install routes to single nodes")
upf.BoolVar(&upArgs.noPacketFilter, "no-packet-filter", false, "disable packet filter")
upf.StringVar(&upArgs.advertiseRoutes, "advertise-routes", "", "routes to advertise to other nodes (comma-separated, e.g. 10.0.0.0/8,192.168.0.0/24)")
upCmd := &ffcli.Command{
Name: "up",
ShortUsage: "up [flags]",
ShortHelp: "Connect to your Tailscale network",
LongHelp: strings.TrimSpace(`
"tailscale up" connects this machine to your Tailscale network,
triggering authentication if necessary.
The flags passed to this command set tailscaled options that are
specific to this machine, such as whether to advertise some routes to
other nodes in the Tailscale network. If you don't specify any flags,
options are reset to their default.
`),
FlagSet: upf,
Exec: runUp,
}
netcheckCmd := &ffcli.Command{
Name: "netcheck",
ShortUsage: "netcheck",
ShortHelp: "Print an analysis of local network conditions",
Exec: runNetcheck,
}
rootCmd := &ffcli.Command{
Name: "tailscale",
ShortUsage: "tailscale subcommand [flags]",
ShortHelp: "The easiest, most secure way to use WireGuard.",
LongHelp: strings.TrimSpace(`
This CLI is still under active development. Commands and flags will
change in the future.
`),
Subcommands: []*ffcli.Command{
upCmd,
netcheckCmd,
},
Exec: func(context.Context, []string) error { return flag.ErrHelp },
}
if err := rootCmd.ParseAndRun(context.Background(), os.Args[1:]); err != nil && err != flag.ErrHelp {
log.Fatal(err)
if err := cli.Run(os.Args[1:]); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
var upArgs = struct {
socket string
server string
acceptRoutes bool
noSingleRoutes bool
noPacketFilter bool
advertiseRoutes string
}{}
func runUp(ctx context.Context, args []string) error {
pol := logpolicy.New("tailnode.log.tailscale.io")
if len(args) > 0 {
log.Fatalf("too many non-flag arguments: %#v", getopt.Args()[0])
}
defer pol.Close()
var adv []wgcfg.CIDR
if upArgs.advertiseRoutes != "" {
advroutes := strings.Split(upArgs.advertiseRoutes, ",")
for _, s := range advroutes {
cidr, err := wgcfg.ParseCIDR(s)
if err != nil {
log.Fatalf("%q is not a valid CIDR prefix: %v", s, err)
}
adv = append(adv, *cidr)
}
}
// TODO(apenwarr): fix different semantics between prefs and uflags
// TODO(apenwarr): allow setting/using CorpDNS
prefs := ipn.NewPrefs()
prefs.ControlURL = upArgs.server
prefs.WantRunning = true
prefs.RouteAll = upArgs.acceptRoutes
prefs.AllowSingleHosts = !upArgs.noSingleRoutes
prefs.UsePacketFilter = !upArgs.noPacketFilter
prefs.AdvertiseRoutes = adv
c, err := safesocket.Connect(upArgs.socket, 0)
if err != nil {
log.Fatalf("safesocket.Connect: %v\n", err)
}
clientToServer := func(b []byte) {
ipn.WriteMsg(c, b)
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
go func() {
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, syscall.SIGINT, syscall.SIGTERM)
<-interrupt
c.Close()
}()
bc := ipn.NewBackendClient(log.Printf, clientToServer)
bc.SetPrefs(prefs)
opts := ipn.Options{
StateKey: globalStateKey,
Notify: func(n ipn.Notify) {
if n.ErrMessage != nil {
log.Fatalf("backend error: %v\n", *n.ErrMessage)
}
if s := n.State; s != nil {
switch *s {
case ipn.NeedsLogin:
bc.StartLoginInteractive()
case ipn.NeedsMachineAuth:
fmt.Fprintf(os.Stderr, "\nTo authorize your machine, visit (as admin):\n\n\t%s/admin/machines\n\n", upArgs.server)
case ipn.Starting, ipn.Running:
// Done full authentication process
fmt.Fprintf(os.Stderr, "\ntailscaled is authenticated, nothing more to do.\n\n")
cancel()
}
}
if url := n.BrowseToURL; url != nil {
fmt.Fprintf(os.Stderr, "\nTo authenticate, visit:\n\n\t%s\n\n", *url)
}
},
}
// We still have to Start right now because it's the only way to
// set up notifications and whatnot. This causes a bunch of churn
// every time the CLI touches anything.
//
// TODO(danderson): redo the frontend/backend API to assume
// ephemeral frontends that read/modify/write state, once
// Windows/Mac state is moved into backend.
bc.Start(opts)
pump(ctx, bc, c)
return nil
}

View File

@@ -4,5 +4,5 @@
# settings.
PORT="41641"
# Extra flags you might want to pass to relaynode.
# Extra flags you might want to pass to tailscaled.
FLAGS=""

View File

@@ -14,14 +14,22 @@ import (
"log"
"net/http"
"net/http/pprof"
"os"
"os/signal"
"runtime"
"runtime/debug"
"syscall"
"time"
"github.com/apenwarr/fixconsole"
"github.com/pborman/getopt/v2"
"tailscale.com/ipn/ipnserver"
"tailscale.com/logpolicy"
"tailscale.com/paths"
"tailscale.com/types/logger"
"tailscale.com/wgengine"
"tailscale.com/wgengine/magicsock"
"tailscale.com/wgengine/router"
)
// globalStateKey is the ipn.StateKey that tailscaled loads on
@@ -33,78 +41,156 @@ import (
// later, the global state key doesn't look like a username.
const globalStateKey = "_daemon"
func main() {
fake := getopt.BoolLong("fake", 0, "fake tunnel+routing instead of tuntap")
debug := getopt.StringLong("debug", 0, "", "Address of debug server")
tunname := getopt.StringLong("tun", 0, wgengine.DefaultTunName, "tunnel interface name")
listenport := getopt.Uint16Long("port", 'p', magicsock.DefaultPort, "WireGuard port (0=autoselect)")
statepath := getopt.StringLong("state", 0, paths.DefaultTailscaledStateFile(), "Path of state file")
socketpath := getopt.StringLong("socket", 's', paths.DefaultTailscaledSocket(), "Path of the service unix socket")
// defaultTunName returns the default tun device name for the platform.
func defaultTunName() string {
switch runtime.GOOS {
case "openbsd":
return "tun"
case "windows":
return "Tailscale"
}
return "tailscale0"
}
logf := wgengine.RusagePrefixLog(log.Printf)
var args struct {
cleanup bool
fake bool
debug string
tunname string
port uint16
statepath string
socketpath string
}
func main() {
// We aren't very performance sensitive, and the parts that are
// performance sensitive (wireguard) try hard not to do any memory
// allocations. So let's be aggressive about garbage collection,
// unless the user specifically overrides it in the usual way.
if _, ok := os.LookupEnv("GOGC"); !ok {
debug.SetGCPercent(10)
}
// Set default values for getopt.
args.tunname = defaultTunName()
args.port = magicsock.DefaultPort
args.statepath = paths.DefaultTailscaledStateFile()
args.socketpath = paths.DefaultTailscaledSocket()
getopt.FlagLong(&args.cleanup, "cleanup", 0, "clean up system state and exit")
getopt.FlagLong(&args.fake, "fake", 0, "fake tunnel+routing instead of tuntap")
getopt.FlagLong(&args.debug, "debug", 0, "address of debug server")
getopt.FlagLong(&args.tunname, "tun", 0, "tunnel interface name")
getopt.FlagLong(&args.port, "port", 'p', "WireGuard port (0=autoselect)")
getopt.FlagLong(&args.statepath, "state", 0, "path of state file")
getopt.FlagLong(&args.socketpath, "socket", 's', "path of the service unix socket")
err := fixconsole.FixConsoleIfNeeded()
if err != nil {
logf("fixConsoleOutput: %v\n", err)
log.Fatalf("fixConsoleOutput: %v", err)
}
pol := logpolicy.New("tailnode.log.tailscale.io")
getopt.Parse()
if len(getopt.Args()) > 0 {
log.Fatalf("too many non-flag arguments: %#v", getopt.Args()[0])
}
if *statepath == "" {
if args.statepath == "" {
log.Fatalf("--state is required")
}
if *socketpath == "" {
if args.socketpath == "" && runtime.GOOS != "windows" {
log.Fatalf("--socket is required")
}
if *debug != "" {
go runDebugServer(*debug)
if err := run(); err != nil {
// No need to log; the func already did
os.Exit(1)
}
}
func run() error {
var err error
pol := logpolicy.New("tailnode.log.tailscale.io")
defer func() {
// Finish uploading logs after closing everything else.
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
pol.Shutdown(ctx)
}()
logf := wgengine.RusagePrefixLog(log.Printf)
logf = logger.RateLimitedFn(logf, 5*time.Second, 5, 100)
if args.cleanup {
router.Cleanup(logf, args.tunname)
return nil
}
var debugMux *http.ServeMux
if args.debug != "" {
debugMux = newDebugMux()
go runDebugServer(debugMux, args.debug)
}
var e wgengine.Engine
if *fake {
if args.fake {
e, err = wgengine.NewFakeUserspaceEngine(logf, 0)
} else {
e, err = wgengine.NewUserspaceEngine(logf, *tunname, *listenport)
e, err = wgengine.NewUserspaceEngine(logf, args.tunname, args.port)
}
if err != nil {
log.Fatalf("wgengine.New: %v\n", err)
logf("wgengine.New: %v", err)
return err
}
e = wgengine.NewWatchdog(e)
ctx, cancel := context.WithCancel(context.Background())
// Exit gracefully by cancelling the ipnserver context in most common cases:
// interrupted from the TTY or killed by a service manager.
go func() {
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, syscall.SIGINT, syscall.SIGTERM)
select {
case <-interrupt:
cancel()
case <-ctx.Done():
// continue
}
}()
opts := ipnserver.Options{
SocketPath: *socketpath,
StatePath: *statepath,
SocketPath: args.socketpath,
Port: 41112,
StatePath: args.statepath,
AutostartStateKey: globalStateKey,
LegacyConfigPath: paths.LegacyConfigPath,
LegacyConfigPath: paths.LegacyConfigPath(),
SurviveDisconnects: true,
DebugMux: debugMux,
}
err = ipnserver.Run(context.Background(), logf, pol.PublicID.String(), opts, e)
if err != nil {
log.Fatalf("tailscaled: %v\n", err)
err = ipnserver.Run(ctx, logf, pol.PublicID.String(), opts, e)
// Cancelation is not an error: it is the only way to stop ipnserver.
if err != nil && err != context.Canceled {
logf("ipnserver.Run: %v", err)
return err
}
// TODO(crawshaw): It would be nice to start a timeout context the moment a signal
// is received and use that timeout to give us a moment to finish uploading logs
// here. But the signal is handled inside ipnserver.Run, so some plumbing is needed.
ctx, cancel := context.WithCancel(context.Background())
cancel()
pol.Shutdown(ctx)
return nil
}
func runDebugServer(addr string) {
func newDebugMux() *http.ServeMux {
mux := http.NewServeMux()
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
srv := http.Server{
return mux
}
func runDebugServer(mux *http.ServeMux, addr string) {
srv := &http.Server{
Addr: addr,
Handler: mux,
}

View File

@@ -9,6 +9,7 @@ StartLimitBurst=0
[Service]
EnvironmentFile=/etc/default/tailscaled
ExecStart=/usr/sbin/tailscaled --state=/var/lib/tailscale/tailscaled.state --socket=/run/tailscale/tailscaled.sock --port $PORT $FLAGS
ExecStopPost=/usr/sbin/tailscaled --cleanup
Restart=on-failure
@@ -16,8 +17,8 @@ RuntimeDirectory=tailscale
RuntimeDirectoryMode=0755
StateDirectory=tailscale
StateDirectoryMode=0750
User=root
Group=root
CacheDirectory=tailscale
CacheDirectoryMode=0750
[Install]
WantedBy=multi-user.target

View File

@@ -32,7 +32,7 @@ import (
"github.com/gliderlabs/ssh"
"github.com/kr/pty"
gossh "golang.org/x/crypto/ssh"
"tailscale.com/interfaces"
"tailscale.com/net/interfaces"
)
var (

View File

@@ -17,43 +17,46 @@ import (
"sync"
"time"
"github.com/tailscale/wireguard-go/wgcfg"
"golang.org/x/oauth2"
"tailscale.com/logtail/backoff"
"tailscale.com/tailcfg"
"tailscale.com/types/empty"
"tailscale.com/types/logger"
"tailscale.com/types/structs"
)
// TODO(apenwarr): eliminate the 'state' variable, as it's now obsolete.
// It's used only by the unit tests.
type state int
// State is the high-level state of the client. It is used only in
// unit tests for proper sequencing, don't depend on it anywhere else.
// TODO(apenwarr): eliminate 'state', as it's now obsolete.
type State int
const (
stateNew = state(iota)
stateNotAuthenticated
stateAuthenticating
stateURLVisitRequired
stateAuthenticated
stateSynchronized // connected and received map update
StateNew = State(iota)
StateNotAuthenticated
StateAuthenticating
StateURLVisitRequired
StateAuthenticated
StateSynchronized // connected and received map update
)
func (s state) MarshalText() ([]byte, error) {
func (s State) MarshalText() ([]byte, error) {
return []byte(s.String()), nil
}
func (s state) String() string {
func (s State) String() string {
switch s {
case stateNew:
case StateNew:
return "state:new"
case stateNotAuthenticated:
case StateNotAuthenticated:
return "state:not-authenticated"
case stateAuthenticating:
case StateAuthenticating:
return "state:authenticating"
case stateURLVisitRequired:
case StateURLVisitRequired:
return "state:url-visit-required"
case stateAuthenticated:
case StateAuthenticated:
return "state:authenticated"
case stateSynchronized:
case StateSynchronized:
return "state:synchronized"
default:
return fmt.Sprintf("state:unknown:%d", int(s))
@@ -61,13 +64,14 @@ func (s state) String() string {
}
type Status struct {
_ structs.Incomparable
LoginFinished *empty.Message
Err string
URL string
Persist *Persist // locally persisted configuration
NetMap *NetworkMap // server-pushed configuration
Hostinfo *tailcfg.Hostinfo // current Hostinfo data
state state
State State
}
// Equal reports whether s and s2 are equal.
@@ -82,7 +86,7 @@ func (s *Status) Equal(s2 *Status) bool {
reflect.DeepEqual(s.Persist, s2.Persist) &&
reflect.DeepEqual(s.NetMap, s2.NetMap) &&
reflect.DeepEqual(s.Hostinfo, s2.Hostinfo) &&
s.state == s2.state
s.State == s2.State
}
func (s Status) String() string {
@@ -90,10 +94,11 @@ func (s Status) String() string {
if err != nil {
panic(err)
}
return s.state.String() + " " + string(b)
return s.State.String() + " " + string(b)
}
type LoginGoal struct {
_ structs.Incomparable
wantLoggedIn bool // true if we *want* to be logged in
token *oauth2.Token // oauth token to use when logging in
flags LoginFlags // flags to use when logging in
@@ -118,7 +123,7 @@ type Client struct {
hostinfo *tailcfg.Hostinfo
inPollNetMap bool // true if currently running a PollNetMap
inSendStatus int // number of sendStatus calls currently in progress
state state
state State
authCtx context.Context // context used for auth requests
mapCtx context.Context // context used for netmap requests
@@ -202,7 +207,7 @@ func (c *Client) cancelMapSafely() {
c.mu.Lock()
defer c.mu.Unlock()
c.logf("cancelMapSafely: synced=%v\n", c.synced)
c.logf("cancelMapSafely: synced=%v", c.synced)
if c.inPollNetMap {
// received at least one netmap since the last
@@ -224,23 +229,23 @@ func (c *Client) cancelMapSafely() {
// request.
select {
case c.newMapCh <- struct{}{}:
c.logf("cancelMapSafely: wrote to channel\n")
c.logf("cancelMapSafely: wrote to channel")
default:
// if channel write failed, then there was already
// an outstanding newMapCh request. One is enough,
// since it'll always use the latest endpoints.
c.logf("cancelMapSafely: channel was full\n")
c.logf("cancelMapSafely: channel was full")
}
}
}
func (c *Client) authRoutine() {
defer close(c.authDone)
bo := backoff.Backoff{Name: "authRoutine"}
bo := backoff.NewBackoff("authRoutine", c.logf)
for {
c.mu.Lock()
c.logf("authRoutine: %s\n", c.state)
c.logf("authRoutine: %s", c.state)
expiry := c.expiry
goal := c.loginGoal
ctx := c.authCtx
@@ -249,13 +254,13 @@ func (c *Client) authRoutine() {
select {
case <-c.quit:
c.logf("authRoutine: quit\n")
c.logf("authRoutine: quit")
return
default:
}
report := func(err error, msg string) {
c.logf("%s: %v\n", msg, err)
c.logf("%s: %v", msg, err)
err = fmt.Errorf("%s: %v", msg, err)
// don't send status updates for context errors,
// since context cancelation is always on purpose.
@@ -284,14 +289,14 @@ func (c *Client) authRoutine() {
}
select {
case <-ctx.Done():
c.logf("authRoutine: context done.\n")
c.logf("authRoutine: context done.")
case <-exp:
// Unfortunately the key expiry isn't provided
// by the control server until mapRequest.
// So we have to do some hackery with c.expiry
// in here.
// TODO(apenwarr): add a key expiry field in RegisterResponse.
c.logf("authRoutine: key expiration check.\n")
c.logf("authRoutine: key expiration check.")
if synced && expiry != nil && !expiry.IsZero() && expiry.Before(c.timeNow()) {
c.logf("Key expired; setting loggedIn=false.")
@@ -316,7 +321,7 @@ func (c *Client) authRoutine() {
c.mu.Lock()
c.loggedIn = false
c.loginGoal = nil
c.state = stateNotAuthenticated
c.state = StateNotAuthenticated
c.synced = false
c.mu.Unlock()
@@ -325,9 +330,9 @@ func (c *Client) authRoutine() {
} else { // ie. goal.wantLoggedIn
c.mu.Lock()
if goal.url != "" {
c.state = stateURLVisitRequired
c.state = StateURLVisitRequired
} else {
c.state = stateAuthenticating
c.state = StateAuthenticating
}
c.mu.Unlock()
@@ -350,13 +355,14 @@ func (c *Client) authRoutine() {
err = fmt.Errorf("weird: server required a new url?")
report(err, "WaitLoginURL")
}
goal.url = url
goal.token = nil
goal.flags = LoginDefault
c.mu.Lock()
c.loginGoal = goal
c.state = stateURLVisitRequired
c.loginGoal = &LoginGoal{
wantLoggedIn: true,
flags: LoginDefault,
url: url,
}
c.state = StateURLVisitRequired
c.synced = false
c.mu.Unlock()
@@ -369,7 +375,7 @@ func (c *Client) authRoutine() {
c.mu.Lock()
c.loggedIn = true
c.loginGoal = nil
c.state = stateAuthenticated
c.state = StateAuthenticated
c.mu.Unlock()
c.sendStatus("authRoutine4", nil, "", nil)
@@ -379,26 +385,40 @@ func (c *Client) authRoutine() {
}
}
// Expiry returns the credential expiration time, or the zero time if
// the expiration time isn't known. Used in tests only.
func (c *Client) Expiry() *time.Time {
c.mu.Lock()
defer c.mu.Unlock()
return c.expiry
}
// Direct returns the underlying direct client object. Used in tests
// only.
func (c *Client) Direct() *Direct {
return c.direct
}
func (c *Client) mapRoutine() {
defer close(c.mapDone)
bo := backoff.Backoff{Name: "mapRoutine"}
bo := backoff.NewBackoff("mapRoutine", c.logf)
for {
c.mu.Lock()
c.logf("mapRoutine: %s\n", c.state)
c.logf("mapRoutine: %s", c.state)
loggedIn := c.loggedIn
ctx := c.mapCtx
c.mu.Unlock()
select {
case <-c.quit:
c.logf("mapRoutine: quit\n")
c.logf("mapRoutine: quit")
return
default:
}
report := func(err error, msg string) {
c.logf("%s: %v\n", msg, err)
c.logf("%s: %v", msg, err)
err = fmt.Errorf("%s: %v", msg, err)
// don't send status updates for context errors,
// since context cancelation is always on purpose.
@@ -416,9 +436,9 @@ func (c *Client) mapRoutine() {
select {
case <-ctx.Done():
c.logf("mapRoutine: context done.\n")
c.logf("mapRoutine: context done.")
case <-c.newMapCh:
c.logf("mapRoutine: new map needed while idle.\n")
c.logf("mapRoutine: new map needed while idle.")
}
} else {
// Be sure this is false when we're not inside
@@ -433,7 +453,7 @@ func (c *Client) mapRoutine() {
select {
case <-c.newMapCh:
c.logf("mapRoutine: new map request during PollNetMap. canceling.\n")
c.logf("mapRoutine: new map request during PollNetMap. canceling.")
c.cancelMapLocked()
// Don't emit this netmap; we're
@@ -446,7 +466,7 @@ func (c *Client) mapRoutine() {
c.synced = true
c.inPollNetMap = true
if c.loggedIn {
c.state = stateSynchronized
c.state = StateSynchronized
}
exp := nm.Expiry
c.expiry = &exp
@@ -455,7 +475,7 @@ func (c *Client) mapRoutine() {
c.mu.Unlock()
c.logf("mapRoutine: netmap received: %s\n", state)
c.logf("mapRoutine: netmap received: %s", state)
if stillAuthed {
c.sendStatus("mapRoutine2", nil, "", nm)
}
@@ -464,8 +484,8 @@ func (c *Client) mapRoutine() {
c.mu.Lock()
c.synced = false
c.inPollNetMap = false
if c.state == stateSynchronized {
c.state = stateAuthenticated
if c.state == StateSynchronized {
c.state = StateAuthenticated
}
c.mu.Unlock()
@@ -496,7 +516,12 @@ func (c *Client) SetHostinfo(hi *tailcfg.Hostinfo) {
if hi == nil {
panic("nil Hostinfo")
}
c.direct.SetHostinfo(hi)
if !c.direct.SetHostinfo(hi) {
c.logf("[unexpected] duplicate Hostinfo: %v", hi)
return
}
c.logf("Hostinfo: %v", hi)
// Send new Hostinfo to server
c.cancelMapSafely()
}
@@ -505,7 +530,12 @@ func (c *Client) SetNetInfo(ni *tailcfg.NetInfo) {
if ni == nil {
panic("nil NetInfo")
}
c.direct.SetNetInfo(ni)
if !c.direct.SetNetInfo(ni) {
c.logf("[unexpected] duplicate NetInfo: %v", ni)
return
}
c.logf("NetInfo: %v", ni)
// Send new Hostinfo (which includes NetInfo) to server
c.cancelMapSafely()
}
@@ -520,11 +550,11 @@ func (c *Client) sendStatus(who string, err error, url string, nm *NetworkMap) {
c.inSendStatus++
c.mu.Unlock()
c.logf("sendStatus: %s: %v\n", who, state)
c.logf("sendStatus: %s: %v", who, state)
var p *Persist
var fin *empty.Message
if state == stateAuthenticated {
if state == StateAuthenticated {
fin = new(empty.Message)
}
if nm != nil && loggedIn && synced {
@@ -541,7 +571,7 @@ func (c *Client) sendStatus(who string, err error, url string, nm *NetworkMap) {
Persist: p,
NetMap: nm,
Hostinfo: hi,
state: state,
State: state,
}
if err != nil {
new.Err = err.Error()
@@ -556,7 +586,7 @@ func (c *Client) sendStatus(who string, err error, url string, nm *NetworkMap) {
}
func (c *Client) Login(t *oauth2.Token, flags LoginFlags) {
c.logf("client.Login(%v, %v)\n", t != nil, flags)
c.logf("client.Login(%v, %v)", t != nil, flags)
c.mu.Lock()
c.loginGoal = &LoginGoal{
@@ -570,7 +600,7 @@ func (c *Client) Login(t *oauth2.Token, flags LoginFlags) {
}
func (c *Client) Logout() {
c.logf("client.Logout()\n")
c.logf("client.Logout()")
c.mu.Lock()
c.loginGoal = &LoginGoal{
@@ -589,7 +619,7 @@ func (c *Client) UpdateEndpoints(localPort uint16, endpoints []string) {
}
func (c *Client) Shutdown() {
c.logf("client.Shutdown()\n")
c.logf("client.Shutdown()")
c.mu.Lock()
inSendStatus := c.inSendStatus
@@ -600,13 +630,30 @@ func (c *Client) Shutdown() {
}
c.mu.Unlock()
c.logf("client.Shutdown: inSendStatus=%v\n", inSendStatus)
c.logf("client.Shutdown: inSendStatus=%v", inSendStatus)
if !closed {
close(c.quit)
c.cancelAuth()
<-c.authDone
c.cancelMapUnsafely()
<-c.mapDone
c.logf("Client.Shutdown done.\n")
c.logf("Client.Shutdown done.")
}
}
// NodePublicKey returns the node public key currently in use. This is
// used exclusively in tests.
func (c *Client) TestOnlyNodePublicKey() wgcfg.Key {
priv := c.direct.GetPersist()
return priv.PrivateNodeKey.Public()
}
func (c *Client) TestOnlySetAuthKey(authkey string) {
c.direct.mu.Lock()
defer c.direct.mu.Unlock()
c.direct.authKey = authkey
}
func (c *Client) TestOnlyTimeNow() time.Time {
return c.timeNow()
}

File diff suppressed because it is too large Load Diff

View File

@@ -13,14 +13,16 @@ import (
func fieldsOf(t reflect.Type) (fields []string) {
for i := 0; i < t.NumField(); i++ {
fields = append(fields, t.Field(i).Name)
if name := t.Field(i).Name; name != "_" {
fields = append(fields, name)
}
}
return
}
func TestStatusEqual(t *testing.T) {
// Verify that the Equal method stays in sync with reality
equalHandles := []string{"LoginFinished", "Err", "URL", "Persist", "NetMap", "Hostinfo", "state"}
equalHandles := []string{"LoginFinished", "Err", "URL", "Persist", "NetMap", "Hostinfo", "State"}
if have := fieldsOf(reflect.TypeOf(Status{})); !reflect.DeepEqual(have, equalHandles) {
t.Errorf("Status.Equal check might be out of sync\nfields: %q\nhandled: %q\n",
have, equalHandles)
@@ -46,13 +48,13 @@ func TestStatusEqual(t *testing.T) {
true,
},
{
&Status{state: stateNew},
&Status{state: stateNew},
&Status{State: StateNew},
&Status{State: StateNew},
true,
},
{
&Status{state: stateNew},
&Status{state: stateAuthenticated},
&Status{State: StateNew},
&Status{State: StateAuthenticated},
false,
},
{

View File

@@ -16,8 +16,9 @@ import (
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"runtime"
"reflect"
"strconv"
"strings"
"sync"
@@ -26,13 +27,17 @@ import (
"github.com/tailscale/wireguard-go/wgcfg"
"golang.org/x/crypto/nacl/box"
"golang.org/x/oauth2"
"tailscale.com/log/logheap"
"tailscale.com/net/netns"
"tailscale.com/net/tlsdial"
"tailscale.com/tailcfg"
"tailscale.com/types/logger"
"tailscale.com/types/structs"
"tailscale.com/version"
"tailscale.com/wgengine/filter"
)
type Persist struct {
_ structs.Incomparable
PrivateMachineKey wgcfg.PrivateKey
PrivateNodeKey wgcfg.PrivateKey
OldPrivateNodeKey wgcfg.PrivateKey // needed to request key rotation
@@ -76,29 +81,35 @@ type Direct struct {
httpc *http.Client // HTTP client used to talk to tailcontrol
serverURL string // URL of the tailcontrol server
timeNow func() time.Time
lastPrintMap time.Time
newDecompressor func() (Decompressor, error)
keepAlive bool
logf logger.Logf
discoPubKey tailcfg.DiscoKey
mu sync.Mutex // mutex guards the following fields
serverKey wgcfg.Key
persist Persist
authKey string
tryingNewKey wgcfg.PrivateKey
expiry *time.Time
hostinfo *tailcfg.Hostinfo // always non-nil
endpoints []string
localPort uint16 // or zero to mean auto
// hostinfo is mutated in-place while mu is held.
hostinfo *tailcfg.Hostinfo // always non-nil
endpoints []string
localPort uint16 // or zero to mean auto
}
type Options struct {
Persist Persist // initial persistent data
HTTPC *http.Client // HTTP client used to talk to tailcontrol
ServerURL string // URL of the tailcontrol server
AuthKey string // optional node auth key for auto registration
TimeNow func() time.Time // time.Now implementation used by Client
Hostinfo *tailcfg.Hostinfo // non-nil passes ownership, nil means to use default using os.Hostname, etc
DiscoPublicKey tailcfg.DiscoKey
NewDecompressor func() (Decompressor, error)
KeepAlive bool
Logf logger.Logf
HTTPTestClient *http.Client // optional HTTP client to use (for tests only)
}
type Decompressor interface {
@@ -112,8 +123,9 @@ func NewDirect(opts Options) (*Direct, error) {
return nil, errors.New("controlclient.New: no server URL specified")
}
opts.ServerURL = strings.TrimRight(opts.ServerURL, "/")
if opts.HTTPC == nil {
opts.HTTPC = http.DefaultClient
serverURL, err := url.Parse(opts.ServerURL)
if err != nil {
return nil, err
}
if opts.TimeNow == nil {
opts.TimeNow = time.Now
@@ -123,14 +135,27 @@ func NewDirect(opts Options) (*Direct, error) {
// TODO(bradfitz): ... but then it shouldn't be in Options.
opts.Logf = log.Printf
}
httpc := opts.HTTPTestClient
if httpc == nil {
dialer := netns.NewDialer()
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.DialContext = dialer.DialContext
tr.ForceAttemptHTTP2 = true
tr.TLSClientConfig = tlsdial.Config(serverURL.Host, tr.TLSClientConfig)
httpc = &http.Client{Transport: tr}
}
c := &Direct{
httpc: opts.HTTPC,
httpc: httpc,
serverURL: opts.ServerURL,
timeNow: opts.TimeNow,
logf: opts.Logf,
newDecompressor: opts.NewDecompressor,
keepAlive: opts.KeepAlive,
persist: opts.Persist,
authKey: opts.AuthKey,
discoPubKey: opts.DiscoPublicKey,
}
if opts.Hostinfo == nil {
c.SetHostinfo(NewHostinfo())
@@ -140,45 +165,34 @@ func NewDirect(opts Options) (*Direct, error) {
return c, nil
}
func hostinfoOS() string {
os := runtime.GOOS
switch os {
case "darwin":
if version.IsMobile() {
return "iOS"
} else {
return "macOS"
}
default:
return os
}
}
func NewHostinfo() *tailcfg.Hostinfo {
hostname, _ := os.Hostname()
return &tailcfg.Hostinfo{
IPNVersion: version.LONG,
Hostname: hostname,
OS: hostinfoOS(),
OS: version.OS(),
}
}
// SetHostinfo clones the provided Hostinfo and remembers it for the
// next update.
func (c *Direct) SetHostinfo(hi *tailcfg.Hostinfo) {
// next update. It reports whether the Hostinfo has changed.
func (c *Direct) SetHostinfo(hi *tailcfg.Hostinfo) bool {
if hi == nil {
panic("nil Hostinfo")
}
c.mu.Lock()
defer c.mu.Unlock()
c.logf("Hostinfo: %v\n", hi)
if hi.Equal(c.hostinfo) {
return false
}
c.hostinfo = hi.Clone()
return true
}
// SetNetInfo clones the provided NetInfo and remembers it for the
// next update.
func (c *Direct) SetNetInfo(ni *tailcfg.NetInfo) {
// next update. It reports whether the NetInfo has changed.
func (c *Direct) SetNetInfo(ni *tailcfg.NetInfo) bool {
if ni == nil {
panic("nil NetInfo")
}
@@ -187,10 +201,13 @@ func (c *Direct) SetNetInfo(ni *tailcfg.NetInfo) {
if c.hostinfo == nil {
c.logf("[unexpected] SetNetInfo called with no HostInfo; ignoring NetInfo update: %+v", ni)
return
return false
}
if reflect.DeepEqual(ni, c.hostinfo.NetInfo) {
return false
}
c.logf("NetInfo: %v\n", ni)
c.hostinfo.NetInfo = ni.Clone()
return true
}
func (c *Direct) GetPersist() Persist {
@@ -207,7 +224,7 @@ const (
)
func (c *Direct) TryLogout(ctx context.Context) error {
c.logf("direct.TryLogout()\n")
c.logf("direct.TryLogout()")
c.mu.Lock()
defer c.mu.Unlock()
@@ -223,12 +240,12 @@ func (c *Direct) TryLogout(ctx context.Context) error {
}
func (c *Direct) TryLogin(ctx context.Context, t *oauth2.Token, flags LoginFlags) (url string, err error) {
c.logf("direct.TryLogin(%v, %v)\n", t != nil, flags)
c.logf("direct.TryLogin(%v, %v)", t != nil, flags)
return c.doLoginOrRegen(ctx, t, flags, false, "")
}
func (c *Direct) WaitLoginURL(ctx context.Context, url string) (newUrl string, err error) {
c.logf("direct.WaitLoginURL\n")
c.logf("direct.WaitLoginURL")
return c.doLoginOrRegen(ctx, nil, LoginDefault, false, url)
}
@@ -248,11 +265,14 @@ func (c *Direct) doLogin(ctx context.Context, t *oauth2.Token, flags LoginFlags,
persist := c.persist
tryingNewKey := c.tryingNewKey
serverKey := c.serverKey
authKey := c.authKey
hostinfo := c.hostinfo.Clone()
backendLogID := hostinfo.BackendLogID
expired := c.expiry != nil && !c.expiry.IsZero() && c.expiry.Before(c.timeNow())
c.mu.Unlock()
if persist.PrivateMachineKey == (wgcfg.PrivateKey{}) {
c.logf("Generating a new machinekey.\n")
c.logf("Generating a new machinekey.")
mkey, err := wgcfg.NewPrivateKey()
if err != nil {
log.Fatal(err)
@@ -261,15 +281,15 @@ func (c *Direct) doLogin(ctx context.Context, t *oauth2.Token, flags LoginFlags,
}
if expired {
c.logf("Old key expired -> regen=true\n")
c.logf("Old key expired -> regen=true")
regen = true
}
if (flags & LoginInteractive) != 0 {
c.logf("LoginInteractive -> regen=true\n")
c.logf("LoginInteractive -> regen=true")
regen = true
}
c.logf("doLogin(regen=%v, hasUrl=%v)\n", regen, url != "")
c.logf("doLogin(regen=%v, hasUrl=%v)", regen, url != "")
if serverKey == (wgcfg.Key{}) {
var err error
serverKey, err = loadServerKey(ctx, c.httpc, c.serverURL)
@@ -285,7 +305,7 @@ func (c *Direct) doLogin(ctx context.Context, t *oauth2.Token, flags LoginFlags,
var oldNodeKey wgcfg.Key
if url != "" {
} else if regen || persist.PrivateNodeKey == (wgcfg.PrivateKey{}) {
c.logf("Generating a new nodekey.\n")
c.logf("Generating a new nodekey.")
persist.OldPrivateNodeKey = persist.PrivateNodeKey
key, err := wgcfg.NewPrivateKey()
if err != nil {
@@ -302,9 +322,9 @@ func (c *Direct) doLogin(ctx context.Context, t *oauth2.Token, flags LoginFlags,
}
if tryingNewKey == (wgcfg.PrivateKey{}) {
log.Fatalf("tryingNewKey is empty, give up\n")
log.Fatalf("tryingNewKey is empty, give up")
}
if c.hostinfo.BackendLogID == "" {
if backendLogID == "" {
err = errors.New("hostinfo: BackendLogID missing")
return regen, url, err
}
@@ -312,15 +332,16 @@ func (c *Direct) doLogin(ctx context.Context, t *oauth2.Token, flags LoginFlags,
Version: 1,
OldNodeKey: tailcfg.NodeKey(oldNodeKey),
NodeKey: tailcfg.NodeKey(tryingNewKey.Public()),
Hostinfo: c.hostinfo,
Hostinfo: hostinfo,
Followup: url,
}
c.logf("RegisterReq: onode=%v node=%v fup=%v\n",
request.OldNodeKey.AbbrevString(),
request.NodeKey.AbbrevString(), url != "")
c.logf("RegisterReq: onode=%v node=%v fup=%v",
request.OldNodeKey.ShortString(),
request.NodeKey.ShortString(), url != "")
request.Auth.Oauth2Token = t
request.Auth.Provider = persist.Provider
request.Auth.LoginName = persist.LoginName
request.Auth.AuthKey = authKey
bodyData, err := encode(request, &serverKey, &persist.PrivateMachineKey)
if err != nil {
return regen, url, err
@@ -338,7 +359,7 @@ func (c *Direct) doLogin(ctx context.Context, t *oauth2.Token, flags LoginFlags,
if err != nil {
return regen, url, fmt.Errorf("register request: %v", err)
}
c.logf("RegisterReq: returned.\n")
c.logf("RegisterReq: returned.")
resp := tailcfg.RegisterResponse{}
if err := decode(res, &resp, &serverKey, &persist.PrivateMachineKey); err != nil {
return regen, url, fmt.Errorf("register request: %v", err)
@@ -349,7 +370,7 @@ func (c *Direct) doLogin(ctx context.Context, t *oauth2.Token, flags LoginFlags,
return true, "", fmt.Errorf("weird: regen=true but server says NodeKeyExpired: %v", request.NodeKey)
}
c.logf("server reports new node key %v has expired",
request.NodeKey.AbbrevString())
request.NodeKey.ShortString())
return true, "", nil
}
if persist.Provider == "" {
@@ -366,9 +387,9 @@ func (c *Direct) doLogin(ctx context.Context, t *oauth2.Token, flags LoginFlags,
// - user is disabled
if resp.AuthURL != "" {
c.logf("AuthURL is %.20v...\n", resp.AuthURL)
c.logf("AuthURL is %v", resp.AuthURL)
} else {
c.logf("No AuthURL\n")
c.logf("No AuthURL")
}
c.mu.Lock()
@@ -415,7 +436,7 @@ func (c *Direct) newEndpoints(localPort uint16, endpoints []string) (changed boo
if c.localPort == localPort && sameStrings(c.endpoints, endpoints) {
return false // unchanged
}
c.logf("client.newEndpoints(%v, %v)\n", localPort, endpoints)
c.logf("client.newEndpoints(%v, %v)", localPort, endpoints)
c.localPort = localPort
c.endpoints = append(c.endpoints[:0], endpoints...)
return true // changed
@@ -435,25 +456,34 @@ func (c *Direct) PollNetMap(ctx context.Context, maxPolls int, cb func(*NetworkM
persist := c.persist
serverURL := c.serverURL
serverKey := c.serverKey
hostinfo := c.hostinfo
hostinfo := c.hostinfo.Clone()
backendLogID := hostinfo.BackendLogID
localPort := c.localPort
ep := append([]string(nil), c.endpoints...)
c.mu.Unlock()
if hostinfo.BackendLogID == "" {
if backendLogID == "" {
return errors.New("hostinfo: BackendLogID missing")
}
allowStream := maxPolls != 1
c.logf("PollNetMap: stream=%v :%v %v\n", maxPolls, localPort, ep)
c.logf("PollNetMap: stream=%v :%v %v", maxPolls, localPort, ep)
vlogf := logger.Discard
if Debug.NetMap {
vlogf = c.logf
}
request := tailcfg.MapRequest{
Version: 4,
KeepAlive: c.keepAlive,
NodeKey: tailcfg.NodeKey(persist.PrivateNodeKey.Public()),
Endpoints: ep,
Stream: allowStream,
Hostinfo: hostinfo,
Version: 4,
IncludeIPv6: true,
KeepAlive: c.keepAlive,
NodeKey: tailcfg.NodeKey(persist.PrivateNodeKey.Public()),
DiscoKey: c.discoPubKey,
Endpoints: ep,
Stream: allowStream,
Hostinfo: hostinfo,
DebugForceDisco: Debug.ForceDisco,
}
if c.newDecompressor != nil {
request.Compress = "zstd"
@@ -461,9 +491,11 @@ func (c *Direct) PollNetMap(ctx context.Context, maxPolls int, cb func(*NetworkM
bodyData, err := encode(request, &serverKey, &persist.PrivateMachineKey)
if err != nil {
vlogf("netmap: encode: %v", err)
return err
}
t0 := time.Now()
u := fmt.Sprintf("%s/machine/%s/map", serverURL, persist.PrivateMachineKey.Public().HexString())
req, err := http.NewRequest("POST", u, bytes.NewReader(bodyData))
if err != nil {
@@ -475,8 +507,10 @@ func (c *Direct) PollNetMap(ctx context.Context, maxPolls int, cb func(*NetworkM
res, err := c.httpc.Do(req)
if err != nil {
vlogf("netmap: Do: %v", err)
return err
}
vlogf("netmap: Do = %v after %v", res.StatusCode, time.Since(t0).Round(time.Millisecond))
if res.StatusCode != 200 {
msg, _ := ioutil.ReadAll(res.Body)
res.Body.Close()
@@ -491,26 +525,35 @@ func (c *Direct) PollNetMap(ctx context.Context, maxPolls int, cb func(*NetworkM
const pollTimeout = 120 * time.Second
timeout := time.NewTimer(pollTimeout)
timeoutReset := make(chan struct{})
defer close(timeoutReset)
pollDone := make(chan struct{})
defer close(pollDone)
go func() {
for {
select {
case <-pollDone:
vlogf("netmap: ending timeout goroutine")
return
case <-timeout.C:
c.logf("map response long-poll timed out!")
cancel()
return
case _, ok := <-timeoutReset:
if !ok {
return // channel closed, shut down goroutine
}
case <-timeoutReset:
if !timeout.Stop() {
<-timeout.C
select {
case <-timeout.C:
case <-pollDone:
vlogf("netmap: ending timeout goroutine")
return
}
}
vlogf("netmap: reset timeout timer")
timeout.Reset(pollTimeout)
}
}
}()
var lastDERPMap *tailcfg.DERPMap
// If allowStream, then the server will use an HTTP long poll to
// return incremental results. There is always one response right
// away, followed by a delay, and eventually others.
@@ -519,33 +562,58 @@ func (c *Direct) PollNetMap(ctx context.Context, maxPolls int, cb func(*NetworkM
// We can use this same read loop either way.
var msg []byte
for i := 0; i < maxPolls || maxPolls < 0; i++ {
vlogf("netmap: starting size read after %v (poll %v)", time.Since(t0).Round(time.Millisecond), i)
var siz [4]byte
if _, err := io.ReadFull(res.Body, siz[:]); err != nil {
vlogf("netmap: size read error after %v: %v", time.Since(t0).Round(time.Millisecond), err)
return err
}
size := binary.LittleEndian.Uint32(siz[:])
vlogf("netmap: read size %v after %v", size, time.Since(t0).Round(time.Millisecond))
msg = append(msg[:0], make([]byte, size)...)
if _, err := io.ReadFull(res.Body, msg); err != nil {
vlogf("netmap: body read error: %v", err)
return err
}
vlogf("netmap: read body after %v", time.Since(t0).Round(time.Millisecond))
var resp tailcfg.MapResponse
// Default filter if the key is missing from the incoming
// json (ie. old tailcontrol server without PacketFilter
// support). If even an empty PacketFilter is provided, this
// will be overwritten.
// TODO(apenwarr 2020-02-01): remove after tailcontrol is fully deployed.
resp.PacketFilter = filter.MatchAllowAll.Clone()
if err := c.decodeMsg(msg, &resp); err != nil {
vlogf("netmap: decode error: %v")
return err
}
if resp.KeepAlive {
c.logf("map response keep alive received")
timeoutReset <- struct{}{}
vlogf("netmap: got keep-alive")
select {
case timeoutReset <- struct{}{}:
vlogf("netmap: sent keep-alive timer reset")
case <-ctx.Done():
c.logf("netmap: not resetting timer for keep-alive due to: %v", ctx.Err())
return ctx.Err()
}
continue
}
vlogf("netmap: got new map")
if resp.DERPMap != nil {
vlogf("netmap: new map contains DERP map")
lastDERPMap = resp.DERPMap
}
if resp.Debug != nil && resp.Debug.LogHeapPprof {
go logheap.LogHeap(resp.Debug.LogHeapURL)
}
// Temporarily (2020-06-29) support removing all but
// discovery-supporting nodes during development, for
// less noise.
if Debug.OnlyDisco {
filtered := resp.Peers[:0]
for _, p := range resp.Peers {
if !p.DiscoKey.IsZero() {
filtered = append(filtered, p)
}
}
resp.Peers = filtered
}
nm := &NetworkMap{
NodeKey: tailcfg.NodeKey(persist.PrivateNodeKey.Public()),
@@ -561,15 +629,9 @@ func (c *Direct) PollNetMap(ctx context.Context, maxPolls int, cb func(*NetworkM
DNS: resp.DNS,
DNSDomains: resp.SearchPaths,
Hostinfo: resp.Node.Hostinfo,
PacketFilter: resp.PacketFilter,
}
// Temporary (2020-02-21) knob to force debug, during DERP testing:
if ok, _ := strconv.ParseBool(os.Getenv("DEBUG_FORCE_DERP")); ok {
c.logf("debug: adding DERP endpoints to all peers")
for i := range nm.Peers {
peer := &nm.Peers[i]
peer.Endpoints = append([]string{"127.3.3.40:1"}, peer.Endpoints...)
}
PacketFilter: c.parsePacketFilter(resp.PacketFilter),
DERPMap: lastDERPMap,
Debug: resp.Debug,
}
for _, profile := range resp.UserProfiles {
nm.UserProfiles[profile.ID] = profile
@@ -579,7 +641,17 @@ func (c *Direct) PollNetMap(ctx context.Context, maxPolls int, cb func(*NetworkM
} else {
nm.MachineStatus = tailcfg.MachineUnauthorized
}
//c.logf("new network map[%d]:\n%s", i, nm.Concise())
// Printing the netmap can be extremely verbose, but is very
// handy for debugging. Let's limit how often we do it.
// Code elsewhere prints netmap diffs every time, so this
// occasional full dump, plus incremental diffs, should do
// the job.
now := c.timeNow()
if now.Sub(c.lastPrintMap) >= 5*time.Minute {
c.lastPrintMap = now
c.logf("new network map[%d]:\n%s", i, nm.Concise())
}
c.mu.Lock()
c.expiry = &nm.Expiry
@@ -606,8 +678,10 @@ func decode(res *http.Response, v interface{}, serverKey *wgcfg.Key, mkey *wgcfg
}
func (c *Direct) decodeMsg(msg []byte, v interface{}) error {
c.mu.Lock()
mkey := c.persist.PrivateMachineKey
serverKey := c.serverKey
c.mu.Unlock()
decrypted, err := decryptMsg(msg, &serverKey, &mkey)
if err != nil {
@@ -617,7 +691,6 @@ func (c *Direct) decodeMsg(msg []byte, v interface{}) error {
if c.newDecompressor == nil {
b = decrypted
} else {
//decoder, err := zstd.NewReader(nil)
decoder, err := c.newDecompressor()
if err != nil {
return err
@@ -706,3 +779,39 @@ func loadServerKey(ctx context.Context, httpc *http.Client, serverURL string) (w
}
return key, nil
}
// Debug contains temporary internal-only debug knobs.
// They're unexported to not draw attention to them.
var Debug = initDebug()
type debug struct {
NetMap bool
OnlyDisco bool
Disco bool
ForceDisco bool // ask control server to not filter out our disco key
}
func initDebug() debug {
d := debug{
NetMap: envBool("TS_DEBUG_NETMAP"),
OnlyDisco: os.Getenv("TS_DEBUG_USE_DISCO") == "only",
ForceDisco: os.Getenv("TS_DEBUG_USE_DISCO") == "only" || envBool("TS_DEBUG_USE_DISCO"),
}
if d.ForceDisco || os.Getenv("TS_DEBUG_USE_DISCO") == "" {
// This is now defaults to on.
d.Disco = true
}
return d
}
func envBool(k string) bool {
e := os.Getenv(k)
if e == "" {
return false
}
v, err := strconv.ParseBool(e)
if err != nil {
panic(fmt.Sprintf("invalid non-bool %q for env var %q", e, k))
}
return v
}

View File

@@ -1,305 +0,0 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build depends_on_currently_unreleased
package controlclient
import (
"context"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"testing"
"time"
"github.com/klauspost/compress/zstd"
"github.com/tailscale/wireguard-go/wgcfg"
"tailscale.com/tailcfg"
"tailscale.io/control" // not yet released
)
func TestClientsReusingKeys(t *testing.T) {
tmpdir, err := ioutil.TempDir("", "control-test-")
if err != nil {
t.Fatal(err)
}
var server *control.Server
httpsrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
server.ServeHTTP(w, r)
}))
server, err = control.New(tmpdir, httpsrv.URL, true)
if err != nil {
t.Fatal(err)
}
server.QuietLogging = true
defer func() {
httpsrv.CloseClientConnections()
httpsrv.Close()
os.RemoveAll(tmpdir)
}()
hi := NewHostinfo()
hi.FrontendLogID = "go-test-only"
hi.BackendLogID = "go-test-only"
c1, err := NewDirect(Options{
ServerURL: httpsrv.URL,
HTTPC: httpsrv.Client(),
//TimeNow: s.control.TimeNow,
Logf: func(fmt string, args ...interface{}) {
t.Helper()
t.Logf("c1: "+fmt, args...)
},
Hostinfo: hi,
})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
authURL, err := c1.TryLogin(ctx, nil, 0)
if err != nil {
t.Fatal(err)
}
const user = "testuser1@tailscale.onmicrosoft.com"
postAuthURL(t, ctx, httpsrv.Client(), user, authURL)
newURL, err := c1.WaitLoginURL(ctx, authURL)
if err != nil {
t.Fatal(err)
}
if newURL != "" {
t.Fatalf("unexpected newURL: %s", newURL)
}
pollErrCh := make(chan error)
go func() {
err := c1.PollNetMap(ctx, -1, func(netMap *NetworkMap) {})
pollErrCh <- err
}()
select {
case err := <-pollErrCh:
t.Fatal(err)
default:
}
c2, err := NewDirect(Options{
ServerURL: httpsrv.URL,
HTTPC: httpsrv.Client(),
Logf: func(fmt string, args ...interface{}) {
t.Helper()
t.Logf("c2: "+fmt, args...)
},
Persist: c1.GetPersist(),
Hostinfo: hi,
NewDecompressor: func() (Decompressor, error) {
return zstd.NewReader(nil)
},
KeepAlive: true,
})
if err != nil {
t.Fatal(err)
}
authURL, err = c2.TryLogin(ctx, nil, 0)
if err != nil {
t.Fatal(err)
}
if authURL != "" {
t.Errorf("unexpected authURL %s", authURL)
}
err = c2.PollNetMap(ctx, 1, func(netMap *NetworkMap) {})
if err != nil {
t.Fatal(err)
}
select {
case err := <-pollErrCh:
t.Logf("expected poll error: %v", err)
case <-time.After(5 * time.Second):
t.Fatal("first client poll failed to close")
}
}
func TestClientsReusingOldKey(t *testing.T) {
tmpdir, err := ioutil.TempDir("", "control-test-")
if err != nil {
t.Fatal(err)
}
var server *control.Server
httpsrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
server.ServeHTTP(w, r)
}))
server, err = control.New(tmpdir, httpsrv.URL, true)
if err != nil {
t.Fatal(err)
}
server.QuietLogging = true
defer func() {
httpsrv.CloseClientConnections()
httpsrv.Close()
os.RemoveAll(tmpdir)
}()
hi := NewHostinfo()
hi.FrontendLogID = "go-test-only"
hi.BackendLogID = "go-test-only"
genOpts := func() Options {
return Options{
ServerURL: httpsrv.URL,
HTTPC: httpsrv.Client(),
//TimeNow: s.control.TimeNow,
Logf: func(fmt string, args ...interface{}) {
t.Helper()
t.Logf("c1: "+fmt, args...)
},
Hostinfo: hi,
}
}
// Login with a new node key. This requires authorization.
c1, err := NewDirect(genOpts())
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
authURL, err := c1.TryLogin(ctx, nil, 0)
if err != nil {
t.Fatal(err)
}
const user = "testuser1@tailscale.onmicrosoft.com"
postAuthURL(t, ctx, httpsrv.Client(), user, authURL)
newURL, err := c1.WaitLoginURL(ctx, authURL)
if err != nil {
t.Fatal(err)
}
if newURL != "" {
t.Fatalf("unexpected newURL: %s", newURL)
}
if err := c1.PollNetMap(ctx, 1, func(netMap *NetworkMap) {}); err != nil {
t.Fatal(err)
}
newPrivKey := func(t *testing.T) wgcfg.PrivateKey {
t.Helper()
k, err := wgcfg.NewPrivateKey()
if err != nil {
t.Fatal(err)
}
return k
}
// Replace the previous key with a new key.
persist1 := c1.GetPersist()
persist2 := Persist{
PrivateMachineKey: persist1.PrivateMachineKey,
OldPrivateNodeKey: persist1.PrivateNodeKey,
PrivateNodeKey: newPrivKey(t),
}
opts := genOpts()
opts.Persist = persist2
c1, err = NewDirect(opts)
if err != nil {
t.Fatal(err)
}
if authURL, err := c1.TryLogin(ctx, nil, 0); err != nil {
t.Fatal(err)
} else if authURL == "" {
t.Fatal("expected authURL for reused oldNodeKey, got none")
} else {
postAuthURL(t, ctx, httpsrv.Client(), user, authURL)
if newURL, err := c1.WaitLoginURL(ctx, authURL); err != nil {
t.Fatal(err)
} else if newURL != "" {
t.Fatalf("unexpected newURL: %s", newURL)
}
}
if p := c1.GetPersist(); p.PrivateNodeKey != opts.Persist.PrivateNodeKey {
t.Error("unexpected node key change")
} else {
persist2 = p
}
// Here we simulate a client using using old persistent data.
// We use the key we have already replaced as the old node key.
// This requires the user to authenticate.
persist3 := Persist{
PrivateMachineKey: persist1.PrivateMachineKey,
OldPrivateNodeKey: persist1.PrivateNodeKey,
PrivateNodeKey: newPrivKey(t),
}
opts = genOpts()
opts.Persist = persist3
c1, err = NewDirect(opts)
if err != nil {
t.Fatal(err)
}
if authURL, err := c1.TryLogin(ctx, nil, 0); err != nil {
t.Fatal(err)
} else if authURL == "" {
t.Fatal("expected authURL for reused oldNodeKey, got none")
} else {
postAuthURL(t, ctx, httpsrv.Client(), user, authURL)
if newURL, err := c1.WaitLoginURL(ctx, authURL); err != nil {
t.Fatal(err)
} else if newURL != "" {
t.Fatalf("unexpected newURL: %s", newURL)
}
}
if err := c1.PollNetMap(ctx, 1, func(netMap *NetworkMap) {}); err != nil {
t.Fatal(err)
}
// At this point, there should only be one node for the machine key
// registered as active in the server.
mkey := tailcfg.MachineKey(persist1.PrivateMachineKey.Public())
nodeIDs, err := server.DB().MachineNodes(mkey)
if err != nil {
t.Fatal(err)
}
if len(nodeIDs) != 1 {
t.Logf("active nodes for machine key %v:", mkey)
for i, nodeID := range nodeIDs {
nodeKey := server.DB().NodeKey(nodeID)
t.Logf("\tnode %d: id=%v, key=%v", i, nodeID, nodeKey)
}
t.Fatalf("want 1 active node for the client machine, got %d", len(nodeIDs))
}
// Now try the previous node key. It should fail.
opts = genOpts()
opts.Persist = persist2
c1, err = NewDirect(opts)
if err != nil {
t.Fatal(err)
}
// TODO(crawshaw): make this return an actual error.
// Have cfgdb track expired keys, and when an expired key is reused
// produce an error.
if authURL, err := c1.TryLogin(ctx, nil, 0); err != nil {
t.Fatal(err)
} else if authURL == "" {
t.Fatal("expected authURL for reused nodeKey, got none")
} else {
postAuthURL(t, ctx, httpsrv.Client(), user, authURL)
if newURL, err := c1.WaitLoginURL(ctx, authURL); err != nil {
t.Fatal(err)
} else if newURL != "" {
t.Fatalf("unexpected newURL: %s", newURL)
}
}
if err := c1.PollNetMap(ctx, 1, func(netMap *NetworkMap) {}); err != nil {
t.Fatal(err)
}
if nodeIDs, err := server.DB().MachineNodes(mkey); err != nil {
t.Fatal(err)
} else if len(nodeIDs) != 1 {
t.Fatalf("want 1 active node for the client machine, got %d", len(nodeIDs))
}
}

View File

@@ -0,0 +1,84 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package controlclient
import (
"fmt"
"net"
"tailscale.com/tailcfg"
"tailscale.com/wgengine/filter"
)
func parseIP(host string, defaultBits int) (filter.Net, error) {
ip := net.ParseIP(host)
if ip != nil && ip.IsUnspecified() {
// For clarity, reject 0.0.0.0 as an input
return filter.NetNone, fmt.Errorf("ports=%#v: to allow all IP addresses, use *:port, not 0.0.0.0:port", host)
} else if ip == nil && host == "*" {
// User explicitly requested wildcard dst ip
return filter.NetAny, nil
} else {
if ip != nil {
ip = ip.To4()
}
if ip == nil || len(ip) != 4 {
return filter.NetNone, fmt.Errorf("ports=%#v: invalid IPv4 address", host)
}
return filter.Net{
IP: filter.NewIP(ip),
Mask: filter.Netmask(defaultBits),
}, nil
}
}
// Parse a backward-compatible FilterRule used by control's wire format,
// producing the most current filter.Matches format.
func (c *Direct) parsePacketFilter(pf []tailcfg.FilterRule) filter.Matches {
mm := make([]filter.Match, 0, len(pf))
var erracc error
for _, r := range pf {
m := filter.Match{}
for i, s := range r.SrcIPs {
bits := 32
if len(r.SrcBits) > i {
bits = r.SrcBits[i]
}
net, err := parseIP(s, bits)
if err != nil && erracc == nil {
erracc = err
continue
}
m.Srcs = append(m.Srcs, net)
}
for _, d := range r.DstPorts {
bits := 32
if d.Bits != nil {
bits = *d.Bits
}
net, err := parseIP(d.IP, bits)
if err != nil && erracc == nil {
erracc = err
continue
}
m.Dsts = append(m.Dsts, filter.NetPortRange{
Net: net,
Ports: filter.PortRange{
First: d.Ports.First,
Last: d.Ports.Last,
},
})
}
mm = append(mm, m)
}
if erracc != nil {
c.logf("parsePacketFilter: %s\n", erracc)
}
return mm
}

View File

@@ -5,18 +5,18 @@
package controlclient
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"log"
"net"
"reflect"
"strconv"
"strings"
"time"
"github.com/tailscale/wireguard-go/wgcfg"
"tailscale.com/tailcfg"
"tailscale.com/version"
"tailscale.com/types/logger"
"tailscale.com/wgengine/filter"
)
@@ -29,12 +29,19 @@ type NetworkMap struct {
Addresses []wgcfg.CIDR
LocalPort uint16 // used for debugging
MachineStatus tailcfg.MachineStatus
Peers []tailcfg.Node
Peers []*tailcfg.Node // sorted by Node.ID
DNS []wgcfg.IP
DNSDomains []string
Hostinfo tailcfg.Hostinfo
PacketFilter filter.Matches
// DERPMap is the last DERP server map received. It's reused
// between updates and should not be modified.
DERPMap *tailcfg.DERPMap
// Debug knobs from control server for debug or feature gating.
Debug *tailcfg.Debug
// ACLs
User tailcfg.UserID
@@ -47,55 +54,148 @@ type NetworkMap struct {
// TODO(crawshaw): Capabilities []tailcfg.Capability
}
func (n *NetworkMap) Equal(n2 *NetworkMap) bool {
// TODO(crawshaw): this is crude, but is an easy way to avoid bugs.
b, err := json.Marshal(n)
if err != nil {
panic(err)
}
b2, err := json.Marshal(n2)
if err != nil {
panic(err)
}
return bytes.Equal(b, b2)
}
func (nm NetworkMap) String() string {
return nm.Concise()
}
func keyString(key [32]byte) string {
b64 := base64.StdEncoding.EncodeToString(key[:])
abbrev := "invalid"
if len(b64) == 44 {
abbrev = b64[0:4] + "…" + b64[39:43]
}
return fmt.Sprintf("[%s]", abbrev)
}
func (nm *NetworkMap) Concise() string {
buf := new(strings.Builder)
fmt.Fprintf(buf, "NetworkMap: self: %v auth=%v :%v %v\n",
keyString(nm.NodeKey), nm.MachineStatus,
nm.LocalPort, nm.Addresses)
nm.printConciseHeader(buf)
for _, p := range nm.Peers {
aip := make([]string, len(p.AllowedIPs))
for i, a := range p.AllowedIPs {
aip[i] = fmt.Sprint(a)
}
u := fmt.Sprint(p.User)
if strings.HasPrefix(u, "userid:") {
u = "u:" + u[7:]
}
f1 := fmt.Sprintf(" %v %-6v %v",
keyString(p.Key), u, p.Endpoints)
f2 := fmt.Sprintf(" %*v\n", 70-len(f1),
strings.Join(aip, " "))
fmt.Fprintf(buf, "%s%s", f1, f2)
printPeerConcise(buf, p)
}
return buf.String()
}
// printConciseHeader prints a concise header line representing nm to buf.
//
// If this function is changed to access different fields of nm, keep
// in equalConciseHeader in sync.
func (nm *NetworkMap) printConciseHeader(buf *strings.Builder) {
fmt.Fprintf(buf, "netmap: self: %v auth=%v",
nm.NodeKey.ShortString(), nm.MachineStatus)
if nm.LocalPort != 0 {
fmt.Fprintf(buf, " port=%v", nm.LocalPort)
}
if nm.Debug != nil {
j, _ := json.Marshal(nm.Debug)
fmt.Fprintf(buf, " debug=%s", j)
}
fmt.Fprintf(buf, " %v", nm.Addresses)
buf.WriteByte('\n')
}
// equalConciseHeader reports whether a and b are equal for the fields
// used by printConciseHeader.
func (a *NetworkMap) equalConciseHeader(b *NetworkMap) bool {
if a.NodeKey != b.NodeKey ||
a.MachineStatus != b.MachineStatus ||
a.LocalPort != b.LocalPort ||
len(a.Addresses) != len(b.Addresses) {
return false
}
for i, a := range a.Addresses {
if b.Addresses[i] != a {
return false
}
}
return (a.Debug == nil && b.Debug == nil) || reflect.DeepEqual(a.Debug, b.Debug)
}
// printPeerConcise appends to buf a line repsenting the peer p.
//
// If this function is changed to access different fields of p, keep
// in nodeConciseEqual in sync.
func printPeerConcise(buf *strings.Builder, p *tailcfg.Node) {
aip := make([]string, len(p.AllowedIPs))
for i, a := range p.AllowedIPs {
s := strings.TrimSuffix(fmt.Sprint(a), "/32")
aip[i] = s
}
ep := make([]string, len(p.Endpoints))
for i, e := range p.Endpoints {
// Align vertically on the ':' between IP and port
colon := strings.IndexByte(e, ':')
spaces := 0
for colon > 0 && len(e)+spaces-colon < 6 {
spaces++
colon--
}
ep[i] = fmt.Sprintf("%21v", e+strings.Repeat(" ", spaces))
}
derp := p.DERP
const derpPrefix = "127.3.3.40:"
if strings.HasPrefix(derp, derpPrefix) {
derp = "D" + derp[len(derpPrefix):]
}
// Most of the time, aip is just one element, so format the
// table to look good in that case. This will also make multi-
// subnet nodes stand out visually.
fmt.Fprintf(buf, " %v %-2v %-15v : %v\n",
p.Key.ShortString(), derp,
strings.Join(aip, " "),
strings.Join(ep, " "))
}
// nodeConciseEqual reports whether a and b are equal for the fields accessed by printPeerConcise.
func nodeConciseEqual(a, b *tailcfg.Node) bool {
return a.Key == b.Key &&
a.DERP == b.DERP &&
eqCIDRsIgnoreNil(a.AllowedIPs, b.AllowedIPs) &&
eqStringsIgnoreNil(a.Endpoints, b.Endpoints)
}
func (b *NetworkMap) ConciseDiffFrom(a *NetworkMap) string {
var diff strings.Builder
// See if header (non-peers, "bare") part of the network map changed.
// If so, print its diff lines first.
if !a.equalConciseHeader(b) {
diff.WriteByte('-')
a.printConciseHeader(&diff)
diff.WriteByte('+')
b.printConciseHeader(&diff)
}
aps, bps := a.Peers, b.Peers
for len(aps) > 0 && len(bps) > 0 {
pa, pb := aps[0], bps[0]
switch {
case pa.ID == pb.ID:
if !nodeConciseEqual(pa, pb) {
diff.WriteByte('-')
printPeerConcise(&diff, pa)
diff.WriteByte('+')
printPeerConcise(&diff, pb)
}
aps, bps = aps[1:], bps[1:]
case pa.ID > pb.ID:
// New peer in b.
diff.WriteByte('+')
printPeerConcise(&diff, pb)
bps = bps[1:]
case pb.ID > pa.ID:
// Deleted peer in b.
diff.WriteByte('-')
printPeerConcise(&diff, pa)
aps = aps[1:]
}
}
for _, pa := range aps {
diff.WriteByte('-')
printPeerConcise(&diff, pa)
}
for _, pb := range bps {
diff.WriteByte('+')
printPeerConcise(&diff, pb)
}
return diff.String()
}
func (nm *NetworkMap) JSON() string {
b, err := json.MarshalIndent(*nm, "", " ")
if err != nil {
@@ -104,187 +204,141 @@ func (nm *NetworkMap) JSON() string {
return string(b)
}
// TODO(apenwarr): delete me once relaynode doesn't need this anymore.
// control.go:userMap() supercedes it. This does not belong in the client.
func (nm *NetworkMap) UserMap() map[string][]filter.IP {
// Make a lookup table of roles
log.Printf("roles list is: %v\n", nm.Roles)
roles := make(map[tailcfg.RoleID]tailcfg.Role)
for _, role := range nm.Roles {
roles[role.ID] = role
}
// First, go through each node's addresses and make a lookup table
// of IP->User.
fwd := make(map[wgcfg.IP]string)
for _, node := range nm.Peers {
for _, addr := range node.Addresses {
if addr.Mask == 32 && addr.IP.Is4() {
user, ok := nm.UserProfiles[node.User]
if ok {
fwd[addr.IP] = user.LoginName
}
}
}
}
// Next, reverse the mapping into User->IP.
rev := make(map[string][]filter.IP)
for ip, username := range fwd {
ip4 := ip.To4()
if ip4 != nil {
fip := filter.NewIP(net.IP(ip4))
rev[username] = append(rev[username], fip)
}
}
// Now add roles, which are lists of users, and therefore lists
// of those users' IP addresses.
for _, user := range nm.UserProfiles {
for _, roleid := range user.Roles {
role, ok := roles[roleid]
if ok {
rolename := "role:" + role.Name
rev[rolename] = append(rev[rolename], rev[user.LoginName]...)
}
}
}
//log.Printf("Usermap is: %v\n", rev)
return rev
}
// WGConfigFlags is a bitmask of flags to control the behavior of the
// wireguard configuration generation done by NetMap.WGCfg.
type WGConfigFlags int
const (
UAllowSingleHosts = 1 << iota
UAllowSubnetRoutes
UAllowDefaultRoute
UHackDefaultRoute
UDefault = 0
AllowSingleHosts WGConfigFlags = 1 << iota
AllowSubnetRoutes
AllowDefaultRoute
HackDefaultRoute
)
// Several programs need to parse these arguments into uflags, so let's
// centralize it here.
func UFlagsHelper(uroutes, rroutes, droutes bool) int {
uflags := 0
if uroutes {
uflags |= UAllowSingleHosts
}
if rroutes {
uflags |= UAllowSubnetRoutes
}
if droutes {
uflags |= UAllowDefaultRoute
}
return uflags
}
func (nm *NetworkMap) UAPI(uflags int, dnsOverride []wgcfg.IP) string {
wgcfg, err := nm.WGCfg(uflags, dnsOverride)
// TODO(bradfitz): UAPI seems to only be used by the old confnode and
// pingnode; delete this when those are deleted/rewritten?
func (nm *NetworkMap) UAPI(flags WGConfigFlags, dnsOverride []wgcfg.IP) string {
wgcfg, err := nm.WGCfg(log.Printf, flags, dnsOverride)
if err != nil {
log.Fatalf("WGCfg() failed unexpectedly: %v\n", err)
log.Fatalf("WGCfg() failed unexpectedly: %v", err)
}
s, err := wgcfg.ToUAPI()
if err != nil {
log.Fatalf("ToUAPI() failed unexpectedly: %v\n", err)
log.Fatalf("ToUAPI() failed unexpectedly: %v", err)
}
return s
}
func (nm *NetworkMap) WGCfg(uflags int, dnsOverride []wgcfg.IP) (*wgcfg.Config, error) {
s := nm._WireGuardConfig(uflags, dnsOverride, true)
return wgcfg.FromWgQuick(s, "tailscale")
}
// EndpointDiscoSuffix is appended to the hex representation of a peer's discovery key
// and is then the sole wireguard endpoint for peers with a non-zero discovery key.
// This form is then recognize by magicsock's CreateEndpoint.
const EndpointDiscoSuffix = ".disco.tailscale:12345"
// TODO(apenwarr): This mode is dangerous.
// Discarding the extra endpoints is almost universally the wrong choice.
// Except that plain wireguard can't handle a peer with multiple endpoints.
// (Yet?)
func (nm *NetworkMap) WireGuardConfigOneEndpoint(uflags int, dnsOverride []wgcfg.IP) string {
return nm._WireGuardConfig(uflags, dnsOverride, false)
}
func (nm *NetworkMap) _WireGuardConfig(uflags int, dnsOverride []wgcfg.IP, allEndpoints bool) string {
buf := new(strings.Builder)
fmt.Fprintf(buf, "[Interface]\n")
fmt.Fprintf(buf, "PrivateKey = %s\n", base64.StdEncoding.EncodeToString(nm.PrivateKey[:]))
if len(nm.Addresses) > 0 {
fmt.Fprintf(buf, "Address = ")
for i, cidr := range nm.Addresses {
if i > 0 {
fmt.Fprintf(buf, ", ")
}
fmt.Fprintf(buf, "%s", cidr)
}
fmt.Fprintf(buf, "\n")
// WGCfg returns the NetworkMaps's Wireguard configuration.
func (nm *NetworkMap) WGCfg(logf logger.Logf, flags WGConfigFlags, dnsOverride []wgcfg.IP) (*wgcfg.Config, error) {
cfg := &wgcfg.Config{
Name: "tailscale",
PrivateKey: nm.PrivateKey,
Addresses: nm.Addresses,
ListenPort: nm.LocalPort,
DNS: append([]wgcfg.IP(nil), dnsOverride...),
Peers: make([]wgcfg.Peer, 0, len(nm.Peers)),
}
fmt.Fprintf(buf, "ListenPort = %d\n", nm.LocalPort)
if len(dnsOverride) > 0 {
dnss := []string{}
for _, ip := range dnsOverride {
dnss = append(dnss, ip.String())
}
fmt.Fprintf(buf, "DNS = %s\n", strings.Join(dnss, ","))
}
fmt.Fprintf(buf, "\n")
for i, peer := range nm.Peers {
if (uflags&UAllowSingleHosts) == 0 && len(peer.AllowedIPs) < 2 {
log.Printf("wgcfg: %v skipping a single-host peer.\n", peer.Key.AbbrevString())
for _, peer := range nm.Peers {
if Debug.OnlyDisco && peer.DiscoKey.IsZero() {
continue
}
if i > 0 {
fmt.Fprintf(buf, "\n")
if (flags&AllowSingleHosts) == 0 && len(peer.AllowedIPs) < 2 {
logf("wgcfg: %v skipping a single-host peer.", peer.Key.ShortString())
continue
}
fmt.Fprintf(buf, "[Peer]\n")
fmt.Fprintf(buf, "PublicKey = %s\n", base64.StdEncoding.EncodeToString(peer.Key[:]))
var endpoints []string
if peer.DERP != "" {
endpoints = append(endpoints, peer.DERP)
cfg.Peers = append(cfg.Peers, wgcfg.Peer{
PublicKey: wgcfg.Key(peer.Key),
})
cpeer := &cfg.Peers[len(cfg.Peers)-1]
if peer.KeepAlive {
cpeer.PersistentKeepalive = 25 // seconds
}
endpoints = append(endpoints, peer.Endpoints...)
if len(endpoints) > 0 {
if len(endpoints) == 1 {
fmt.Fprintf(buf, "Endpoint = %s", endpoints[0])
} else if allEndpoints {
// TODO(apenwarr): This mode is incompatible.
// Normal wireguard clients don't know how to
// parse it (yet?)
fmt.Fprintf(buf, "Endpoint = %s",
strings.Join(endpoints, ","))
} else {
fmt.Fprintf(buf, "Endpoint = %s # other endpoints: %s",
endpoints[0],
strings.Join(endpoints[1:], ", "))
if !peer.DiscoKey.IsZero() {
if err := appendEndpoint(cpeer, fmt.Sprintf("%x%s", peer.DiscoKey[:], EndpointDiscoSuffix)); err != nil {
return nil, err
}
cpeer.Endpoints = []wgcfg.Endpoint{{Host: fmt.Sprintf("%x.disco.tailscale", peer.DiscoKey[:]), Port: 12345}}
} else {
if err := appendEndpoint(cpeer, peer.DERP); err != nil {
return nil, err
}
for _, ep := range peer.Endpoints {
if err := appendEndpoint(cpeer, ep); err != nil {
return nil, err
}
}
buf.WriteByte('\n')
}
var aips []string
for _, allowedIP := range peer.AllowedIPs {
aip := allowedIP.String()
if allowedIP.Mask == 0 {
if (uflags & UAllowDefaultRoute) == 0 {
log.Printf("wgcfg: %v skipping default route\n", peer.Key.AbbrevString())
if (flags & AllowDefaultRoute) == 0 {
logf("wgcfg: %v skipping default route", peer.Key.ShortString())
continue
}
if (uflags & UHackDefaultRoute) != 0 {
aip = "10.0.0.0/8"
log.Printf("wgcfg: %v converting default route => %v\n", peer.Key.AbbrevString(), aip)
if (flags & HackDefaultRoute) != 0 {
allowedIP = wgcfg.CIDR{IP: wgcfg.IPv4(10, 0, 0, 0), Mask: 8}
logf("wgcfg: %v converting default route => %v", peer.Key.ShortString(), allowedIP.String())
}
} else if allowedIP.Mask < 32 {
if (uflags & UAllowSubnetRoutes) == 0 {
log.Printf("wgcfg: %v skipping subnet route\n", peer.Key.AbbrevString())
if (flags & AllowSubnetRoutes) == 0 {
logf("wgcfg: %v skipping subnet route", peer.Key.ShortString())
continue
}
}
aips = append(aips, aip)
}
fmt.Fprintf(buf, "AllowedIPs = %s\n", strings.Join(aips, ", "))
doKeepAlives := !version.IsMobile()
if doKeepAlives {
fmt.Fprintf(buf, "PersistentKeepalive = 25\n")
cpeer.AllowedIPs = append(cpeer.AllowedIPs, allowedIP)
}
}
return buf.String()
return cfg, nil
}
func appendEndpoint(peer *wgcfg.Peer, epStr string) error {
if epStr == "" {
return nil
}
host, port, err := net.SplitHostPort(epStr)
if err != nil {
return fmt.Errorf("malformed endpoint %q for peer %v", epStr, peer.PublicKey.ShortString())
}
port16, err := strconv.ParseUint(port, 10, 16)
if err != nil {
return fmt.Errorf("invalid port in endpoint %q for peer %v", epStr, peer.PublicKey.ShortString())
}
peer.Endpoints = append(peer.Endpoints, wgcfg.Endpoint{Host: host, Port: uint16(port16)})
return nil
}
// eqStringsIgnoreNil reports whether a and b have the same length and
// contents, but ignore whether a or b are nil.
func eqStringsIgnoreNil(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i, v := range a {
if v != b[i] {
return false
}
}
return true
}
// eqCIDRsIgnoreNil reports whether a and b have the same length and
// contents, but ignore whether a or b are nil.
func eqCIDRsIgnoreNil(a, b []wgcfg.CIDR) bool {
if len(a) != len(b) {
return false
}
for i, v := range a {
if v != b[i] {
return false
}
}
return true
}

View File

@@ -0,0 +1,217 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package controlclient
import (
"testing"
"tailscale.com/tailcfg"
)
func testNodeKey(b byte) (ret tailcfg.NodeKey) {
for i := range ret {
ret[i] = b
}
return
}
func TestNetworkMapConcise(t *testing.T) {
for _, tt := range []struct {
name string
nm *NetworkMap
want string
}{
{
name: "basic",
nm: &NetworkMap{
NodeKey: testNodeKey(1),
Peers: []*tailcfg.Node{
{
Key: testNodeKey(2),
DERP: "127.3.3.40:2",
Endpoints: []string{"192.168.0.100:12", "192.168.0.100:12354"},
},
{
Key: testNodeKey(3),
DERP: "127.3.3.40:4",
Endpoints: []string{"10.2.0.100:12", "10.1.0.100:12345"},
},
},
},
want: "netmap: self: [AQEBA] auth=machine-unknown []\n [AgICA] D2 : 192.168.0.100:12 192.168.0.100:12354\n [AwMDA] D4 : 10.2.0.100:12 10.1.0.100:12345\n",
},
{
name: "debug_non_nil",
nm: &NetworkMap{
NodeKey: testNodeKey(1),
Debug: &tailcfg.Debug{},
},
want: "netmap: self: [AQEBA] auth=machine-unknown debug={} []\n",
},
{
name: "debug_values",
nm: &NetworkMap{
NodeKey: testNodeKey(1),
Debug: &tailcfg.Debug{LogHeapPprof: true},
},
want: "netmap: self: [AQEBA] auth=machine-unknown debug={\"LogHeapPprof\":true} []\n",
},
} {
t.Run(tt.name, func(t *testing.T) {
var got string
n := int(testing.AllocsPerRun(1000, func() {
got = tt.nm.Concise()
}))
t.Logf("Allocs = %d", n)
if got != tt.want {
t.Errorf("Wrong output\n Got: %q\nWant: %q\n## Got (unescaped):\n%s\n## Want (unescaped):\n%s\n", got, tt.want, got, tt.want)
}
})
}
}
func TestConciseDiffFrom(t *testing.T) {
for _, tt := range []struct {
name string
a, b *NetworkMap
want string
}{
{
name: "no_change",
a: &NetworkMap{
NodeKey: testNodeKey(1),
Peers: []*tailcfg.Node{
{
Key: testNodeKey(2),
DERP: "127.3.3.40:2",
Endpoints: []string{"192.168.0.100:12", "192.168.0.100:12354"},
},
},
},
b: &NetworkMap{
NodeKey: testNodeKey(1),
Peers: []*tailcfg.Node{
{
Key: testNodeKey(2),
DERP: "127.3.3.40:2",
Endpoints: []string{"192.168.0.100:12", "192.168.0.100:12354"},
},
},
},
want: "",
},
{
name: "header_change",
a: &NetworkMap{
NodeKey: testNodeKey(1),
Peers: []*tailcfg.Node{
{
Key: testNodeKey(2),
DERP: "127.3.3.40:2",
Endpoints: []string{"192.168.0.100:12", "192.168.0.100:12354"},
},
},
},
b: &NetworkMap{
NodeKey: testNodeKey(2),
Peers: []*tailcfg.Node{
{
Key: testNodeKey(2),
DERP: "127.3.3.40:2",
Endpoints: []string{"192.168.0.100:12", "192.168.0.100:12354"},
},
},
},
want: "-netmap: self: [AQEBA] auth=machine-unknown []\n+netmap: self: [AgICA] auth=machine-unknown []\n",
},
{
name: "peer_add",
a: &NetworkMap{
NodeKey: testNodeKey(1),
Peers: []*tailcfg.Node{
{
ID: 2,
Key: testNodeKey(2),
DERP: "127.3.3.40:2",
Endpoints: []string{"192.168.0.100:12", "192.168.0.100:12354"},
},
},
},
b: &NetworkMap{
NodeKey: testNodeKey(1),
Peers: []*tailcfg.Node{
{
ID: 1,
Key: testNodeKey(1),
DERP: "127.3.3.40:1",
Endpoints: []string{"192.168.0.100:12", "192.168.0.100:12354"},
},
{
ID: 2,
Key: testNodeKey(2),
DERP: "127.3.3.40:2",
Endpoints: []string{"192.168.0.100:12", "192.168.0.100:12354"},
},
{
ID: 3,
Key: testNodeKey(3),
DERP: "127.3.3.40:3",
Endpoints: []string{"192.168.0.100:12", "192.168.0.100:12354"},
},
},
},
want: "+ [AQEBA] D1 : 192.168.0.100:12 192.168.0.100:12354\n+ [AwMDA] D3 : 192.168.0.100:12 192.168.0.100:12354\n",
},
{
name: "peer_remove",
a: &NetworkMap{
NodeKey: testNodeKey(1),
Peers: []*tailcfg.Node{
{
ID: 1,
Key: testNodeKey(1),
DERP: "127.3.3.40:1",
Endpoints: []string{"192.168.0.100:12", "192.168.0.100:12354"},
},
{
ID: 2,
Key: testNodeKey(2),
DERP: "127.3.3.40:2",
Endpoints: []string{"192.168.0.100:12", "192.168.0.100:12354"},
},
{
ID: 3,
Key: testNodeKey(3),
DERP: "127.3.3.40:3",
Endpoints: []string{"192.168.0.100:12", "192.168.0.100:12354"},
},
},
},
b: &NetworkMap{
NodeKey: testNodeKey(1),
Peers: []*tailcfg.Node{
{
ID: 2,
Key: testNodeKey(2),
DERP: "127.3.3.40:2",
Endpoints: []string{"192.168.0.100:12", "192.168.0.100:12354"},
},
},
},
want: "- [AQEBA] D1 : 192.168.0.100:12 192.168.0.100:12354\n- [AwMDA] D3 : 192.168.0.100:12 192.168.0.100:12354\n",
},
} {
t.Run(tt.name, func(t *testing.T) {
var got string
n := int(testing.AllocsPerRun(50, func() {
got = tt.b.ConciseDiffFrom(tt.a)
}))
t.Logf("Allocs = %d", n)
if got != tt.want {
t.Errorf("Wrong output\n Got: %q\nWant: %q\n## Got (unescaped):\n%s\n## Want (unescaped):\n%s\n", got, tt.want, got, tt.want)
}
})
}
}

View File

@@ -32,10 +32,11 @@ const MaxPacketSize = 64 << 10
const magic = "DERP🔑" // 8 bytes: 0x44 45 52 50 f0 9f 94 91
const (
nonceLen = 24
keyLen = 32
maxInfoLen = 1 << 20
keepAlive = 60 * time.Second
nonceLen = 24
frameHeaderLen = 1 + 4 // frameType byte + 4 byte length
keyLen = 32
maxInfoLen = 1 << 20
keepAlive = 60 * time.Second
)
// protocolVersion is bumped whenever there's a wire-incompatible change.
@@ -71,9 +72,35 @@ const (
frameClientInfo = frameType(0x02) // 32B pub key + 24B nonce + naclbox(json)
frameServerInfo = frameType(0x03) // 24B nonce + naclbox(json)
frameSendPacket = frameType(0x04) // 32B dest pub key + packet bytes
frameForwardPacket = frameType(0x0a) // 32B src pub key + 32B dst pub key + packet bytes
frameRecvPacket = frameType(0x05) // v0/1: packet bytes, v2: 32B src pub key + packet bytes
frameKeepAlive = frameType(0x06) // no payload, no-op (to be replaced with ping/pong)
frameNotePreferred = frameType(0x07) // 1 byte payload: 0x01 or 0x00 for whether this is client's home node
// framePeerGone is sent from server to client to signal that
// a previous sender is no longer connected. That is, if A
// sent to B, and then if A disconnects, the server sends
// framePeerGone to B so B can forget that a reverse path
// exists on that connection to get back to A.
framePeerGone = frameType(0x08) // 32B pub key of peer that's gone
// framePeerPresent is like framePeerGone, but for other
// members of the DERP region when they're meshed up together.
framePeerPresent = frameType(0x09) // 32B pub key of peer that's connected
// frameWatchConns is how one DERP node in a regional mesh
// subscribes to the others in the region.
// There's no payload. If the sender doesn't have permission, the connection
// is closed. Otherwise, the client is initially flooded with
// framePeerPresent for all connected nodes, and then a stream of
// framePeerPresent & framePeerGone has peers connect and disconnect.
frameWatchConns = frameType(0x10)
// frameClosePeer is a privileged frame type (requires the
// mesh key for now) that closes the provided peer's
// connection. (To be used for cluster load balancing
// purposes, when clients end up on a non-ideal node)
frameClosePeer = frameType(0x11) // 32B pub key of peer to close.
)
var bin = binary.BigEndian
@@ -131,7 +158,8 @@ func readFrame(br *bufio.Reader, maxSize uint32, b []byte) (t frameType, frameLe
if frameLen > maxSize {
return 0, 0, fmt.Errorf("frame header size %d exceeds reader limit of %d", frameLen, maxSize)
}
n, err := io.ReadFull(br, b[:frameLen])
n, err := io.ReadFull(br, b[:minUint32(frameLen, uint32(len(b)))])
if err != nil {
return 0, 0, err
}
@@ -172,3 +200,10 @@ func minInt(a, b int) int {
}
return b
}
func minUint32(a, b uint32) uint32 {
if a < b {
return a
}
return b
}

View File

@@ -11,7 +11,6 @@ import (
"errors"
"fmt"
"io"
"net"
"sync"
"time"
@@ -20,21 +19,57 @@ import (
"tailscale.com/types/logger"
)
// Client is a DERP client.
type Client struct {
serverKey key.Public // of the DERP server; not a machine or node key
privateKey key.Private
publicKey key.Public // of privateKey
protoVersion int // min of server+client
logf logger.Logf
nc net.Conn
nc Conn
br *bufio.Reader
meshKey string
wmu sync.Mutex // hold while writing to bw
bw *bufio.Writer
wmu sync.Mutex // hold while writing to bw
bw *bufio.Writer
// Owned by Recv:
peeked int // bytes to discard on next Recv
readErr error // sticky read error
}
func NewClient(privateKey key.Private, nc net.Conn, brw *bufio.ReadWriter, logf logger.Logf) (*Client, error) {
// ClientOpt is an option passed to NewClient.
type ClientOpt interface {
update(*clientOpt)
}
type clientOptFunc func(*clientOpt)
func (f clientOptFunc) update(o *clientOpt) { f(o) }
// clientOpt are the options passed to newClient.
type clientOpt struct {
MeshKey string
}
// MeshKey returns a ClientOpt to pass to the DERP server during connect to get
// access to join the mesh.
//
// An empty key means to not use a mesh key.
func MeshKey(key string) ClientOpt { return clientOptFunc(func(o *clientOpt) { o.MeshKey = key }) }
func NewClient(privateKey key.Private, nc Conn, brw *bufio.ReadWriter, logf logger.Logf, opts ...ClientOpt) (*Client, error) {
var opt clientOpt
for _, o := range opts {
if o == nil {
return nil, errors.New("nil ClientOpt")
}
o.update(&opt)
}
return newClient(privateKey, nc, brw, logf, opt)
}
func newClient(privateKey key.Private, nc Conn, brw *bufio.ReadWriter, logf logger.Logf, opt clientOpt) (*Client, error) {
c := &Client{
privateKey: privateKey,
publicKey: privateKey.Public(),
@@ -42,8 +77,8 @@ func NewClient(privateKey key.Private, nc net.Conn, brw *bufio.ReadWriter, logf
nc: nc,
br: brw.Reader,
bw: brw.Writer,
meshKey: opt.MeshKey,
}
if err := c.recvServerKey(); err != nil {
return nil, fmt.Errorf("derp.Client: failed to receive server key: %v", err)
}
@@ -110,6 +145,12 @@ func (c *Client) recvServerInfo() (*serverInfo, error) {
type clientInfo struct {
Version int // `json:"version,omitempty"`
// MeshKey optionally specifies a pre-shared key used by
// trusted clients. It's required to subscribe to the
// connection list & forward packets. It's empty for regular
// users.
MeshKey string // `json:"meshKey,omitempty"`
}
func (c *Client) sendClientKey() error {
@@ -117,7 +158,10 @@ func (c *Client) sendClientKey() error {
if _, err := crand.Read(nonce[:]); err != nil {
return err
}
msg, err := json.Marshal(clientInfo{Version: protocolVersion})
msg, err := json.Marshal(clientInfo{
Version: protocolVersion,
MeshKey: c.meshKey,
})
if err != nil {
return err
}
@@ -130,6 +174,9 @@ func (c *Client) sendClientKey() error {
return writeFrame(c.bw, frameClientInfo, buf)
}
// ServerPublicKey returns the server's public key.
func (c *Client) ServerPublicKey() key.Public { return c.serverKey }
// Send sends a packet to the Tailscale node identified by dstKey.
//
// It is an error if the packet is larger than 64KB.
@@ -138,7 +185,7 @@ func (c *Client) Send(dstKey key.Public, pkt []byte) error { return c.send(dstKe
func (c *Client) send(dstKey key.Public, pkt []byte) (ret error) {
defer func() {
if ret != nil {
ret = fmt.Errorf("derp.Send: %v", ret)
ret = fmt.Errorf("derp.Send: %w", ret)
}
}()
@@ -161,6 +208,40 @@ func (c *Client) send(dstKey key.Public, pkt []byte) (ret error) {
return c.bw.Flush()
}
func (c *Client) ForwardPacket(srcKey, dstKey key.Public, pkt []byte) (err error) {
defer func() {
if err != nil {
err = fmt.Errorf("derp.ForwardPacket: %w", err)
}
}()
if len(pkt) > MaxPacketSize {
return fmt.Errorf("packet too big: %d", len(pkt))
}
c.wmu.Lock()
defer c.wmu.Unlock()
timer := time.AfterFunc(5*time.Second, c.writeTimeoutFired)
defer timer.Stop()
if err := writeFrameHeader(c.bw, frameForwardPacket, uint32(keyLen*2+len(pkt))); err != nil {
return err
}
if _, err := c.bw.Write(srcKey[:]); err != nil {
return err
}
if _, err := c.bw.Write(dstKey[:]); err != nil {
return err
}
if _, err := c.bw.Write(pkt); err != nil {
return err
}
return c.bw.Flush()
}
func (c *Client) writeTimeoutFired() { c.nc.Close() }
// NotePreferred sends a packet that tells the server whether this
// client is the user's preferred server. This is only used in the
// server for stats.
@@ -187,6 +268,25 @@ func (c *Client) NotePreferred(preferred bool) (err error) {
return c.bw.Flush()
}
// WatchConnectionChanges sends a request to subscribe to the peer's connection list.
// It's a fatal error if the client wasn't created using MeshKey.
func (c *Client) WatchConnectionChanges() error {
c.wmu.Lock()
defer c.wmu.Unlock()
if err := writeFrameHeader(c.bw, frameWatchConns, 0); err != nil {
return err
}
return c.bw.Flush()
}
// ClosePeer asks the server to close target's TCP connection.
// It's a fatal error if the client wasn't created using MeshKey.
func (c *Client) ClosePeer(target key.Public) error {
c.wmu.Lock()
defer c.wmu.Unlock()
return writeFrame(c.bw, frameClosePeer, target[:])
}
// ReceivedMessage represents a type returned by Client.Recv. Unless
// otherwise documented, the returned message aliases the byte slice
// provided to Recv and thus the message is only as good as that
@@ -205,27 +305,80 @@ type ReceivedPacket struct {
func (ReceivedPacket) msg() {}
// PeerGoneMessage is a ReceivedMessage that indicates that the client
// identified by the underlying public key had previously sent you a
// packet but has now disconnected from the server.
type PeerGoneMessage key.Public
func (PeerGoneMessage) msg() {}
// PeerPresentMessage is a ReceivedMessage that indicates that the client
// is connected to the server. (Only used by trusted mesh clients)
type PeerPresentMessage key.Public
func (PeerPresentMessage) msg() {}
// Recv reads a message from the DERP server.
// The provided buffer must be large enough to receive a complete packet,
// which in practice are are 1.5-4 KB, but can be up to 64 KB.
//
// The returned message may alias memory owned by the Client; it
// should only be accessed until the next call to Client.
//
// Once Recv returns an error, the Client is dead forever.
func (c *Client) Recv(b []byte) (m ReceivedMessage, err error) {
func (c *Client) Recv() (m ReceivedMessage, err error) {
return c.recvTimeout(120 * time.Second)
}
func (c *Client) recvTimeout(timeout time.Duration) (m ReceivedMessage, err error) {
if c.readErr != nil {
return nil, c.readErr
}
defer func() {
if err != nil {
err = fmt.Errorf("derp.Recv: %v", err)
err = fmt.Errorf("derp.Recv: %w", err)
c.readErr = err
}
}()
for {
c.nc.SetReadDeadline(time.Now().Add(120 * time.Second))
t, n, err := readFrame(c.br, 1<<20, b)
c.nc.SetReadDeadline(time.Now().Add(timeout))
// Discard any peeked bytes from a previous Recv call.
if c.peeked != 0 {
if n, err := c.br.Discard(c.peeked); err != nil || n != c.peeked {
// Documented to never fail, but might as well check.
return nil, fmt.Errorf("bufio.Reader.Discard(%d bytes): got %v, %v", c.peeked, n, err)
}
c.peeked = 0
}
t, n, err := readFrameHeader(c.br)
if err != nil {
return nil, err
}
if n > 1<<20 {
return nil, fmt.Errorf("unexpectedly large frame of %d bytes returned", n)
}
var b []byte // frame payload (past the 5 byte header)
// If the frame fits in our bufio.Reader buffer, just use it.
// In practice it's 4KB (from derphttp.Client's bufio.NewReader(httpConn)) and
// in practive, WireGuard packets (and thus DERP frames) are under 1.5KB.
// So This is the common path.
if int(n) <= c.br.Size() {
b, err = c.br.Peek(int(n))
c.peeked = int(n)
} else {
// But if for some reason we read a large DERP message (which isn't necessarily
// a Wireguard packet), then just allocate memory for it.
// TODO(bradfitz): use a pool if large frames ever happen in practice.
b = make([]byte, n)
_, err = io.ReadFull(c.br, b)
}
if err != nil {
return nil, err
}
switch t {
default:
continue
@@ -233,6 +386,24 @@ func (c *Client) Recv(b []byte) (m ReceivedMessage, err error) {
// TODO: eventually we'll have server->client pings that
// require ack pongs.
continue
case framePeerGone:
if n < keyLen {
c.logf("[unexpected] dropping short peerGone frame from DERP server")
continue
}
var pg PeerGoneMessage
copy(pg[:], b[:keyLen])
return pg, nil
case framePeerPresent:
if n < keyLen {
c.logf("[unexpected] dropping short peerPresent frame from DERP server")
continue
}
var pg PeerPresentMessage
copy(pg[:], b[:keyLen])
return pg, nil
case frameRecvPacket:
var rp ReceivedPacket
if c.protoVersion < protocolSrcAddrs {

File diff suppressed because it is too large Load Diff

View File

@@ -6,15 +6,25 @@ package derp
import (
"bufio"
"context"
crand "crypto/rand"
"errors"
"expvar"
"fmt"
"io"
"net"
"reflect"
"sync"
"testing"
"time"
"tailscale.com/net/nettest"
"tailscale.com/types/key"
"tailscale.com/types/logger"
)
func newPrivateKey(t *testing.T) (k key.Private) {
t.Helper()
if _, err := crand.Read(k[:]); err != nil {
t.Fatal(err)
}
@@ -35,14 +45,14 @@ func TestSendRecv(t *testing.T) {
clientKeys = append(clientKeys, priv.Public())
}
ln, err := net.Listen("tcp", ":0")
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer ln.Close()
var clients []*Client
var connsOut []net.Conn
var connsOut []Conn
var recvChs []chan []byte
errCh := make(chan error, 3)
@@ -60,7 +70,8 @@ func TestSendRecv(t *testing.T) {
t.Fatal(err)
}
defer cin.Close()
go s.Accept(cin, bufio.NewReadWriter(bufio.NewReader(cin), bufio.NewWriter(cin)))
brwServer := bufio.NewReadWriter(bufio.NewReader(cin), bufio.NewWriter(cin))
go s.Accept(cin, brwServer, fmt.Sprintf("test-client-%d", i))
key := clientPrivateKeys[i]
brw := bufio.NewReadWriter(bufio.NewReader(cout), bufio.NewWriter(cout))
@@ -73,12 +84,13 @@ func TestSendRecv(t *testing.T) {
t.Logf("Connected client %d.", i)
}
var peerGoneCount expvar.Int
t.Logf("Starting read loops")
for i := 0; i < numClients; i++ {
go func(i int) {
for {
b := make([]byte, 1<<16)
m, err := clients[i].Recv(b)
m, err := clients[i].Recv()
if err != nil {
errCh <- err
return
@@ -87,11 +99,13 @@ func TestSendRecv(t *testing.T) {
default:
t.Errorf("unexpected message type %T", m)
continue
case PeerGoneMessage:
peerGoneCount.Add(1)
case ReceivedPacket:
if m.Source.IsZero() {
t.Errorf("zero Source address in ReceivedPacket")
}
recvChs[i] <- m.Data
recvChs[i] <- append([]byte(nil), m.Data...)
}
}
}(i)
@@ -131,6 +145,18 @@ func TestSendRecv(t *testing.T) {
t.Errorf("total/home=%v/%v; want %v/%v", gotTotal, gotHome, total, home)
}
wantClosedPeers := func(want int64) {
t.Helper()
var got int64
dl := time.Now().Add(5 * time.Second)
for time.Now().Before(dl) {
if got = peerGoneCount.Value(); got == want {
return
}
}
t.Errorf("peer gone count = %v; want %v", got, want)
}
msg1 := []byte("hello 0->1\n")
if err := clients[0].Send(clientKeys[1], msg1); err != nil {
t.Fatal(err)
@@ -160,13 +186,559 @@ func TestSendRecv(t *testing.T) {
wantActive(3, 1)
connsOut[1].Close()
wantActive(2, 0)
wantClosedPeers(1)
clients[2].NotePreferred(true)
wantActive(2, 1)
clients[2].NotePreferred(false)
wantActive(2, 0)
connsOut[2].Close()
wantActive(1, 0)
wantClosedPeers(1)
t.Logf("passed")
s.Close()
}
func TestSendFreeze(t *testing.T) {
serverPrivateKey := newPrivateKey(t)
s := NewServer(serverPrivateKey, t.Logf)
defer s.Close()
s.WriteTimeout = 100 * time.Millisecond
// We send two streams of messages:
//
// alice --> bob
// alice --> cathy
//
// Then cathy stops processing messsages.
// That should not interfere with alice talking to bob.
newClient := func(name string, k key.Private) (c *Client, clientConn nettest.Conn) {
t.Helper()
c1, c2 := nettest.NewConn(name, 1024)
go s.Accept(c1, bufio.NewReadWriter(bufio.NewReader(c1), bufio.NewWriter(c1)), name)
brw := bufio.NewReadWriter(bufio.NewReader(c2), bufio.NewWriter(c2))
c, err := NewClient(k, c2, brw, t.Logf)
if err != nil {
t.Fatal(err)
}
return c, c2
}
aliceKey := newPrivateKey(t)
aliceClient, aliceConn := newClient("alice", aliceKey)
bobKey := newPrivateKey(t)
bobClient, bobConn := newClient("bob", bobKey)
cathyKey := newPrivateKey(t)
cathyClient, cathyConn := newClient("cathy", cathyKey)
var (
aliceCh = make(chan struct{}, 32)
bobCh = make(chan struct{}, 32)
cathyCh = make(chan struct{}, 32)
)
chs := func(name string) chan struct{} {
switch name {
case "alice":
return aliceCh
case "bob":
return bobCh
case "cathy":
return cathyCh
default:
panic("unknown ch: " + name)
}
}
errCh := make(chan error, 4)
recv := func(name string, client *Client) {
ch := chs(name)
for {
m, err := client.Recv()
if err != nil {
errCh <- fmt.Errorf("%s: %w", name, err)
return
}
switch m := m.(type) {
default:
errCh <- fmt.Errorf("%s: unexpected message type %T", name, m)
return
case ReceivedPacket:
if m.Source.IsZero() {
errCh <- fmt.Errorf("%s: zero Source address in ReceivedPacket", name)
return
}
select {
case ch <- struct{}{}:
default:
}
}
}
}
go recv("alice", aliceClient)
go recv("bob", bobClient)
go recv("cathy", cathyClient)
var cancel func()
go func() {
t := time.NewTicker(2 * time.Millisecond)
defer t.Stop()
var ctx context.Context
ctx, cancel = context.WithCancel(context.Background())
for {
select {
case <-t.C:
case <-ctx.Done():
errCh <- nil
return
}
msg1 := []byte("hello alice->bob\n")
if err := aliceClient.Send(bobKey.Public(), msg1); err != nil {
errCh <- fmt.Errorf("alice send to bob: %w", err)
return
}
msg2 := []byte("hello alice->cathy\n")
// TODO: an error is expected here.
// We ignore it, maybe we should log it somehow?
aliceClient.Send(cathyKey.Public(), msg2)
}
}()
drainAny := func(ch chan struct{}) {
// We are draining potentially infinite sources,
// so place some reasonable upper limit.
//
// The important thing here is to make sure that
// if any tokens remain in the channel, they
// must have been generated after drainAny was
// called.
for i := 0; i < cap(ch); i++ {
select {
case <-ch:
default:
return
}
}
}
drain := func(t *testing.T, name string) bool {
t.Helper()
timer := time.NewTimer(1 * time.Second)
defer timer.Stop()
// Ensure ch has at least one element.
ch := chs(name)
select {
case <-ch:
case <-timer.C:
t.Errorf("no packet received by %s", name)
return false
}
// Drain remaining.
drainAny(ch)
return true
}
isEmpty := func(t *testing.T, name string) {
t.Helper()
select {
case <-chs(name):
t.Errorf("packet received by %s, want none", name)
default:
}
}
t.Run("initial send", func(t *testing.T) {
drain(t, "bob")
drain(t, "cathy")
isEmpty(t, "alice")
})
t.Run("block cathy", func(t *testing.T) {
// Block cathy. Now the cathyConn buffer will fill up quickly,
// and the derp server will back up.
cathyConn.SetReadBlock(true)
time.Sleep(2 * s.WriteTimeout)
drain(t, "bob")
drainAny(chs("cathy"))
isEmpty(t, "alice")
// Now wait a little longer, and ensure packets still flow to bob
if !drain(t, "bob") {
t.Errorf("connection alice->bob frozen by alice->cathy")
}
})
// Cleanup, make sure we process all errors.
t.Logf("TEST COMPLETE, cancelling sender")
cancel()
t.Logf("closing connections")
aliceConn.Close()
bobConn.Close()
cathyConn.Close()
for i := 0; i < cap(errCh); i++ {
err := <-errCh
if err != nil {
if errors.Is(err, io.EOF) {
continue
}
t.Error(err)
}
}
}
type testServer struct {
s *Server
ln net.Listener
logf logger.Logf
mu sync.Mutex
pubName map[key.Public]string
clients map[*testClient]bool
}
func (ts *testServer) addTestClient(c *testClient) {
ts.mu.Lock()
defer ts.mu.Unlock()
ts.clients[c] = true
}
func (ts *testServer) addKeyName(k key.Public, name string) {
ts.mu.Lock()
defer ts.mu.Unlock()
ts.pubName[k] = name
ts.logf("test adding named key %q for %x", name, k)
}
func (ts *testServer) keyName(k key.Public) string {
ts.mu.Lock()
defer ts.mu.Unlock()
if name, ok := ts.pubName[k]; ok {
return name
}
return k.ShortString()
}
func (ts *testServer) close(t *testing.T) error {
ts.ln.Close()
ts.s.Close()
for c := range ts.clients {
c.close(t)
}
return nil
}
func newTestServer(t *testing.T) *testServer {
t.Helper()
logf := logger.WithPrefix(t.Logf, "derp-server: ")
s := NewServer(newPrivateKey(t), logf)
s.SetMeshKey("mesh-key")
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
go func() {
i := 0
for {
i++
c, err := ln.Accept()
if err != nil {
return
}
// TODO: register c in ts so Close also closes it?
go func(i int) {
brwServer := bufio.NewReadWriter(bufio.NewReader(c), bufio.NewWriter(c))
go s.Accept(c, brwServer, fmt.Sprintf("test-client-%d", i))
}(i)
}
}()
return &testServer{
s: s,
ln: ln,
logf: logf,
clients: map[*testClient]bool{},
pubName: map[key.Public]string{},
}
}
type testClient struct {
name string
c *Client
nc net.Conn
pub key.Public
ts *testServer
closed bool
}
func newTestClient(t *testing.T, ts *testServer, name string, newClient func(net.Conn, key.Private, logger.Logf) (*Client, error)) *testClient {
t.Helper()
nc, err := net.Dial("tcp", ts.ln.Addr().String())
if err != nil {
t.Fatal(err)
}
key := newPrivateKey(t)
ts.addKeyName(key.Public(), name)
c, err := newClient(nc, key, logger.WithPrefix(t.Logf, "client-"+name+": "))
if err != nil {
t.Fatal(err)
}
tc := &testClient{
name: name,
nc: nc,
c: c,
ts: ts,
pub: key.Public(),
}
ts.addTestClient(tc)
return tc
}
func newRegularClient(t *testing.T, ts *testServer, name string) *testClient {
return newTestClient(t, ts, name, func(nc net.Conn, priv key.Private, logf logger.Logf) (*Client, error) {
brw := bufio.NewReadWriter(bufio.NewReader(nc), bufio.NewWriter(nc))
return NewClient(priv, nc, brw, logf)
})
}
func newTestWatcher(t *testing.T, ts *testServer, name string) *testClient {
return newTestClient(t, ts, name, func(nc net.Conn, priv key.Private, logf logger.Logf) (*Client, error) {
brw := bufio.NewReadWriter(bufio.NewReader(nc), bufio.NewWriter(nc))
c, err := NewClient(priv, nc, brw, logf, MeshKey("mesh-key"))
if err != nil {
return nil, err
}
if err := c.WatchConnectionChanges(); err != nil {
return nil, err
}
return c, nil
})
}
func (tc *testClient) wantPresent(t *testing.T, peers ...key.Public) {
t.Helper()
want := map[key.Public]bool{}
for _, k := range peers {
want[k] = true
}
for {
m, err := tc.c.recvTimeout(time.Second)
if err != nil {
t.Fatal(err)
}
switch m := m.(type) {
case PeerPresentMessage:
got := key.Public(m)
if !want[got] {
t.Fatalf("got peer present for %v; want present for %v", tc.ts.keyName(got), logger.ArgWriter(func(bw *bufio.Writer) {
for _, pub := range peers {
fmt.Fprintf(bw, "%s ", tc.ts.keyName(pub))
}
}))
}
delete(want, got)
if len(want) == 0 {
return
}
default:
t.Fatalf("unexpected message type %T", m)
}
}
}
func (tc *testClient) wantGone(t *testing.T, peer key.Public) {
t.Helper()
m, err := tc.c.recvTimeout(time.Second)
if err != nil {
t.Fatal(err)
}
switch m := m.(type) {
case PeerGoneMessage:
got := key.Public(m)
if peer != got {
t.Errorf("got gone message for %v; want gone for %v", tc.ts.keyName(got), tc.ts.keyName(peer))
}
default:
t.Fatalf("unexpected message type %T", m)
}
}
func (c *testClient) close(t *testing.T) {
t.Helper()
if c.closed {
return
}
c.closed = true
t.Logf("closing client %q (%x)", c.name, c.pub)
c.nc.Close()
}
// TestWatch tests the connection watcher mechanism used by regional
// DERP nodes to mesh up with each other.
func TestWatch(t *testing.T) {
ts := newTestServer(t)
defer ts.close(t)
w1 := newTestWatcher(t, ts, "w1")
w1.wantPresent(t, w1.pub)
c1 := newRegularClient(t, ts, "c1")
w1.wantPresent(t, c1.pub)
c2 := newRegularClient(t, ts, "c2")
w1.wantPresent(t, c2.pub)
w2 := newTestWatcher(t, ts, "w2")
w1.wantPresent(t, w2.pub)
w2.wantPresent(t, w1.pub, w2.pub, c1.pub, c2.pub)
c3 := newRegularClient(t, ts, "c3")
w1.wantPresent(t, c3.pub)
w2.wantPresent(t, c3.pub)
c2.close(t)
w1.wantGone(t, c2.pub)
w2.wantGone(t, c2.pub)
w3 := newTestWatcher(t, ts, "w3")
w1.wantPresent(t, w3.pub)
w2.wantPresent(t, w3.pub)
w3.wantPresent(t, c1.pub, c3.pub, w1.pub, w2.pub, w3.pub)
c1.close(t)
w1.wantGone(t, c1.pub)
w2.wantGone(t, c1.pub)
w3.wantGone(t, c1.pub)
}
type testFwd int
func (testFwd) ForwardPacket(key.Public, key.Public, []byte) error { panic("not called in tests") }
func pubAll(b byte) (ret key.Public) {
for i := range ret {
ret[i] = b
}
return
}
func TestForwarderRegistration(t *testing.T) {
s := &Server{
clients: make(map[key.Public]*sclient),
clientsMesh: map[key.Public]PacketForwarder{},
}
want := func(want map[key.Public]PacketForwarder) {
t.Helper()
if got := s.clientsMesh; !reflect.DeepEqual(got, want) {
t.Fatalf("mismatch\n got: %v\nwant: %v\n", got, want)
}
}
wantCounter := func(c *expvar.Int, want int) {
t.Helper()
if got := c.Value(); got != int64(want) {
t.Errorf("counter = %v; want %v", got, want)
}
}
u1 := pubAll(1)
u2 := pubAll(2)
u3 := pubAll(3)
s.AddPacketForwarder(u1, testFwd(1))
s.AddPacketForwarder(u2, testFwd(2))
want(map[key.Public]PacketForwarder{
u1: testFwd(1),
u2: testFwd(2),
})
// Verify a remove of non-registered forwarder is no-op.
s.RemovePacketForwarder(u2, testFwd(999))
want(map[key.Public]PacketForwarder{
u1: testFwd(1),
u2: testFwd(2),
})
// Verify a remove of non-registered user is no-op.
s.RemovePacketForwarder(u3, testFwd(1))
want(map[key.Public]PacketForwarder{
u1: testFwd(1),
u2: testFwd(2),
})
// Actual removal.
s.RemovePacketForwarder(u2, testFwd(2))
want(map[key.Public]PacketForwarder{
u1: testFwd(1),
})
// Adding a dup for a user.
wantCounter(&s.multiForwarderCreated, 0)
s.AddPacketForwarder(u1, testFwd(100))
want(map[key.Public]PacketForwarder{
u1: multiForwarder{
testFwd(1): 1,
testFwd(100): 2,
},
})
wantCounter(&s.multiForwarderCreated, 1)
// Removing a forwarder in a multi set that doesn't exist; does nothing.
s.RemovePacketForwarder(u1, testFwd(55))
want(map[key.Public]PacketForwarder{
u1: multiForwarder{
testFwd(1): 1,
testFwd(100): 2,
},
})
// Removing a forwarder in a multi set that does exist should collapse it away
// from being a multiForwarder.
wantCounter(&s.multiForwarderDeleted, 0)
s.RemovePacketForwarder(u1, testFwd(1))
want(map[key.Public]PacketForwarder{
u1: testFwd(100),
})
wantCounter(&s.multiForwarderDeleted, 1)
// Removing an entry for a client that's still connected locally should result
// in a nil forwarder.
u1c := &sclient{
key: u1,
logf: logger.Discard,
}
s.clients[u1] = u1c
s.RemovePacketForwarder(u1, testFwd(100))
want(map[key.Public]PacketForwarder{
u1: nil,
})
// But once that client disconnects, it should go away.
s.unregisterClient(u1c)
want(map[key.Public]PacketForwarder{})
// But if it already has a forwarder, it's not removed.
s.AddPacketForwarder(u1, testFwd(2))
s.unregisterClient(u1c)
want(map[key.Public]PacketForwarder{
u1: testFwd(2),
})
// Now pretend u1 was already connected locally (so clientsMesh[u1] is nil), and then we heard
// that they're also connected to a peer of ours. That sholdn't transition the forwarder
// from nil to the new one, not a multiForwarder.
s.clients[u1] = u1c
s.clientsMesh[u1] = nil
want(map[key.Public]PacketForwarder{
u1: nil,
})
s.AddPacketForwarder(u1, testFwd(3))
want(map[key.Public]PacketForwarder{
u1: testFwd(3),
})
}

View File

@@ -18,15 +18,18 @@ import (
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"net/url"
"sync"
"time"
"inet.af/netaddr"
"tailscale.com/derp"
"tailscale.com/net/dnscache"
"tailscale.com/net/netns"
"tailscale.com/net/tlsdial"
"tailscale.com/tailcfg"
"tailscale.com/types/key"
"tailscale.com/types/logger"
)
@@ -38,25 +41,51 @@ import (
// Send/Recv will completely re-establish the connection (unless Close
// has been called).
type Client struct {
TLSConfig *tls.Config // for sever connection, optional, nil means default
DNSCache *dnscache.Resolver // optional; if nil, no caching
TLSConfig *tls.Config // optional; nil means default
DNSCache *dnscache.Resolver // optional; nil means no caching
MeshKey string // optional; for trusted clients
privateKey key.Private
logf logger.Logf
url *url.URL
// Either url or getRegion is non-nil:
url *url.URL
getRegion func() *tailcfg.DERPRegion
ctx context.Context // closed via cancelCtx in Client.Close
cancelCtx context.CancelFunc
mu sync.Mutex
preferred bool
closed bool
netConn io.Closer
client *derp.Client
mu sync.Mutex
preferred bool
closed bool
netConn io.Closer
client *derp.Client
connGen int // incremented once per new connection; valid values are >0
serverPubKey key.Public
}
// NewRegionClient returns a new DERP-over-HTTP client. It connects lazily.
// To trigger a connection, use Connect.
func NewRegionClient(privateKey key.Private, logf logger.Logf, getRegion func() *tailcfg.DERPRegion) *Client {
ctx, cancel := context.WithCancel(context.Background())
c := &Client{
privateKey: privateKey,
logf: logf,
getRegion: getRegion,
ctx: ctx,
cancelCtx: cancel,
}
return c
}
// NewNetcheckClient returns a Client that's only able to have its DialRegion method called.
// It's used by the netcheck package.
func NewNetcheckClient(logf logger.Logf) *Client {
return &Client{logf: logf}
}
// NewClient returns a new DERP-over-HTTP client. It connects lazily.
// To trigger a connection use Connect.
// To trigger a connection, use Connect.
func NewClient(privateKey key.Private, serverURL string, logf logger.Logf) (*Client, error) {
u, err := url.Parse(serverURL)
if err != nil {
@@ -65,6 +94,7 @@ func NewClient(privateKey key.Private, serverURL string, logf logger.Logf) (*Cli
if urlPort(u) == "" {
return nil, fmt.Errorf("derphttp.NewClient: invalid URL scheme %q", u.Scheme)
}
ctx, cancel := context.WithCancel(context.Background())
c := &Client{
privateKey: privateKey,
@@ -79,10 +109,20 @@ func NewClient(privateKey key.Private, serverURL string, logf logger.Logf) (*Cli
// Connect connects or reconnects to the server, unless already connected.
// It returns nil if there was already a good connection, or if one was made.
func (c *Client) Connect(ctx context.Context) error {
_, err := c.connect(ctx, "derphttp.Client.Connect")
_, _, err := c.connect(ctx, "derphttp.Client.Connect")
return err
}
// ServerPublicKey returns the server's public key.
//
// It only returns a non-zero value once a connection has succeeded
// from an earlier call.
func (c *Client) ServerPublicKey() key.Public {
c.mu.Lock()
defer c.mu.Unlock()
return c.serverPubKey
}
func urlPort(u *url.URL) string {
if p := u.Port(); p != "" {
return p
@@ -96,18 +136,45 @@ func urlPort(u *url.URL) string {
return ""
}
func (c *Client) connect(ctx context.Context, caller string) (client *derp.Client, err error) {
func (c *Client) targetString(reg *tailcfg.DERPRegion) string {
if c.url != nil {
return c.url.String()
}
return fmt.Sprintf("region %d (%v)", reg.RegionID, reg.RegionCode)
}
func (c *Client) useHTTPS() bool {
if c.url != nil && c.url.Scheme == "http" {
return false
}
return true
}
// tlsServerName returns the tls.Config.ServerName value (for the TLS ClientHello).
func (c *Client) tlsServerName(node *tailcfg.DERPNode) string {
if c.url != nil {
return c.url.Host
}
return node.HostName
}
func (c *Client) urlString(node *tailcfg.DERPNode) string {
if c.url != nil {
return c.url.String()
}
return fmt.Sprintf("https://%s/derp", node.HostName)
}
func (c *Client) connect(ctx context.Context, caller string) (client *derp.Client, connGen int, err error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
return nil, ErrClientClosed
return nil, 0, ErrClientClosed
}
if c.client != nil {
return c.client, nil
return c.client, c.connGen, nil
}
c.logf("%s: connecting to %v", caller, c.url)
// timeout is the fallback maximum time (if ctx doesn't limit
// it further) to do all of: DNS + TCP + TLS + HTTP Upgrade +
// DERP upgrade.
@@ -127,39 +194,42 @@ func (c *Client) connect(ctx context.Context, caller string) (client *derp.Clien
}()
defer cancel()
var reg *tailcfg.DERPRegion // nil when using c.url to dial
if c.getRegion != nil {
reg = c.getRegion()
if reg == nil {
return nil, 0, errors.New("DERP region not available")
}
}
var tcpConn net.Conn
defer func() {
if err != nil {
if ctx.Err() != nil {
err = fmt.Errorf("%v: %v", ctx.Err(), err)
}
err = fmt.Errorf("%s connect to %v: %v", caller, c.url, err)
err = fmt.Errorf("%s connect to %v: %v", caller, c.targetString(reg), err)
if tcpConn != nil {
go tcpConn.Close()
}
}
}()
host := c.url.Hostname()
hostOrIP := host
var d net.Dialer
log.Printf("Dialing: %q", net.JoinHostPort(host, urlPort(c.url)))
if c.DNSCache != nil {
ip, err := c.DNSCache.LookupIP(ctx, host)
if err != nil {
return nil, err
}
hostOrIP = ip.String()
var node *tailcfg.DERPNode // nil when using c.url to dial
if c.url != nil {
c.logf("%s: connecting to %v", caller, c.url)
tcpConn, err = c.dialURL(ctx)
} else {
c.logf("%s: connecting to derp-%d (%v)", caller, reg.RegionID, reg.RegionCode)
tcpConn, node, err = c.dialRegion(ctx, reg)
}
tcpConn, err = d.DialContext(ctx, "tcp", net.JoinHostPort(hostOrIP, urlPort(c.url)))
if err != nil {
return nil, fmt.Errorf("dial of %q: %v", host, err)
return nil, 0, err
}
// Now that we have a TCP connection, force close it.
// Now that we have a TCP connection, force close it if the
// TLS handshake + DERP setup takes too long.
done := make(chan struct{})
defer close(done)
go func() {
@@ -183,66 +253,251 @@ func (c *Client) connect(ctx context.Context, caller string) (client *derp.Clien
}()
var httpConn net.Conn // a TCP conn or a TLS conn; what we speak HTTP to
if c.url.Scheme == "https" {
tlsConfig := &tls.Config{}
if c.TLSConfig != nil {
tlsConfig = c.TLSConfig.Clone()
}
tlsConfig.ServerName = c.url.Host
httpConn = tls.Client(tcpConn, tlsConfig)
if c.useHTTPS() {
httpConn = c.tlsClient(tcpConn, node)
} else {
httpConn = tcpConn
}
brw := bufio.NewReadWriter(bufio.NewReader(httpConn), bufio.NewWriter(httpConn))
req, err := http.NewRequest("GET", c.url.String(), nil)
req, err := http.NewRequest("GET", c.urlString(node), nil)
if err != nil {
return nil, err
return nil, 0, err
}
req.Header.Set("Upgrade", "DERP")
req.Header.Set("Connection", "Upgrade")
if err := req.Write(brw); err != nil {
return nil, err
return nil, 0, err
}
if err := brw.Flush(); err != nil {
return nil, err
return nil, 0, err
}
resp, err := http.ReadResponse(brw.Reader, req)
if err != nil {
return nil, err
return nil, 0, err
}
if resp.StatusCode != http.StatusSwitchingProtocols {
b, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
return nil, fmt.Errorf("GET failed: %v: %s", err, b)
return nil, 0, fmt.Errorf("GET failed: %v: %s", err, b)
}
derpClient, err := derp.NewClient(c.privateKey, httpConn, brw, c.logf)
derpClient, err := derp.NewClient(c.privateKey, httpConn, brw, c.logf, derp.MeshKey(c.MeshKey))
if err != nil {
return nil, err
return nil, 0, err
}
if c.preferred {
if err := derpClient.NotePreferred(true); err != nil {
go httpConn.Close()
return nil, 0, err
}
}
c.serverPubKey = derpClient.ServerPublicKey()
c.client = derpClient
c.netConn = tcpConn
c.connGen++
return c.client, c.connGen, nil
}
func (c *Client) dialURL(ctx context.Context) (net.Conn, error) {
host := c.url.Hostname()
hostOrIP := host
dialer := netns.NewDialer()
if c.DNSCache != nil {
ip, err := c.DNSCache.LookupIP(ctx, host)
if err == nil {
hostOrIP = ip.String()
}
if err != nil && netns.IsSOCKSDialer(dialer) {
// Return an error if we're not using a dial
// proxy that can do DNS lookups for us.
return nil, err
}
}
c.client = derpClient
c.netConn = tcpConn
return c.client, nil
tcpConn, err := dialer.DialContext(ctx, "tcp", net.JoinHostPort(hostOrIP, urlPort(c.url)))
if err != nil {
return nil, fmt.Errorf("dial of %v: %v", host, err)
}
return tcpConn, nil
}
// dialRegion returns a TCP connection to the provided region, trying
// each node in order (with dialNode) until one connects or ctx is
// done.
func (c *Client) dialRegion(ctx context.Context, reg *tailcfg.DERPRegion) (net.Conn, *tailcfg.DERPNode, error) {
if len(reg.Nodes) == 0 {
return nil, nil, fmt.Errorf("no nodes for %s", c.targetString(reg))
}
var firstErr error
for _, n := range reg.Nodes {
if n.STUNOnly {
if firstErr == nil {
firstErr = fmt.Errorf("no non-STUNOnly nodes for %s", c.targetString(reg))
}
continue
}
c, err := c.dialNode(ctx, n)
if err == nil {
return c, n, nil
}
if firstErr == nil {
firstErr = err
}
}
return nil, nil, firstErr
}
func (c *Client) tlsClient(nc net.Conn, node *tailcfg.DERPNode) *tls.Conn {
tlsConf := tlsdial.Config(c.tlsServerName(node), c.TLSConfig)
if node != nil {
if node.DERPTestPort != 0 {
tlsConf.InsecureSkipVerify = true
}
if node.CertName != "" {
tlsdial.SetConfigExpectedCert(tlsConf, node.CertName)
}
}
return tls.Client(nc, tlsConf)
}
func (c *Client) DialRegionTLS(ctx context.Context, reg *tailcfg.DERPRegion) (tlsConn *tls.Conn, connClose io.Closer, err error) {
tcpConn, node, err := c.dialRegion(ctx, reg)
if err != nil {
return nil, nil, err
}
done := make(chan bool) // unbufferd
defer close(done)
tlsConn = c.tlsClient(tcpConn, node)
go func() {
select {
case <-done:
case <-ctx.Done():
tcpConn.Close()
}
}()
err = tlsConn.Handshake()
if err != nil {
return nil, nil, err
}
select {
case done <- true:
return tlsConn, tcpConn, nil
case <-ctx.Done():
return nil, nil, ctx.Err()
}
}
func (c *Client) dialContext(ctx context.Context, proto, addr string) (net.Conn, error) {
return netns.NewDialer().DialContext(ctx, proto, addr)
}
// shouldDialProto reports whether an explicitly provided IPv4 or IPv6
// address (given in s) is valid. An empty value means to dial, but to
// use DNS. The predicate function reports whether the non-empty
// string s contained a valid IP address of the right family.
func shouldDialProto(s string, pred func(netaddr.IP) bool) bool {
if s == "" {
return true
}
ip, _ := netaddr.ParseIP(s)
return pred(ip)
}
const dialNodeTimeout = 1500 * time.Millisecond
// dialNode returns a TCP connection to node n, racing IPv4 and IPv6
// (both as applicable) against each other.
// A node is only given dialNodeTimeout to connect.
//
// TODO(bradfitz): longer if no options remain perhaps? ... Or longer
// overall but have dialRegion start overlapping races?
func (c *Client) dialNode(ctx context.Context, n *tailcfg.DERPNode) (net.Conn, error) {
type res struct {
c net.Conn
err error
}
resc := make(chan res) // must be unbuffered
ctx, cancel := context.WithTimeout(ctx, dialNodeTimeout)
defer cancel()
nwait := 0
startDial := func(dstPrimary, proto string) {
nwait++
go func() {
dst := dstPrimary
if dst == "" {
dst = n.HostName
}
port := "443"
if n.DERPTestPort != 0 {
port = fmt.Sprint(n.DERPTestPort)
}
c, err := c.dialContext(ctx, proto, net.JoinHostPort(dst, port))
select {
case resc <- res{c, err}:
case <-ctx.Done():
if c != nil {
c.Close()
}
}
}()
}
if shouldDialProto(n.IPv4, netaddr.IP.Is4) {
startDial(n.IPv4, "tcp4")
}
if shouldDialProto(n.IPv6, netaddr.IP.Is6) {
startDial(n.IPv6, "tcp6")
}
if nwait == 0 {
return nil, errors.New("both IPv4 and IPv6 are explicitly disabled for node")
}
var firstErr error
for {
select {
case res := <-resc:
nwait--
if res.err == nil {
return res.c, nil
}
if firstErr == nil {
firstErr = res.err
}
if nwait == 0 {
return nil, firstErr
}
case <-ctx.Done():
return nil, ctx.Err()
}
}
}
func (c *Client) Send(dstKey key.Public, b []byte) error {
client, err := c.connect(context.TODO(), "derphttp.Client.Send")
client, _, err := c.connect(context.TODO(), "derphttp.Client.Send")
if err != nil {
return err
}
if err := client.Send(dstKey, b); err != nil {
c.closeForReconnect()
c.closeForReconnect(client)
}
return err
}
func (c *Client) ForwardPacket(from, to key.Public, b []byte) error {
client, _, err := c.connect(context.TODO(), "derphttp.Client.ForwardPacket")
if err != nil {
return err
}
if err := client.ForwardPacket(from, to, b); err != nil {
c.closeForReconnect(client)
}
return err
}
@@ -261,23 +516,63 @@ func (c *Client) NotePreferred(v bool) {
if client != nil {
if err := client.NotePreferred(v); err != nil {
c.closeForReconnect()
c.closeForReconnect(client)
}
}
}
func (c *Client) Recv(b []byte) (derp.ReceivedMessage, error) {
client, err := c.connect(context.TODO(), "derphttp.Client.Recv")
// WatchConnectionChanges sends a request to subscribe to
// notifications about clients connecting & disconnecting.
//
// Only trusted connections (using MeshKey) are allowed to use this.
func (c *Client) WatchConnectionChanges() error {
client, _, err := c.connect(context.TODO(), "derphttp.Client.WatchConnectionChanges")
if err != nil {
return nil, err
return err
}
m, err := client.Recv(b)
err = client.WatchConnectionChanges()
if err != nil {
c.closeForReconnect()
c.closeForReconnect(client)
}
return err
}
// ClosePeer asks the server to close target's TCP connection.
//
// Only trusted connections (using MeshKey) are allowed to use this.
func (c *Client) ClosePeer(target key.Public) error {
client, _, err := c.connect(context.TODO(), "derphttp.Client.ClosePeer")
if err != nil {
return err
}
err = client.ClosePeer(target)
if err != nil {
c.closeForReconnect(client)
}
return err
}
// Recv reads a message from c. The returned message may alias memory from Client.
// The message should only be used until the next Client call.
func (c *Client) Recv() (derp.ReceivedMessage, error) {
m, _, err := c.RecvDetail()
return m, err
}
// RecvDetail is like Recv, but additional returns the connection generation on each message.
// The connGen value is incremented every time the derphttp.Client reconnects to the server.
func (c *Client) RecvDetail() (m derp.ReceivedMessage, connGen int, err error) {
client, connGen, err := c.connect(context.TODO(), "derphttp.Client.Recv")
if err != nil {
return nil, 0, err
}
m, err = client.Recv()
if err != nil {
c.closeForReconnect(client)
}
return m, connGen, err
}
// Close closes the client. It will not automatically reconnect after
// being closed.
func (c *Client) Close() error {
@@ -298,9 +593,19 @@ func (c *Client) Close() error {
// closeForReconnect closes the underlying network connection and
// zeros out the client field so future calls to Connect will
// reconnect.
func (c *Client) closeForReconnect() {
//
// The provided brokenClient is the client to forget. If current
// client is not brokenClient, closeForReconnect does nothing. (This
// prevents a send and receive goroutine from failing at the ~same
// time and both calling closeForReconnect and the caller goroutines
// forever calling closeForReconnect in lockstep endlessly;
// https://github.com/tailscale/tailscale/pull/264)
func (c *Client) closeForReconnect(brokenClient *derp.Client) {
c.mu.Lock()
defer c.mu.Unlock()
if c.client != brokenClient {
return
}
if c.netConn != nil {
c.netConn.Close()
c.netConn = nil

View File

@@ -32,6 +32,6 @@ func Handler(s *derp.Server) http.Handler {
http.Error(w, "HTTP does not support general TCP support", 500)
return
}
s.Accept(netConn, conn)
s.Accept(netConn, conn, netConn.RemoteAddr().String())
})
}

View File

@@ -93,8 +93,7 @@ func TestSendRecv(t *testing.T) {
return
default:
}
b := make([]byte, 1<<16)
m, err := c.Recv(b)
m, err := c.Recv()
if err != nil {
t.Logf("client%d: %v", i, err)
break
@@ -103,8 +102,10 @@ func TestSendRecv(t *testing.T) {
default:
t.Errorf("unexpected message type %T", m)
continue
case derp.PeerGoneMessage:
// Ignore.
case derp.ReceivedPacket:
recvChs[i] <- m.Data
recvChs[i] <- append([]byte(nil), m.Data...)
}
}
}(i)

View File

@@ -0,0 +1,122 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package derphttp
import (
"sync"
"time"
"tailscale.com/derp"
"tailscale.com/types/key"
)
// RunWatchConnectionLoop loops forever, sending WatchConnectionChanges and subscribing to
// connection changes.
//
// If the server's public key is ignoreServerKey, RunWatchConnectionLoop returns.
//
// Otherwise, the add and remove funcs are called as clients come & go.
func (c *Client) RunWatchConnectionLoop(ignoreServerKey key.Public, add, remove func(key.Public)) {
logf := c.logf
const retryInterval = 5 * time.Second
const statusInterval = 10 * time.Second
var (
mu sync.Mutex
present = map[key.Public]bool{}
loggedConnected = false
)
clear := func() {
mu.Lock()
defer mu.Unlock()
if len(present) == 0 {
return
}
logf("reconnected; clearing %d forwarding mappings", len(present))
for k := range present {
remove(k)
}
present = map[key.Public]bool{}
}
lastConnGen := 0
lastStatus := time.Now()
logConnectedLocked := func() {
if loggedConnected {
return
}
logf("connected; %d peers", len(present))
loggedConnected = true
}
const logConnectedDelay = 200 * time.Millisecond
timer := time.AfterFunc(2*time.Second, func() {
mu.Lock()
defer mu.Unlock()
logConnectedLocked()
})
defer timer.Stop()
updatePeer := func(k key.Public, isPresent bool) {
if isPresent {
add(k)
} else {
remove(k)
}
mu.Lock()
defer mu.Unlock()
if isPresent {
present[k] = true
if !loggedConnected {
timer.Reset(logConnectedDelay)
}
} else {
// If we got a peerGone message, that means the initial connection's
// flood of peerPresent messages is done, so we can log already:
logConnectedLocked()
delete(present, k)
}
}
for {
err := c.WatchConnectionChanges()
if err != nil {
clear()
logf("WatchConnectionChanges: %v", err)
time.Sleep(retryInterval)
continue
}
if c.ServerPublicKey() == ignoreServerKey {
logf("detected self-connect; ignoring host")
return
}
for {
m, connGen, err := c.RecvDetail()
if err != nil {
clear()
logf("Recv: %v", err)
time.Sleep(retryInterval)
break
}
if connGen != lastConnGen {
lastConnGen = connGen
clear()
}
switch m := m.(type) {
case derp.PeerPresentMessage:
updatePeer(key.Public(m), true)
case derp.PeerGoneMessage:
updatePeer(key.Public(m), false)
default:
continue
}
if now := time.Now(); now.Sub(lastStatus) > statusInterval {
lastStatus = now
logf("%d peers", len(present))
}
}
}
}

65
derp/derpmap/derpmap.go Normal file
View File

@@ -0,0 +1,65 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package derpmap contains information about Tailscale.com's production DERP nodes.
package derpmap
import (
"fmt"
"strings"
"tailscale.com/tailcfg"
)
func derpNode(suffix, v4, v6 string) *tailcfg.DERPNode {
return &tailcfg.DERPNode{
Name: suffix, // updated later
RegionID: 0, // updated later
IPv4: v4,
IPv6: v6,
}
}
func derpRegion(id int, code string, nodes ...*tailcfg.DERPNode) *tailcfg.DERPRegion {
region := &tailcfg.DERPRegion{
RegionID: id,
RegionCode: code,
Nodes: nodes,
}
for _, n := range nodes {
n.Name = fmt.Sprintf("%d%s", id, n.Name)
n.RegionID = id
n.HostName = fmt.Sprintf("derp%s.tailscale.com", strings.TrimSuffix(n.Name, "a"))
}
return region
}
// Prod returns Tailscale's map of relay servers.
//
// This list is only used by cmd/tailscale's netcheck subcommand. In
// normal operation the Tailscale nodes get this sent to them from the
// control server.
//
// This list is subject to change and should not be relied on.
func Prod() *tailcfg.DERPMap {
return &tailcfg.DERPMap{
Regions: map[int]*tailcfg.DERPRegion{
1: derpRegion(1, "nyc",
derpNode("a", "159.89.225.99", "2604:a880:400:d1::828:b001"),
),
2: derpRegion(2, "sfo",
derpNode("a", "167.172.206.31", "2604:a880:2:d1::c5:7001"),
),
3: derpRegion(3, "sin",
derpNode("a", "68.183.179.66", "2400:6180:0:d1::67d:8001"),
),
4: derpRegion(4, "fra",
derpNode("a", "167.172.182.26", "2a03:b0c0:3:e0::36e:9001"),
),
5: derpRegion(5, "syd",
derpNode("a", "103.43.75.49", "2001:19f0:5801:10b7:5400:2ff:feaa:284c"),
),
},
}
}

179
disco/disco.go Normal file
View File

@@ -0,0 +1,179 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package disco contains the discovery message types.
//
// A discovery message is:
//
// Header:
// magic [6]byte // “TS💬” (0x54 53 f0 9f 92 ac)
// senderDiscoPub [32]byte // nacl public key
// nonce [24]byte
//
// The recipient then decrypts the bytes following (the nacl secretbox)
// and then the inner payload structure is:
//
// messageType byte (the MessageType constants below)
// messageVersion byte (0 for now; but always ignore bytes at the end)
// message-paylod [...]byte
package disco
import (
"encoding/binary"
"errors"
"fmt"
"net"
"inet.af/netaddr"
)
// Magic is the 6 byte header of all discovery messages.
const Magic = "TS💬" // 6 bytes: 0x54 53 f0 9f 92 ac
const keyLen = 32
// NonceLen is the length of the nonces used by nacl secretboxes.
const NonceLen = 24
type MessageType byte
const (
TypePing = MessageType(0x01)
TypePong = MessageType(0x02)
TypeCallMeMaybe = MessageType(0x03)
)
const v0 = byte(0)
var errShort = errors.New("short message")
// LooksLikeDiscoWrapper reports whether p looks like it's a packet
// containing an encrypted disco message.
func LooksLikeDiscoWrapper(p []byte) bool {
if len(p) < len(Magic)+keyLen+NonceLen {
return false
}
return string(p[:len(Magic)]) == Magic
}
// Parse parses the encrypted part of the message from inside the
// nacl secretbox.
func Parse(p []byte) (Message, error) {
if len(p) < 2 {
return nil, errShort
}
t, ver, p := MessageType(p[0]), p[1], p[2:]
switch t {
case TypePing:
return parsePing(ver, p)
case TypePong:
return parsePong(ver, p)
case TypeCallMeMaybe:
return CallMeMaybe{}, nil
default:
return nil, fmt.Errorf("unknown message type 0x%02x", byte(t))
}
}
// Message a discovery message.
type Message interface {
// AppendMarshal appends the message's marshaled representation.
AppendMarshal([]byte) []byte
}
// appendMsgHeader appends two bytes (for t and ver) and then also
// dataLen bytes to b, returning the appended slice in all. The
// returned data slice is a subslice of all with just dataLen bytes of
// where the caller will fill in the data.
func appendMsgHeader(b []byte, t MessageType, ver uint8, dataLen int) (all, data []byte) {
// TODO: optimize this?
all = append(b, make([]byte, dataLen+2)...)
all[len(b)] = byte(t)
all[len(b)+1] = ver
data = all[len(b)+2:]
return
}
type Ping struct {
TxID [12]byte
}
func (m *Ping) AppendMarshal(b []byte) []byte {
ret, d := appendMsgHeader(b, TypePing, v0, 12)
copy(d, m.TxID[:])
return ret
}
func parsePing(ver uint8, p []byte) (m *Ping, err error) {
if len(p) < 12 {
return nil, errShort
}
m = new(Ping)
copy(m.TxID[:], p)
return m, nil
}
// CallMeMaybe is a message sent only over DERP to request that the recipient try
// to open up a magicsock path back to the sender.
//
// The sender should've already sent UDP packets to the peer to open
// up the stateful firewall mappings inbound.
//
// The recipient may choose to not open a path back, if it's already
// happy with its path. But usually it will.
type CallMeMaybe struct{}
func (CallMeMaybe) AppendMarshal(b []byte) []byte {
ret, _ := appendMsgHeader(b, TypeCallMeMaybe, v0, 0)
return ret
}
// Pong is a response a Ping.
//
// It includes the sender's source IP + port, so it's effectively a
// STUN response.
type Pong struct {
TxID [12]byte
Src netaddr.IPPort // 18 bytes (16+2) on the wire; v4-mapped ipv6 for IPv4
}
const pongLen = 12 + 16 + 2
func (m *Pong) AppendMarshal(b []byte) []byte {
ret, d := appendMsgHeader(b, TypePong, v0, pongLen)
d = d[copy(d, m.TxID[:]):]
ip16 := m.Src.IP.As16()
d = d[copy(d, ip16[:]):]
binary.BigEndian.PutUint16(d, m.Src.Port)
return ret
}
func parsePong(ver uint8, p []byte) (m *Pong, err error) {
if len(p) < pongLen {
return nil, errShort
}
m = new(Pong)
copy(m.TxID[:], p)
p = p[12:]
m.Src.IP, _ = netaddr.FromStdIP(net.IP(p[:16]))
p = p[16:]
m.Src.Port = binary.BigEndian.Uint16(p)
return m, nil
}
// MessageSummary returns a short summary of m for logging purposes.
func MessageSummary(m Message) string {
switch m := m.(type) {
case *Ping:
return fmt.Sprintf("ping tx=%x", m.TxID[:6])
case *Pong:
return fmt.Sprintf("pong tx=%x", m.TxID[:6])
case CallMeMaybe:
return "call-me-maybe"
default:
return fmt.Sprintf("%#v", m)
}
}

82
disco/disco_test.go Normal file
View File

@@ -0,0 +1,82 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package disco
import (
"fmt"
"reflect"
"strings"
"testing"
"inet.af/netaddr"
)
func TestMarshalAndParse(t *testing.T) {
tests := []struct {
name string
want string
m Message
}{
{
name: "ping",
m: &Ping{
TxID: [12]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
},
want: "01 00 01 02 03 04 05 06 07 08 09 0a 0b 0c",
},
{
name: "pong",
m: &Pong{
TxID: [12]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
Src: mustIPPort("2.3.4.5:1234"),
},
want: "02 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 00 00 00 00 00 00 00 00 00 00 ff ff 02 03 04 05 04 d2",
},
{
name: "pongv6",
m: &Pong{
TxID: [12]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
Src: mustIPPort("[fed0::12]:6666"),
},
want: "02 00 01 02 03 04 05 06 07 08 09 0a 0b 0c fe d0 00 00 00 00 00 00 00 00 00 00 00 00 00 12 1a 0a",
},
{
name: "call_me_maybe",
m: CallMeMaybe{},
want: "03 00",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
foo := []byte("foo")
got := string(tt.m.AppendMarshal(foo))
if !strings.HasPrefix(got, "foo") {
t.Fatalf("didn't start with foo: got %q", got)
}
got = strings.TrimPrefix(got, "foo")
gotHex := fmt.Sprintf("% x", got)
if gotHex != tt.want {
t.Fatalf("wrong marshal\n got: %s\nwant: %s\n", gotHex, tt.want)
}
back, err := Parse([]byte(got))
if err != nil {
t.Fatalf("parse back: %v", err)
}
if !reflect.DeepEqual(back, tt.m) {
t.Errorf("message in %+v doesn't match Parse back result %+v", tt.m, back)
}
})
}
}
func mustIPPort(s string) netaddr.IPPort {
ipp, err := netaddr.ParseIPPort(s)
if err != nil {
panic(err)
}
return ipp
}

28
go.mod
View File

@@ -1,6 +1,6 @@
module tailscale.com
go 1.13
go 1.14
require (
github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239 // indirect
@@ -9,26 +9,30 @@ require (
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 // indirect
github.com/gliderlabs/ssh v0.2.2
github.com/go-ole/go-ole v1.2.4
github.com/godbus/dbus/v5 v5.0.3
github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e
github.com/google/go-cmp v0.4.0
github.com/goreleaser/nfpm v1.1.10
github.com/klauspost/compress v1.9.8
github.com/jsimonetti/rtnetlink v0.0.0-20200117123717-f846d4f6c1f4
github.com/klauspost/compress v1.10.10
github.com/kr/pty v1.1.1
github.com/mdlayher/netlink v1.1.0
github.com/miekg/dns v1.1.30
github.com/pborman/getopt v0.0.0-20190409184431-ee0cd42419d3
github.com/peterbourgon/ff v1.7.0 // indirect
github.com/peterbourgon/ff/v2 v2.0.0
github.com/tailscale/hujson v0.0.0-20190930033718-5098e564d9b3 // indirect
github.com/tailscale/winipcfg-go v0.0.0-20200213045944-185b07f8233f
github.com/tailscale/wireguard-go v0.0.0-20200307073332-1d43cf6b424f
golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073
golang.org/x/net v0.0.0-20200301022130-244492dfa37a // indirect
github.com/tailscale/winipcfg-go v0.0.0-20200413171540-609dcf2df55f
github.com/tailscale/wireguard-go v0.0.0-20200724155040-d554a2a5e7e1
github.com/tcnksm/go-httpstat v0.2.0
github.com/toqueteos/webbrowser v1.2.0
go4.org/mem v0.0.0-20200706164138-185c595c3ecc
golang.org/x/crypto v0.0.0-20200317142112-1b76d66859c6
golang.org/x/net v0.0.0-20200301022130-244492dfa37a
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e
golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527
golang.org/x/sys v0.0.0-20200501052902-10377860bb8e
golang.org/x/time v0.0.0-20191024005414-555d28b269f0
gortc.io/stun v1.22.1
honnef.co/go/tools v0.0.1-2020.1.3 // indirect
golang.org/x/tools v0.0.0-20191216052735-49a3e744a425
honnef.co/go/tools v0.0.1-2020.1.4
inet.af/netaddr v0.0.0-20200718043157-99321d6ad24c
rsc.io/goversion v1.2.0
)

99
go.sum
View File

@@ -30,6 +30,8 @@ github.com/gliderlabs/ssh v0.2.2 h1:6zsha5zo/TWhRhwqCD3+EarCAgZ2yN28ipRnGPnwkI0=
github.com/gliderlabs/ssh v0.2.2/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0=
github.com/go-ole/go-ole v1.2.4 h1:nNBDSCOigTSiarFpYE9J/KtEA1IOW4CNeqT9TQDqCxI=
github.com/go-ole/go-ole v1.2.4/go.mod h1:XCwSNxSkXRo4vlyPy93sltvi/qJq0jqQhjqQNIwKuxM=
github.com/godbus/dbus/v5 v5.0.3 h1:ZqHaoEF7TBzh4jzPmqVhE/5A1z9of6orkAe5uHoAeME=
github.com/godbus/dbus/v5 v5.0.3/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e h1:1r7pUrabqp18hOBcwBwiTsbnFeTZHV9eER/QT5JVZxY=
github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=
@@ -49,8 +51,8 @@ github.com/jsimonetti/rtnetlink v0.0.0-20190606172950-9527aa82566a/go.mod h1:Oz+
github.com/jsimonetti/rtnetlink v0.0.0-20200117123717-f846d4f6c1f4 h1:nwOc1YaOrYJ37sEBrtWZrdqzK22hiJs3GpDmP3sR2Yw=
github.com/jsimonetti/rtnetlink v0.0.0-20200117123717-f846d4f6c1f4/go.mod h1:WGuG/smIU4J/54PblvSbh+xvCZmpJnFgr3ds6Z55XMQ=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/klauspost/compress v1.9.8 h1:VMAMUUOh+gaxKTMk+zqbjsSjsIcUcL/LF4o63i82QyA=
github.com/klauspost/compress v1.9.8/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A=
github.com/klauspost/compress v1.10.10 h1:a/y8CglcM7gLGYmlbP/stPE5sR3hbhFRUjCBfd/0B3I=
github.com/klauspost/compress v1.10.10/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1 h1:VkoXIwSboBpnk99O/KFauAEILuNHv5DVFKZMBN/gUgw=
@@ -63,14 +65,13 @@ github.com/mdlayher/netlink v0.0.0-20190409211403-11939a169225/go.mod h1:eQB3mZE
github.com/mdlayher/netlink v1.0.0/go.mod h1:KxeJAFOFLG6AjpyDkQ/iIhxygIUKD+vcwqcnu43w/+M=
github.com/mdlayher/netlink v1.1.0 h1:mpdLgm+brq10nI9zM1BpX1kpDbh3NLl3RSnVq6ZSkfg=
github.com/mdlayher/netlink v1.1.0/go.mod h1:H4WCitaheIsdF9yOYu8CFmCgQthAPIWZmcKp9uZHgmY=
github.com/mitchellh/go-wordwrap v1.0.0/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo=
github.com/miekg/dns v1.1.30 h1:Qww6FseFn8PRfw07jueqIXqodm0JKiiKuK0DeXSqfyo=
github.com/miekg/dns v1.1.30/go.mod h1:KNUDUusw/aVsxyTYZM1oqvCicbwhgbNgztCETuNZ7xM=
github.com/op/go-logging v0.0.0-20160315200505-970db520ece7 h1:lDH9UUVJtmYCjyT0CI4q8xvlXPxeZ0gYCVvWbmPlp88=
github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk=
github.com/pborman/getopt v0.0.0-20190409184431-ee0cd42419d3 h1:YtFkrqsMEj7YqpIhRteVxJxCeC3jJBieuLr0d4C4rSA=
github.com/pborman/getopt v0.0.0-20190409184431-ee0cd42419d3/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o=
github.com/pelletier/go-toml v1.6.0/go.mod h1:5N711Q9dKgbdkxHL+MEfF31hpT7l0S0s/t2kKREewys=
github.com/peterbourgon/ff v1.7.0 h1:hknvTgsh90jNBIjPq7xeq32Y9AmSbpXvjrFW4sJwW+A=
github.com/peterbourgon/ff v1.7.0/go.mod h1:/KKxnU5cBj4w21jEMj4Rway/kslRP6XAOHh7CH8AyAM=
github.com/peterbourgon/ff/v2 v2.0.0 h1:lx0oYI5qr/FU1xnpNhQ+EZM04gKgn46jyYvGEEqBBbY=
github.com/peterbourgon/ff/v2 v2.0.0/go.mod h1:xjwr+t+SjWm4L46fcj/D+Ap+6ME7+HqFzaP22pP5Ggk=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
@@ -83,63 +84,33 @@ github.com/sassoftware/go-rpmutils v0.0.0-20190420191620-a8f1baeba37b/go.mod h1:
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/tailscale/hujson v0.0.0-20190930033718-5098e564d9b3 h1:rdtXEo9yffOjh4vZQJw3heaY+ggXKp+zvMX5fihh6lI=
github.com/tailscale/hujson v0.0.0-20190930033718-5098e564d9b3/go.mod h1:STqf+YV0ADdzk4ejtXFsGqDpATP9JoL0OB+hiFQbkdE=
github.com/tailscale/winipcfg-go v0.0.0-20200213045944-185b07f8233f h1:q2ynfOHxHaaMnkZ1YHswWeO6wEk7IyOnkFozytZ1ztc=
github.com/tailscale/winipcfg-go v0.0.0-20200213045944-185b07f8233f/go.mod h1:x880GWw5fvrl2DVTQ04ttXQD4DuppTt1Yz6wLibbjNE=
github.com/tailscale/wireguard-go v0.0.0-20191108062213-b93cdd0582db h1:oP0crfwOb3WZSVrMVm/o51NXN2JirDlcdlNEIPTmgI0=
github.com/tailscale/wireguard-go v0.0.0-20200207221558-a158079b156a h1:5TWA3nl2QUfL9OiE3tlBpqJd4GYd4hbGtDNkWQQ2fyc=
github.com/tailscale/wireguard-go v0.0.0-20200207221558-a158079b156a/go.mod h1:QPS8HjBzzAXoQNndUNx2efJaQbCCz8nI2Cv1ksTUHyY=
github.com/tailscale/wireguard-go v0.0.0-20200208161837-3cd0a483944a h1:vIyObUBvnXB1XTKTBM4AgoUFR9RHiz/kslGHClkXQVg=
github.com/tailscale/wireguard-go v0.0.0-20200208161837-3cd0a483944a/go.mod h1:JPm5cTfu1K+qDFRbiHy0sOlHUylYQbpl356sdYFD8V4=
github.com/tailscale/wireguard-go v0.0.0-20200208214841-2981baf46731 h1:sNmny/5pHqHdm081Fx8rcNFnwt0zTGuee/0+Jz+tXCA=
github.com/tailscale/wireguard-go v0.0.0-20200208214841-2981baf46731/go.mod h1:JPm5cTfu1K+qDFRbiHy0sOlHUylYQbpl356sdYFD8V4=
github.com/tailscale/wireguard-go v0.0.0-20200211020303-f39bc8eeee1b h1:99LOgoPy0PcmT+yg1HiPJXk/aV/KWeGGh4WtSVB7noM=
github.com/tailscale/wireguard-go v0.0.0-20200211020303-f39bc8eeee1b/go.mod h1:JPm5cTfu1K+qDFRbiHy0sOlHUylYQbpl356sdYFD8V4=
github.com/tailscale/wireguard-go v0.0.0-20200213180345-a7c4b7719b1d h1:LVJovgZxbmPxtY6kJm4vwMtk0HpcNeI+vU2jB3T8M40=
github.com/tailscale/wireguard-go v0.0.0-20200213180345-a7c4b7719b1d/go.mod h1:JPm5cTfu1K+qDFRbiHy0sOlHUylYQbpl356sdYFD8V4=
github.com/tailscale/wireguard-go v0.0.0-20200219153015-ff5ce9e55c86 h1:yVWApjTol2CR3dVbiiSOI78KnElu3AlHFvntYM2egBU=
github.com/tailscale/wireguard-go v0.0.0-20200219153015-ff5ce9e55c86/go.mod h1:JPm5cTfu1K+qDFRbiHy0sOlHUylYQbpl356sdYFD8V4=
github.com/tailscale/wireguard-go v0.0.0-20200224122332-ad79bbddc844 h1:CChfZok8JbY2dT+BNLHAcCLcGuCTBEhrkYtUwOk5rVY=
github.com/tailscale/wireguard-go v0.0.0-20200224122332-ad79bbddc844/go.mod h1:JPm5cTfu1K+qDFRbiHy0sOlHUylYQbpl356sdYFD8V4=
github.com/tailscale/wireguard-go v0.0.0-20200225215529-3ec48fad1002 h1:F/IqMilbeud18Ef4kU5oAFDgjD9tgl7pq3OFcqoCEKM=
github.com/tailscale/wireguard-go v0.0.0-20200225215529-3ec48fad1002/go.mod h1:JPm5cTfu1K+qDFRbiHy0sOlHUylYQbpl356sdYFD8V4=
github.com/tailscale/wireguard-go v0.0.0-20200228112021-e513af474d50 h1:A3jG81hD8NVUdzrIus7RfGnZy8i47xHQW4CXjQFnnCY=
github.com/tailscale/wireguard-go v0.0.0-20200228112021-e513af474d50/go.mod h1:JPm5cTfu1K+qDFRbiHy0sOlHUylYQbpl356sdYFD8V4=
github.com/tailscale/wireguard-go v0.0.0-20200228184309-3f8d44fb81cd h1:d+WIJL0sRFBqxOjLlUD3exOV68oEVqndTvAzjAZpGNA=
github.com/tailscale/wireguard-go v0.0.0-20200228184309-3f8d44fb81cd/go.mod h1:JPm5cTfu1K+qDFRbiHy0sOlHUylYQbpl356sdYFD8V4=
github.com/tailscale/wireguard-go v0.0.0-20200301084640-52819259e449 h1:MySSF619UHACu0gIDUq032SlZXGTl3M6S2zSl3A2gt8=
github.com/tailscale/wireguard-go v0.0.0-20200301084640-52819259e449/go.mod h1:JPm5cTfu1K+qDFRbiHy0sOlHUylYQbpl356sdYFD8V4=
github.com/tailscale/wireguard-go v0.0.0-20200301090855-c9a152bc3b51 h1:9U7gdTXXgX7zoPAShuOnh9KTi3nInbkihuTGcNpuCow=
github.com/tailscale/wireguard-go v0.0.0-20200301090855-c9a152bc3b51/go.mod h1:JPm5cTfu1K+qDFRbiHy0sOlHUylYQbpl356sdYFD8V4=
github.com/tailscale/wireguard-go v0.0.0-20200301220325-351e6067e97c h1:Fxmm2RUWZEC6H1a+9CoKm0vjvwr4VUv9H930PBRNh6s=
github.com/tailscale/wireguard-go v0.0.0-20200301220325-351e6067e97c/go.mod h1:JPm5cTfu1K+qDFRbiHy0sOlHUylYQbpl356sdYFD8V4=
github.com/tailscale/wireguard-go v0.0.0-20200305022019-7888c7edfed2 h1:qjA3efFS6+yVTOqZAeXq6lY9A0oUn6zp+zWYb/alfCA=
github.com/tailscale/wireguard-go v0.0.0-20200305022019-7888c7edfed2/go.mod h1:JPm5cTfu1K+qDFRbiHy0sOlHUylYQbpl356sdYFD8V4=
github.com/tailscale/winipcfg-go v0.0.0-20200413171540-609dcf2df55f h1:uFj5bslHsMzxIM8UTjAhq4VXeo6GfNW91rpoh/WMJaY=
github.com/tailscale/winipcfg-go v0.0.0-20200413171540-609dcf2df55f/go.mod h1:x880GWw5fvrl2DVTQ04ttXQD4DuppTt1Yz6wLibbjNE=
github.com/tcnksm/go-httpstat v0.2.0 h1:rP7T5e5U2HfmOBmZzGgGZjBQ5/GluWUylujl0tJ04I0=
github.com/tcnksm/go-httpstat v0.2.0/go.mod h1:s3JVJFtQxtBEBC9dwcdTTXS9xFnM3SXAZwPG41aurT8=
github.com/toqueteos/webbrowser v1.2.0 h1:tVP/gpK69Fx+qMJKsLE7TD8LuGWPnEV71wBN9rrstGQ=
github.com/toqueteos/webbrowser v1.2.0/go.mod h1:XWoZq4cyp9WeUeak7w7LXRUQf1F1ATJMir8RTqb4ayM=
github.com/ulikunitz/xz v0.5.6 h1:jGHAfXawEGZQ3blwU5wnWKQJvAraT7Ftq9EXjnXYgt8=
github.com/ulikunitz/xz v0.5.6/go.mod h1:2bypXElzHzzJZwzH67Y6wb67pO62Rzfn7BSiF4ABRW8=
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 h1:nIPpBwaJSVYIxUFsDv3M8ofmx9yWTog9BfvIu0q41lo=
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8/go.mod h1:HUYIGzjTL3rfEspMxjDjgmT5uz5wzYJKVo23qUhYTos=
go4.org/mem v0.0.0-20200706164138-185c595c3ecc h1:paujszgN6SpsO/UsXC7xax3gQAKz/XQKCYZLQdU34Tw=
go4.org/mem v0.0.0-20200706164138-185c595c3ecc/go.mod h1:NEYvpHWemiG/E5UWfaN5QAIGZeT1sa0Z2UNk6oeMb/k=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191002192127-34f69633bfdc/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200206161412-a0c6ece9d31a h1:aczoJ0HPNE92XKa7DrIzkNN6esOKO2TBwiiYoKcINhA=
golang.org/x/crypto v0.0.0-20200206161412-a0c6ece9d31a/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200208060501-ecb85df21340 h1:KOcEaR10tFr7gdJV2GCKw8Os5yED1u1aOqHjOAb6d2Y=
golang.org/x/crypto v0.0.0-20200208060501-ecb85df21340/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200210222208-86ce3cb69678 h1:wCWoJcFExDgyYx2m2hpHgwz8W3+FPdfldvIgzqDIhyg=
golang.org/x/crypto v0.0.0-20200210222208-86ce3cb69678/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200221231518-2aa609cf4a9d h1:1ZiEyfaQIg3Qh0EoqpwAakHVhecoE5wlSg5GjnafJGw=
golang.org/x/crypto v0.0.0-20200221231518-2aa609cf4a9d/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073 h1:xMPOj6Pz6UipU1wXLkrtqpHbR0AVFnyPEQq/wRWz9lM=
golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200317142112-1b76d66859c6 h1:TjszyFsQsyZNHwdVdZ5m7bjmreu0znc2kRYsEml9/Ww=
golang.org/x/crypto v0.0.0-20200317142112-1b76d66859c6/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20191003171128-d98b1b443823/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20191007182048-72f939374954/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200202094626-16171245cfb2 h1:CCH4IOTTfewWjGOlSp+zGcjutRKlBEZQ6wTn8ozI/nI=
@@ -150,7 +121,6 @@ golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d h1:TzXSXBo42m9gQenoE3b9BG
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4 h1:YUO/7uOKsKeq9UokNS62b8FYywz3ker1l1vDZRCRefw=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e h1:vcxGaoTs7kV8m5Np9uUNQin4BrLOthgV7252N8V+FwY=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -161,34 +131,27 @@ golang.org/x/sys v0.0.0-20190405154228-4b34438f7a67/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20190411185658-b44545bcd369/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190924154521-2837fb4f24fe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191003212358-c178f38b412c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5 h1:LfCXLvNmTYH9kEmVgqbnsWfruoXZIrh4YBgqVHtDvw0=
golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4 h1:sfkvUWPNGwSV+8/fNqctR5lS2AqCSqYwXdrjCxp/dXo=
golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200217220822-9197077df867 h1:JoRuNIf+rpHl+VhScRQQvzbHed86tKkqwPMV34T8myw=
golang.org/x/sys v0.0.0-20200217220822-9197077df867/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200301040627-c5d0d7b4ec88 h1:LNVdAhESTW4gWDhYvciNcGoS9CEcxRiUKE9kSgw+X3s=
golang.org/x/sys v0.0.0-20200301040627-c5d0d7b4ec88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200301204400-5d559ad92b82 h1:lMQVwSjnOFtj3Ssuec21gK8stJac9xnIo2CjVk2cczw=
golang.org/x/sys v0.0.0-20200301204400-5d559ad92b82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527 h1:uYVVQ9WP/Ds2ROhcaGPeIdVq0RIXVLwsHlnvJ+cT1So=
golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200501052902-10377860bb8e h1:hq86ru83GdWTlfQFZGO4nZJTU4Bs2wfHl8oFHRaXsfc=
golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/time v0.0.0-20191024005414-555d28b269f0 h1:/5xXl8Y5W96D+TtHSlonuFqGHIWVuyCkGJLwGh9JJFs=
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac h1:MQEvx39qSf8vyrx3XRaOe+j1UDIzKwkYOVObRgGPVqI=
golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d h1:/iIZNFGxc/a7C3yWjGcnboV+Tkc7mxr+p6fDztwoxuM=
golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191216052735-49a3e744a425 h1:VvQyQJN0tSuecqgcIxMWnnfG5kSmgy9KZR9sW3W5QeA=
golang.org/x/tools v0.0.0-20191216052735-49a3e744a425/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.zx2c4.com/wireguard v0.0.20200121 h1:vcswa5Q6f+sylDfjqyrVNNrjsFUUbPsgAQTBCAg/Qf8=
golang.zx2c4.com/wireguard v0.0.20200121/go.mod h1:P2HsVp8SKwZEufsnezXZA4GRX/T49/HlU7DGuelXsU4=
google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
@@ -200,11 +163,9 @@ gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.7 h1:VUgggvou5XRW9mHwD/yXxIYSMtY0zoKQf/v226p2nyo=
gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gortc.io/stun v1.22.1 h1:96mOdDATYRqhYB+TZdenWBg4CzL2Ye5kPyBXQ8KAB+8=
gortc.io/stun v1.22.1/go.mod h1:XD5lpONVyjvV3BgOyJFNo0iv6R2oZB4L+weMqxts+zg=
honnef.co/go/tools v0.0.1-2019.2.3 h1:3JgtbtFHMiCmsznwGVTUWbgGov+pVqnlf1dEJTNAXeM=
honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=
honnef.co/go/tools v0.0.1-2020.1.3 h1:sXmLre5bzIR6ypkjXCDI3jHPssRhc8KD/Ome589sc3U=
honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=
honnef.co/go/tools v0.0.1-2020.1.4 h1:UoveltGrhghAA7ePc+e+QYDHXrBps2PqFZiHkGR/xK8=
honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=
inet.af/netaddr v0.0.0-20200718043157-99321d6ad24c h1:si3Owrfem175Ry6gKqnh59eOXxDojyBTIHxUKuvK/Eo=
inet.af/netaddr v0.0.0-20200718043157-99321d6ad24c/go.mod h1:qqYzz/2whtrbWJvt+DNWQyvekNN4ePQZcg2xc2/Yjww=
rsc.io/goversion v1.2.0 h1:SPn+NLTiAG7w30IRK/DKp1BjvpWabYgxlLp/+kx5J8w=
rsc.io/goversion v1.2.0/go.mod h1:Eih9y/uIBS3ulggl7KNJ09xGSLcuNaLgmvvqa07sgfo=

View File

@@ -1,154 +0,0 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package interfaces contains helpers for looking up system network interfaces.
package interfaces
import (
"net"
"strings"
)
// Tailscale returns the current machine's Tailscale interface, if any.
// If none is found, all zero values are returned.
// A non-nil error is only returned on a problem listing the system interfaces.
func Tailscale() (net.IP, *net.Interface, error) {
ifs, err := net.Interfaces()
if err != nil {
return nil, nil, err
}
for _, iface := range ifs {
if !maybeTailscaleInterfaceName(iface.Name) {
continue
}
addrs, err := iface.Addrs()
if err != nil {
continue
}
for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok && IsTailscaleIP(ipnet.IP) {
return ipnet.IP, &iface, nil
}
}
}
return nil, nil, nil
}
// HaveIPv6GlobalAddress reports whether the machine appears to have a
// global scope unicast IPv6 address.
//
// It only returns an error if there's a problem querying the system
// interfaces.
func HaveIPv6GlobalAddress() (bool, error) {
ifs, err := net.Interfaces()
if err != nil {
return false, err
}
for i := range ifs {
iface := &ifs[i]
if !isUp(iface) || isLoopback(iface) {
continue
}
addrs, err := iface.Addrs()
if err != nil {
continue
}
for _, a := range addrs {
ipnet, ok := a.(*net.IPNet)
if !ok {
continue
}
if ipnet.IP.To4() != nil || !ipnet.IP.IsGlobalUnicast() {
continue
}
return true, nil
}
}
return false, nil
}
// maybeTailscaleInterfaceName reports whether s is an interface
// name that might be used by Tailscale.
func maybeTailscaleInterfaceName(s string) bool {
return strings.HasPrefix(s, "wg") ||
strings.HasPrefix(s, "ts") ||
strings.HasPrefix(s, "tailscale") ||
strings.HasPrefix(s, "utun")
}
// IsTailscaleIP reports whether ip is an IP in a range used by
// Tailscale virtual network interfaces.
func IsTailscaleIP(ip net.IP) bool {
return cgNAT.Contains(ip)
}
func isUp(nif *net.Interface) bool { return nif.Flags&net.FlagUp != 0 }
func isLoopback(nif *net.Interface) bool { return nif.Flags&net.FlagLoopback != 0 }
// LocalAddresses returns the machine's IP addresses, separated by
// whether they're loopback addresses.
func LocalAddresses() (regular, loopback []string, err error) {
// TODO(crawshaw): don't serve interface addresses that we are routing
ifaces, err := net.Interfaces()
if err != nil {
return nil, nil, err
}
for i := range ifaces {
iface := &ifaces[i]
if !isUp(iface) {
// Down interfaces don't count
continue
}
ifcIsLoopback := isLoopback(iface)
addrs, err := iface.Addrs()
if err != nil {
return nil, nil, err
}
for _, a := range addrs {
switch v := a.(type) {
case *net.IPNet:
// TODO(crawshaw): IPv6 support.
// Easy to do here, but we need good endpoint ordering logic.
ip := v.IP.To4()
if ip == nil {
continue
}
// TODO(apenwarr): don't special case cgNAT.
// In the general wireguard case, it might
// very well be something we can route to
// directly, because both nodes are
// behind the same CGNAT router.
if cgNAT.Contains(ip) {
continue
}
if linkLocalIPv4.Contains(ip) {
continue
}
if ip.IsLoopback() || ifcIsLoopback {
loopback = append(loopback, ip.String())
} else {
regular = append(regular, ip.String())
}
}
}
}
return regular, loopback, nil
}
var cgNAT = func() *net.IPNet {
_, ipNet, err := net.ParseCIDR("100.64.0.0/10")
if err != nil {
panic(err)
}
return ipNet
}()
var linkLocalIPv4 = func() *net.IPNet {
_, ipNet, err := net.ParseCIDR("169.254.0.0/16")
if err != nil {
panic(err)
}
return ipNet
}()

View File

@@ -0,0 +1,93 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package deepprint walks a Go value recursively, in a predictable
// order, without looping, and prints each value out to a given
// Writer, which is assumed to be a hash.Hash, as this package doesn't
// format things nicely.
//
// This is intended as a lighter version of go-spew, etc. We don't need its
// features when our writer is just a hash.
package deepprint
import (
"crypto/sha256"
"fmt"
"io"
"reflect"
)
func Hash(v interface{}) string {
h := sha256.New()
Print(h, v)
return fmt.Sprintf("%x", h.Sum(nil))
}
func Print(w io.Writer, v interface{}) {
print(w, reflect.ValueOf(v), make(map[uintptr]bool))
}
func print(w io.Writer, v reflect.Value, visited map[uintptr]bool) {
if !v.IsValid() {
return
}
switch v.Kind() {
default:
panic(fmt.Sprintf("unhandled kind %v for type %v", v.Kind(), v.Type()))
case reflect.Ptr:
ptr := v.Pointer()
if visited[ptr] {
return
}
visited[ptr] = true
print(w, v.Elem(), visited)
return
case reflect.Struct:
fmt.Fprintf(w, "struct{\n")
t := v.Type()
for i, n := 0, v.NumField(); i < n; i++ {
sf := t.Field(i)
fmt.Fprintf(w, "%s: ", sf.Name)
print(w, v.Field(i), visited)
fmt.Fprintf(w, "\n")
}
case reflect.Slice, reflect.Array:
if v.Type().Elem().Kind() == reflect.Uint8 && v.CanInterface() {
fmt.Fprintf(w, "%q", v.Interface())
return
}
fmt.Fprintf(w, "[%d]{\n", v.Len())
for i, ln := 0, v.Len(); i < ln; i++ {
fmt.Fprintf(w, " [%d]: ", i)
print(w, v.Index(i), visited)
fmt.Fprintf(w, "\n")
}
fmt.Fprintf(w, "}\n")
case reflect.Interface:
print(w, v.Elem(), visited)
case reflect.Map:
sm := newSortedMap(v)
fmt.Fprintf(w, "map[%d]{\n", len(sm.Key))
for i, k := range sm.Key {
print(w, k, visited)
fmt.Fprintf(w, ": ")
print(w, sm.Value[i], visited)
fmt.Fprintf(w, "\n")
}
fmt.Fprintf(w, "}\n")
case reflect.String:
fmt.Fprintf(w, "%s", v.String())
case reflect.Bool:
fmt.Fprintf(w, "%v", v.Bool())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
fmt.Fprintf(w, "%v", v.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
fmt.Fprintf(w, "%v", v.Uint())
case reflect.Float32, reflect.Float64:
fmt.Fprintf(w, "%v", v.Float())
case reflect.Complex64, reflect.Complex128:
fmt.Fprintf(w, "%v", v.Complex())
}
}

View File

@@ -0,0 +1,70 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package deepprint
import (
"bytes"
"testing"
"github.com/tailscale/wireguard-go/wgcfg"
"inet.af/netaddr"
"tailscale.com/wgengine/router"
)
func TestDeepPrint(t *testing.T) {
// v contains the types of values we care about for our current callers.
// Mostly we're just testing that we don't panic on handled types.
v := getVal()
var buf bytes.Buffer
Print(&buf, v)
t.Logf("Got: %s", buf.Bytes())
hash1 := Hash(v)
t.Logf("hash: %v", hash1)
for i := 0; i < 20; i++ {
hash2 := Hash(getVal())
if hash1 != hash2 {
t.Error("second hash didn't match")
}
}
}
func getVal() []interface{} {
return []interface{}{
&wgcfg.Config{
Name: "foo",
Addresses: []wgcfg.CIDR{{Mask: 5, IP: wgcfg.IP{Addr: [16]byte{3: 3}}}},
ListenPort: 5,
Peers: []wgcfg.Peer{
{
Endpoints: []wgcfg.Endpoint{
{
Host: "foo",
Port: 5,
},
},
},
},
},
&router.Config{
DNSConfig: router.DNSConfig{
Nameservers: []netaddr.IP{netaddr.IPv4(8, 8, 8, 8)},
Domains: []string{"tailscale.net"},
},
},
map[string]string{
"key1": "val1",
"key2": "val2",
"key3": "val3",
"key4": "val4",
"key5": "val5",
"key6": "val6",
"key7": "val7",
"key8": "val8",
"key9": "val9",
},
}
}

View File

@@ -0,0 +1,224 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// and
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is a slightly modified fork of Go's src/internal/fmtsort/sort.go
package deepprint
import (
"reflect"
"sort"
)
// Note: Throughout this package we avoid calling reflect.Value.Interface as
// it is not always legal to do so and it's easier to avoid the issue than to face it.
// sortedMap represents a map's keys and values. The keys and values are
// aligned in index order: Value[i] is the value in the map corresponding to Key[i].
type sortedMap struct {
Key []reflect.Value
Value []reflect.Value
}
func (o *sortedMap) Len() int { return len(o.Key) }
func (o *sortedMap) Less(i, j int) bool { return compare(o.Key[i], o.Key[j]) < 0 }
func (o *sortedMap) Swap(i, j int) {
o.Key[i], o.Key[j] = o.Key[j], o.Key[i]
o.Value[i], o.Value[j] = o.Value[j], o.Value[i]
}
// Sort accepts a map and returns a sortedMap that has the same keys and
// values but in a stable sorted order according to the keys, modulo issues
// raised by unorderable key values such as NaNs.
//
// The ordering rules are more general than with Go's < operator:
//
// - when applicable, nil compares low
// - ints, floats, and strings order by <
// - NaN compares less than non-NaN floats
// - bool compares false before true
// - complex compares real, then imag
// - pointers compare by machine address
// - channel values compare by machine address
// - structs compare each field in turn
// - arrays compare each element in turn.
// Otherwise identical arrays compare by length.
// - interface values compare first by reflect.Type describing the concrete type
// and then by concrete value as described in the previous rules.
//
func newSortedMap(mapValue reflect.Value) *sortedMap {
if mapValue.Type().Kind() != reflect.Map {
return nil
}
// Note: this code is arranged to not panic even in the presence
// of a concurrent map update. The runtime is responsible for
// yelling loudly if that happens. See issue 33275.
n := mapValue.Len()
key := make([]reflect.Value, 0, n)
value := make([]reflect.Value, 0, n)
iter := mapValue.MapRange()
for iter.Next() {
key = append(key, iter.Key())
value = append(value, iter.Value())
}
sorted := &sortedMap{
Key: key,
Value: value,
}
sort.Stable(sorted)
return sorted
}
// compare compares two values of the same type. It returns -1, 0, 1
// according to whether a > b (1), a == b (0), or a < b (-1).
// If the types differ, it returns -1.
// See the comment on Sort for the comparison rules.
func compare(aVal, bVal reflect.Value) int {
aType, bType := aVal.Type(), bVal.Type()
if aType != bType {
return -1 // No good answer possible, but don't return 0: they're not equal.
}
switch aVal.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
a, b := aVal.Int(), bVal.Int()
switch {
case a < b:
return -1
case a > b:
return 1
default:
return 0
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
a, b := aVal.Uint(), bVal.Uint()
switch {
case a < b:
return -1
case a > b:
return 1
default:
return 0
}
case reflect.String:
a, b := aVal.String(), bVal.String()
switch {
case a < b:
return -1
case a > b:
return 1
default:
return 0
}
case reflect.Float32, reflect.Float64:
return floatCompare(aVal.Float(), bVal.Float())
case reflect.Complex64, reflect.Complex128:
a, b := aVal.Complex(), bVal.Complex()
if c := floatCompare(real(a), real(b)); c != 0 {
return c
}
return floatCompare(imag(a), imag(b))
case reflect.Bool:
a, b := aVal.Bool(), bVal.Bool()
switch {
case a == b:
return 0
case a:
return 1
default:
return -1
}
case reflect.Ptr:
a, b := aVal.Pointer(), bVal.Pointer()
switch {
case a < b:
return -1
case a > b:
return 1
default:
return 0
}
case reflect.Chan:
if c, ok := nilCompare(aVal, bVal); ok {
return c
}
ap, bp := aVal.Pointer(), bVal.Pointer()
switch {
case ap < bp:
return -1
case ap > bp:
return 1
default:
return 0
}
case reflect.Struct:
for i := 0; i < aVal.NumField(); i++ {
if c := compare(aVal.Field(i), bVal.Field(i)); c != 0 {
return c
}
}
return 0
case reflect.Array:
for i := 0; i < aVal.Len(); i++ {
if c := compare(aVal.Index(i), bVal.Index(i)); c != 0 {
return c
}
}
return 0
case reflect.Interface:
if c, ok := nilCompare(aVal, bVal); ok {
return c
}
c := compare(reflect.ValueOf(aVal.Elem().Type()), reflect.ValueOf(bVal.Elem().Type()))
if c != 0 {
return c
}
return compare(aVal.Elem(), bVal.Elem())
default:
// Certain types cannot appear as keys (maps, funcs, slices), but be explicit.
panic("bad type in compare: " + aType.String())
}
}
// nilCompare checks whether either value is nil. If not, the boolean is false.
// If either value is nil, the boolean is true and the integer is the comparison
// value. The comparison is defined to be 0 if both are nil, otherwise the one
// nil value compares low. Both arguments must represent a chan, func,
// interface, map, pointer, or slice.
func nilCompare(aVal, bVal reflect.Value) (int, bool) {
if aVal.IsNil() {
if bVal.IsNil() {
return 0, true
}
return -1, true
}
if bVal.IsNil() {
return 1, true
}
return 0, false
}
// floatCompare compares two floating-point values. NaNs compare low.
func floatCompare(a, b float64) int {
switch {
case isNaN(a):
return -1 // No good answer if b is a NaN so don't bother checking.
case isNaN(b):
return 1
case a < b:
return -1
case a > b:
return 1
}
return 0
}
func isNaN(a float64) bool {
return a != a
}

View File

@@ -5,11 +5,15 @@
package ipn
import (
"net/http"
"time"
"golang.org/x/oauth2"
"tailscale.com/control/controlclient"
"tailscale.com/ipn/ipnstate"
"tailscale.com/tailcfg"
"tailscale.com/types/empty"
"tailscale.com/types/structs"
"tailscale.com/wgengine"
)
@@ -24,6 +28,10 @@ const (
Running
)
// GoogleIDToken Type is the oauth2.Token.TokenType for the Google
// ID tokens used by the Android client.
const GoogleIDTokenType = "ts_android_google_login"
func (s State) String() string {
return [...]string{"NoState", "NeedsLogin", "NeedsMachineAuth",
"Stopped", "Starting", "Running"}[s]
@@ -33,26 +41,33 @@ func (s State) String() string {
type EngineStatus struct {
RBytes, WBytes wgengine.ByteCount
NumLive int
LiveDERPs int // number of active DERP connections
LivePeers map[tailcfg.NodeKey]wgengine.PeerStatus
}
type NetworkMap = controlclient.NetworkMap
// Notify is a communication from a backend (e.g. tailscaled) to a frontend
// (cmd/tailscale, iOS, macOS, Win Tasktray).
// In any given notification, any or all of these may be nil, meaning
// that they have not changed.
// They are JSON-encoded on the wire, despite the lack of struct tags.
type Notify struct {
Version string // version number of IPN backend
ErrMessage *string // critical error message, if any
LoginFinished *empty.Message // event: non-nil when login process succeeded
State *State // current IPN state has changed
Prefs *Prefs // preferences were changed
NetMap *NetworkMap // new netmap received
Engine *EngineStatus // wireguard engine stats
BrowseToURL *string // UI should open a browser right now
BackendLogID *string // public logtail id used by backend
_ structs.Incomparable
Version string // version number of IPN backend
ErrMessage *string // critical error message, if any
LoginFinished *empty.Message // event: non-nil when login process succeeded
State *State // current IPN state has changed
Prefs *Prefs // preferences were changed
NetMap *controlclient.NetworkMap // new netmap received
Engine *EngineStatus // wireguard engine stats
Status *ipnstate.Status // full status
BrowseToURL *string // UI should open a browser right now
BackendLogID *string // public logtail id used by backend
// LocalTCPPort, if non-nil, informs the UI frontend which
// (non-zero) localhost TCP port it's listening on.
// This is currently only used by Tailscale when run in the
// macOS Network Extension.
LocalTCPPort *uint16 `json:",omitempty"`
// type is mirrored in xcode/Shared/IPN.swift
}
@@ -88,6 +103,9 @@ type Options struct {
// an initial overwrite of backend state with Prefs.
StateKey StateKey
Prefs *Prefs
// AuthKey is an optional node auth key used to authorize a
// new node key without user interaction.
AuthKey string
// LegacyConfigPath optionally specifies the old-style relaynode
// relay.conf location. If both LegacyConfigPath and StateKey are
// specified and the requested state doesn't exist in the backend
@@ -98,6 +116,9 @@ type Options struct {
LegacyConfigPath string
// Notify is called when backend events happen.
Notify func(Notify) `json:"-"`
// HTTPTestClient is an optional HTTP client to pass to controlclient
// (for tests only).
HTTPTestClient *http.Client
}
// Backend is the interface between Tailscale frontends
@@ -113,6 +134,8 @@ type Backend interface {
// flow. This should trigger a new BrowseToURL notification
// eventually.
StartLoginInteractive()
// Login logs in with an OAuth2 token.
Login(token *oauth2.Token)
// Logout terminates the current login session and stops the
// wireguard engine.
Logout()
@@ -125,6 +148,9 @@ type Backend interface {
// counts. Connection events are emitted automatically without
// polling.
RequestEngineStatus()
// RequestStatus requests that a full Status update
// notification is sent.
RequestStatus()
// FakeExpireAfter pretends that the current key is going to
// expire after duration x. This is useful for testing GUIs to
// make sure they react properly with keys that are going to

View File

@@ -1,229 +0,0 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build depends_on_currently_unreleased
package ipn
import (
"bytes"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/tailscale/wireguard-go/tun/tuntest"
"tailscale.com/control/controlclient"
"tailscale.com/tailcfg"
"tailscale.com/testy"
"tailscale.com/wgengine"
"tailscale.com/wgengine/magicsock"
"tailscale.io/control" // not yet released
)
func TestIPN(t *testing.T) {
testy.FixLogs(t)
defer testy.UnfixLogs(t)
// Turn off STUN for the test to make it hermitic.
// TODO(crawshaw): add a test that runs against a local STUN server.
origDefaultSTUN := magicsock.DefaultSTUN
magicsock.DefaultSTUN = nil
defer func() {
magicsock.DefaultSTUN = origDefaultSTUN
}()
// TODO(apenwarr): Make resource checks actually pass.
// They don't right now, because (at least) wgengine doesn't fully
// shut down.
// rc := testy.NewResourceCheck()
// defer rc.Assert(t)
var ctl *control.Server
ctlHandler := func(w http.ResponseWriter, r *http.Request) {
ctl.ServeHTTP(w, r)
}
https := httptest.NewServer(http.HandlerFunc(ctlHandler))
serverURL := https.URL
defer https.Close()
defer https.CloseClientConnections()
tmpdir, err := ioutil.TempDir("", "ipntest")
if err != nil {
t.Fatalf("create tempdir: %v\n", err)
}
ctl, err = control.New(tmpdir, serverURL, true)
if err != nil {
t.Fatalf("create control server: %v\n", ctl)
}
n1 := newNode(t, "n1", https)
defer n1.Backend.Shutdown()
n1.Backend.StartLoginInteractive()
n2 := newNode(t, "n2", https)
defer n2.Backend.Shutdown()
n2.Backend.StartLoginInteractive()
t.Run("login", func(t *testing.T) {
var s1, s2 State
for {
t.Logf("\n\nn1.state=%v n2.state=%v\n\n", s1, s2)
// TODO(crawshaw): switch from || to &&. To do this we need to
// transmit some data so that the handshake completes on both
// sides. (Because handshakes are 1RTT, it is the data
// transmission that completes the handshake.)
if s1 == Running || s2 == Running {
// TODO(apenwarr): ensure state sequence.
// Right now we'll just exit as soon as
// state==Running, even if the backend is lying or
// something. Not a great test.
break
}
select {
case n := <-n1.NotifyCh:
t.Logf("n1n: %v\n", n)
if n.State != nil {
s1 = *n.State
if s1 == NeedsMachineAuth {
authNode(t, ctl, n1.Backend)
}
}
case n := <-n2.NotifyCh:
t.Logf("n2n: %v\n", n)
if n.State != nil {
s2 = *n.State
if s2 == NeedsMachineAuth {
authNode(t, ctl, n2.Backend)
}
}
case <-time.After(3 * time.Second):
t.Fatalf("\n\n\nFATAL: timed out waiting for notifications.\n\n\n")
}
}
})
n1addr := n1.Backend.NetMap().Addresses[0].IP
n2addr := n2.Backend.NetMap().Addresses[0].IP
t.Run("ping n2", func(t *testing.T) {
t.Skip("TODO(crawshaw): skipping ping test, it is flaky")
msg := tuntest.Ping(n2addr.IP(), n1addr.IP())
n1.ChannelTUN.Outbound <- msg
select {
case msgRecv := <-n2.ChannelTUN.Inbound:
if !bytes.Equal(msg, msgRecv) {
t.Error("bad ping")
}
case <-time.After(1 * time.Second):
t.Error("no ping seen")
}
})
t.Run("ping n1", func(t *testing.T) {
t.Skip("TODO(crawshaw): skipping ping test, it is flaky")
msg := tuntest.Ping(n1addr.IP(), n2addr.IP())
n2.ChannelTUN.Outbound <- msg
select {
case msgRecv := <-n1.ChannelTUN.Inbound:
if !bytes.Equal(msg, msgRecv) {
t.Error("bad ping")
}
case <-time.After(1 * time.Second):
t.Error("no ping seen")
}
})
drain:
for {
select {
case <-n1.NotifyCh:
case <-n2.NotifyCh:
default:
break drain
}
}
n1.Backend.Logout()
t.Run("logout", func(t *testing.T) {
select {
case n := <-n1.NotifyCh:
if n.State != nil {
if *n.State != NeedsLogin {
t.Errorf("n.State=%v, want %v", n.State, NeedsLogin)
return
}
}
case <-time.After(3 * time.Second):
t.Fatalf("timeout waiting for logout notification")
}
})
}
type testNode struct {
Backend *LocalBackend
ChannelTUN *tuntest.ChannelTUN
NotifyCh <-chan Notify
}
// Create a new IPN node.
func newNode(t *testing.T, prefix string, https *httptest.Server) testNode {
t.Helper()
logfe := func(fmt string, args ...interface{}) {
t.Logf(prefix+".e: "+fmt, args...)
}
logf := func(fmt string, args ...interface{}) {
t.Logf(prefix+": "+fmt, args...)
}
tun := tuntest.NewChannelTUN()
e1, err := wgengine.NewUserspaceEngineAdvanced(logfe, tun.TUN(), wgengine.NewFakeRouter, 0)
if err != nil {
t.Fatalf("NewFakeEngine: %v\n", err)
}
n, err := NewLocalBackend(logf, prefix, &MemoryStore{}, e1)
if err != nil {
t.Fatalf("NewLocalBackend: %v\n", err)
}
nch := make(chan Notify, 1000)
c := controlclient.Persist{
Provider: "google",
LoginName: "test1@tailscale.com",
}
prefs := NewPrefs()
prefs.ControlURL = https.URL
prefs.Persist = &c
n.Start(Options{
FrontendLogID: prefix + "-f",
Prefs: prefs,
Notify: func(n Notify) {
// Automatically visit auth URLs
if n.BrowseToURL != nil {
t.Logf("\n\n\nURL! %vv\n", *n.BrowseToURL)
hc := https.Client()
_, err := hc.Get(*n.BrowseToURL)
if err != nil {
t.Logf("BrowseToURL: %v\n", err)
}
}
nch <- n
},
})
return testNode{
Backend: n,
ChannelTUN: tun,
NotifyCh: nch,
}
}
// Tell the control server to authorize the given node.
func authNode(t *testing.T, ctl *control.Server, n *LocalBackend) {
mk := n.prefs.Persist.PrivateMachineKey.Public()
nk := n.prefs.Persist.PrivateNodeKey.Public()
ctl.AuthorizeMachine(tailcfg.MachineKey(mk), tailcfg.NodeKey(nk))
}

View File

@@ -7,6 +7,10 @@ package ipn
import (
"log"
"time"
"golang.org/x/oauth2"
"tailscale.com/control/controlclient"
"tailscale.com/ipn/ipnstate"
)
type FakeBackend struct {
@@ -39,10 +43,18 @@ func (b *FakeBackend) newState(s State) {
func (b *FakeBackend) StartLoginInteractive() {
u := b.serverURL + "/this/is/fake"
b.notify(Notify{BrowseToURL: &u})
b.login()
}
func (b *FakeBackend) Login(token *oauth2.Token) {
b.login()
}
func (b *FakeBackend) login() {
b.newState(NeedsMachineAuth)
b.newState(Stopped)
// TODO(apenwarr): Fill in a more interesting netmap here.
b.notify(Notify{NetMap: &NetworkMap{}})
b.notify(Notify{NetMap: &controlclient.NetworkMap{}})
b.newState(Starting)
// TODO(apenwarr): Fill in a more interesting status.
b.notify(Notify{Engine: &EngineStatus{}})
@@ -71,6 +83,10 @@ func (b *FakeBackend) RequestEngineStatus() {
b.notify(Notify{Engine: &EngineStatus{}})
}
func (b *FakeBackend) FakeExpireAfter(x time.Duration) {
b.notify(Notify{NetMap: &NetworkMap{}})
func (b *FakeBackend) RequestStatus() {
b.notify(Notify{Status: &ipnstate.Status{}})
}
func (b *FakeBackend) FakeExpireAfter(x time.Duration) {
b.notify(Notify{NetMap: &controlclient.NetworkMap{}})
}

View File

@@ -9,6 +9,8 @@ import (
"time"
"github.com/tailscale/wireguard-go/wgcfg"
"golang.org/x/oauth2"
"tailscale.com/control/controlclient"
"tailscale.com/types/logger"
)
@@ -20,7 +22,7 @@ type Handle struct {
// Mutex protects everything below
mu sync.Mutex
netmapCache *NetworkMap
netmapCache *controlclient.NetworkMap
engineStatusCache EngineStatus
stateCache State
prefsCache *Prefs
@@ -62,7 +64,7 @@ func (h *Handle) Reset() {
func (h *Handle) notify(n Notify) {
h.mu.Lock()
if n.BackendLogID != nil {
h.logf("Handle: logs: be:%v fe:%v\n",
h.logf("Handle: logs: be:%v fe:%v",
*n.BackendLogID, h.frontendLogID)
}
if n.State != nil {
@@ -127,7 +129,7 @@ func (h *Handle) LocalAddrs() []wgcfg.CIDR {
return []wgcfg.CIDR{}
}
func (h *Handle) NetMap() *NetworkMap {
func (h *Handle) NetMap() *controlclient.NetworkMap {
h.mu.Lock()
defer h.mu.Unlock()
@@ -153,6 +155,10 @@ func (h *Handle) StartLoginInteractive() {
h.b.StartLoginInteractive()
}
func (h *Handle) Login(token *oauth2.Token) {
h.b.Login(token)
}
func (h *Handle) Logout() {
h.b.Logout()
}
@@ -161,6 +167,10 @@ func (h *Handle) RequestEngineStatus() {
h.b.RequestEngineStatus()
}
func (h *Handle) RequestStatus() {
h.b.RequestStatus()
}
func (h *Handle) FakeExpireAfter(x time.Duration) {
h.b.FakeExpireAfter(x)
}

View File

@@ -10,20 +10,19 @@ import (
"fmt"
"log"
"net"
"net/http"
"os"
"os/exec"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"github.com/google/go-cmp/cmp"
"github.com/klauspost/compress/zstd"
"tailscale.com/control/controlclient"
"tailscale.com/ipn"
"tailscale.com/logtail/backoff"
"tailscale.com/safesocket"
"tailscale.com/smallzstd"
"tailscale.com/types/logger"
"tailscale.com/version"
"tailscale.com/wgengine"
@@ -34,15 +33,19 @@ type Options struct {
// SocketPath, on unix systems, is the unix socket path to listen
// on for frontend connections.
SocketPath string
// Port, on windows, is the localhost TCP port to listen on for
// frontend connections.
Port int
// StatePath is the path to the stored agent state.
StatePath string
// AutostartStateKey, if non-empty, immediately starts the agent
// using the given StateKey. If empty, the agent stays idle and
// waits for a frontend to start it.
AutostartStateKey ipn.StateKey
// LegacyConfigPath optionally specifies the old-style relaynode
// relay.conf location. If both LegacyConfigPath and
// AutostartStateKey are specified and the requested state doesn't
@@ -52,48 +55,150 @@ type Options struct {
// TODO(danderson): remove some time after the transition to
// tailscaled is done.
LegacyConfigPath string
// SurviveDisconnects specifies how the server reacts to its
// frontend disconnecting. If true, the server keeps running on
// its existing state, and accepts new frontend connections. If
// false, the server dumps its state and becomes idle.
//
// To support CLI connections (notably, "tailscale status"),
// the actual definition of "disconnect" is when the
// connection count transitions from 1 to 0.
SurviveDisconnects bool
// DebugMux, if non-nil, specifies an HTTP ServeMux in which
// to register a debug handler.
DebugMux *http.ServeMux
// ErrorMessage, if not empty, signals that the server will exist
// only to relay the provided critical error message to the user.
ErrorMessage string
}
func pump(logf logger.Logf, ctx context.Context, bs *ipn.BackendServer, s net.Conn) {
defer logf("Control connection done.\n")
// server is an IPN backend and its set of 0 or more active connections
// talking to an IPN backend.
type server struct {
resetOnZero bool // call bs.Reset on transition from 1->0 connections
for ctx.Err() == nil && !bs.GotQuit {
msg, err := ipn.ReadMsg(s)
bsMu sync.Mutex // lock order: bsMu, then mu
bs *ipn.BackendServer
mu sync.Mutex
clients map[net.Conn]bool
}
func (s *server) serveConn(ctx context.Context, c net.Conn, logf logger.Logf) {
s.addConn(c)
logf("incoming control connection")
defer s.removeAndCloseConn(c)
for ctx.Err() == nil {
msg, err := ipn.ReadMsg(c)
if err != nil {
logf("ReadMsg: %v\n", err)
break
if ctx.Err() == nil {
logf("ReadMsg: %v", err)
}
return
}
err = bs.GotCommandMsg(msg)
if err != nil {
logf("GotCommandMsg: %v\n", err)
break
s.bsMu.Lock()
if err := s.bs.GotCommandMsg(msg); err != nil {
logf("GotCommandMsg: %v", err)
}
gotQuit := s.bs.GotQuit
s.bsMu.Unlock()
if gotQuit {
return
}
}
}
func Run(rctx context.Context, logf logger.Logf, logid string, opts Options, e wgengine.Engine) (err error) {
runDone := make(chan error, 1)
defer func() { runDone <- err }()
func (s *server) addConn(c net.Conn) {
s.mu.Lock()
defer s.mu.Unlock()
if s.clients == nil {
s.clients = map[net.Conn]bool{}
}
s.clients[c] = true
}
func (s *server) removeAndCloseConn(c net.Conn) {
s.mu.Lock()
delete(s.clients, c)
remain := len(s.clients)
s.mu.Unlock()
if remain == 0 && s.resetOnZero {
s.bsMu.Lock()
s.bs.Reset()
s.bsMu.Unlock()
}
c.Close()
}
func (s *server) stopAll() {
s.mu.Lock()
defer s.mu.Unlock()
for c := range s.clients {
safesocket.ConnCloseRead(c)
safesocket.ConnCloseWrite(c)
}
s.clients = nil
}
func (s *server) writeToClients(b []byte) {
s.mu.Lock()
defer s.mu.Unlock()
for c := range s.clients {
ipn.WriteMsg(c, b)
}
}
func Run(ctx context.Context, logf logger.Logf, logid string, opts Options, e wgengine.Engine) error {
runDone := make(chan struct{})
defer close(runDone)
listen, _, err := safesocket.Listen(opts.SocketPath, uint16(opts.Port))
if err != nil {
return fmt.Errorf("safesocket.Listen: %v", err)
}
// Go listeners can't take a context, close it instead.
server := &server{
resetOnZero: !opts.SurviveDisconnects,
}
// When the context is closed or when we return, whichever is first, close our listner
// and all open connections.
go func() {
select {
case <-rctx.Done():
case <-ctx.Done():
case <-runDone:
}
server.stopAll()
listen.Close()
}()
logf("Listening on %v\n", listen.Addr())
logf("Listening on %v", listen.Addr())
bo := backoff.NewBackoff("ipnserver", logf)
if opts.ErrorMessage != "" {
for i := 1; ctx.Err() == nil; i++ {
s, err := listen.Accept()
if err != nil {
logf("%d: Accept: %v", i, err)
bo.BackOff(ctx, err)
continue
}
serverToClient := func(b []byte) {
ipn.WriteMsg(s, b)
}
go func() {
defer s.Close()
bs := ipn.NewBackendServer(logf, nil, serverToClient)
bs.SendErrorMessage(opts.ErrorMessage)
s.Read(make([]byte, 1))
}()
}
return ctx.Err()
}
var store ipn.StateStore
if opts.StatePath != "" {
@@ -109,22 +214,24 @@ func Run(rctx context.Context, logf logger.Logf, logid string, opts Options, e w
if err != nil {
return fmt.Errorf("NewLocalBackend: %v", err)
}
defer b.Shutdown()
b.SetDecompressor(func() (controlclient.Decompressor, error) {
return zstd.NewReader(nil)
return smallzstd.NewDecoder(nil)
})
b.SetCmpDiff(func(x, y interface{}) string { return cmp.Diff(x, y) })
var s net.Conn
serverToClient := func(b []byte) {
if s != nil { // TODO: racy access to s?
ipn.WriteMsg(s, b)
}
if opts.DebugMux != nil {
opts.DebugMux.HandleFunc("/debug/ipn", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
st := b.Status()
// TODO(bradfitz): add LogID and opts to st?
st.WriteHTML(w)
})
}
bs := ipn.NewBackendServer(logf, b, serverToClient)
server.bs = ipn.NewBackendServer(logf, b, server.writeToClients)
if opts.AutostartStateKey != "" {
bs.GotCommand(&ipn.Command{
server.bs.GotCommand(&ipn.Command{
Version: version.LONG,
Start: &ipn.StartArgs{
Opts: ipn.Options{
@@ -135,55 +242,18 @@ func Run(rctx context.Context, logf logger.Logf, logid string, opts Options, e w
})
}
var (
oldS net.Conn
ctx context.Context
cancel context.CancelFunc
)
stopAll := func() {
// Currently we only support one client connection at a time.
// Theoretically we could allow multiple clients, by passing
// notifications to all of them and accepting commands from
// any of them, but there doesn't seem to be much need for
// that right now.
if oldS != nil {
cancel()
safesocket.ConnCloseRead(oldS)
safesocket.ConnCloseWrite(oldS)
}
}
bo := backoff.Backoff{Name: "ipnserver"}
for i := 1; rctx.Err() == nil; i++ {
s, err = listen.Accept()
for i := 1; ctx.Err() == nil; i++ {
c, err := listen.Accept()
if err != nil {
logf("%d: Accept: %v\n", i, err)
bo.BackOff(rctx, err)
if ctx.Err() == nil {
logf("ipnserver: Accept: %v", err)
bo.BackOff(ctx, err)
}
continue
}
logf("%d: Incoming control connection.\n", i)
stopAll()
ctx, cancel = context.WithCancel(rctx)
oldS = s
go func(ctx context.Context, s net.Conn, i int) {
logf := logger.WithPrefix(logf, fmt.Sprintf("%d: ", i))
pump(logf, ctx, bs, s)
if !opts.SurviveDisconnects || bs.GotQuit {
bs.Reset()
s.Close()
}
// Quitting not allowed, just keep going.
bs.GotQuit = false
}(ctx, s, i)
bo.BackOff(ctx, nil)
go server.serveConn(ctx, c, logger.WithPrefix(logf, fmt.Sprintf("ipnserver: conn%d: ", i)))
}
stopAll()
return rctx.Err()
return ctx.Err()
}
func BabysitProc(ctx context.Context, args []string, logf logger.Logf) {
@@ -205,10 +275,10 @@ func BabysitProc(ctx context.Context, args []string, logf logger.Logf) {
var sig os.Signal
select {
case sig = <-interrupt:
logf("BabysitProc: got signal: %v\n", sig)
logf("BabysitProc: got signal: %v", sig)
close(done)
case <-ctx.Done():
logf("BabysitProc: context done\n")
logf("BabysitProc: context done")
sig = os.Kill
close(done)
}
@@ -218,11 +288,11 @@ func BabysitProc(ctx context.Context, args []string, logf logger.Logf) {
proc.mu.Unlock()
}()
bo := backoff.Backoff{Name: "BabysitProc"}
bo := backoff.NewBackoff("BabysitProc", logf)
for {
startTime := time.Now()
log.Printf("exec: %#v %v\n", executable, args)
log.Printf("exec: %#v %v", executable, args)
cmd := exec.Command(executable, args...)
// Create a pipe object to use as the subproc's stdin.
@@ -233,7 +303,7 @@ func BabysitProc(ctx context.Context, args []string, logf logger.Logf) {
// We never need to actually write to wStdin.
rStdin, wStdin, err := os.Pipe()
if err != nil {
log.Printf("os.Pipe 1: %v\n", err)
log.Printf("os.Pipe 1: %v", err)
return
}
@@ -245,7 +315,7 @@ func BabysitProc(ctx context.Context, args []string, logf logger.Logf) {
// logf() calls. bufio is more appropriate.
rStdout, wStdout, err := os.Pipe()
if err != nil {
log.Printf("os.Pipe 2: %v\n", err)
log.Printf("os.Pipe 2: %v", err)
}
go func(r *os.File) {
defer r.Close()
@@ -253,7 +323,7 @@ func BabysitProc(ctx context.Context, args []string, logf logger.Logf) {
for {
s, err := rb.ReadString('\n')
if s != "" {
logf("%s\n", strings.TrimSuffix(s, "\n"))
logf("%s", s)
}
if err != nil {
break

304
ipn/ipnstate/ipnstate.go Normal file
View File

@@ -0,0 +1,304 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package ipnstate captures the entire state of the Tailscale network.
//
// It's a leaf package so ipn, wgengine, and magicsock can all depend on it.
package ipnstate
import (
"bytes"
"fmt"
"html"
"io"
"log"
"sort"
"strings"
"sync"
"time"
"tailscale.com/tailcfg"
"tailscale.com/types/key"
)
// Status represents the entire state of the IPN network.
type Status struct {
BackendState string
Peer map[key.Public]*PeerStatus
User map[tailcfg.UserID]tailcfg.UserProfile
}
func (s *Status) Peers() []key.Public {
kk := make([]key.Public, 0, len(s.Peer))
for k := range s.Peer {
kk = append(kk, k)
}
sort.Slice(kk, func(i, j int) bool { return bytes.Compare(kk[i][:], kk[j][:]) < 0 })
return kk
}
type PeerStatus struct {
PublicKey key.Public
HostName string // HostInfo's Hostname (not a DNS name or necessarily unique)
OS string // HostInfo.OS
UserID tailcfg.UserID
TailAddr string // Tailscale IP
// Endpoints:
Addrs []string
CurAddr string // one of Addrs, or unique if roaming
Relay string // DERP region
RxBytes int64
TxBytes int64
Created time.Time // time registered with tailcontrol
LastWrite time.Time // time last packet sent
LastSeen time.Time // last seen to tailcontrol
LastHandshake time.Time // with local wireguard
KeepAlive bool
// InNetworkMap means that this peer was seen in our latest network map.
// In theory, all of InNetworkMap and InMagicSock and InEngine should all be true.
InNetworkMap bool
// InMagicSock means that this peer is being tracked by magicsock.
// In theory, all of InNetworkMap and InMagicSock and InEngine should all be true.
InMagicSock bool
// InEngine means that this peer is tracked by the wireguard engine.
// In theory, all of InNetworkMap and InMagicSock and InEngine should all be true.
InEngine bool
}
// SimpleHostName returns a potentially simplified version of ps.HostName for display purposes.
func (ps *PeerStatus) SimpleHostName() string {
n := ps.HostName
n = strings.TrimSuffix(n, ".local")
n = strings.TrimSuffix(n, ".localdomain")
return n
}
type StatusBuilder struct {
mu sync.Mutex
locked bool
st Status
}
func (sb *StatusBuilder) Status() *Status {
sb.mu.Lock()
defer sb.mu.Unlock()
sb.locked = true
return &sb.st
}
// AddUser adds a user profile to the status.
func (sb *StatusBuilder) AddUser(id tailcfg.UserID, up tailcfg.UserProfile) {
sb.mu.Lock()
defer sb.mu.Unlock()
if sb.locked {
log.Printf("[unexpected] ipnstate: AddUser after Locked")
return
}
if sb.st.User == nil {
sb.st.User = make(map[tailcfg.UserID]tailcfg.UserProfile)
}
sb.st.User[id] = up
}
// AddPeer adds a peer node to the status.
//
// Its PeerStatus is mixed with any previous status already added.
func (sb *StatusBuilder) AddPeer(peer key.Public, st *PeerStatus) {
if st == nil {
panic("nil PeerStatus")
}
sb.mu.Lock()
defer sb.mu.Unlock()
if sb.locked {
log.Printf("[unexpected] ipnstate: AddPeer after Locked")
return
}
if sb.st.Peer == nil {
sb.st.Peer = make(map[key.Public]*PeerStatus)
}
e, ok := sb.st.Peer[peer]
if !ok {
sb.st.Peer[peer] = st
st.PublicKey = peer
return
}
if v := st.HostName; v != "" {
e.HostName = v
}
if v := st.Relay; v != "" {
e.Relay = v
}
if v := st.UserID; v != 0 {
e.UserID = v
}
if v := st.TailAddr; v != "" {
e.TailAddr = v
}
if v := st.OS; v != "" {
e.OS = st.OS
}
if v := st.Addrs; v != nil {
e.Addrs = v
}
if v := st.CurAddr; v != "" {
e.CurAddr = v
}
if v := st.RxBytes; v != 0 {
e.RxBytes = v
}
if v := st.TxBytes; v != 0 {
e.TxBytes = v
}
if v := st.LastHandshake; !v.IsZero() {
e.LastHandshake = v
}
if v := st.Created; !v.IsZero() {
e.Created = v
}
if v := st.LastSeen; !v.IsZero() {
e.LastSeen = v
}
if v := st.LastWrite; !v.IsZero() {
e.LastWrite = v
}
if st.InNetworkMap {
e.InNetworkMap = true
}
if st.InMagicSock {
e.InMagicSock = true
}
if st.InEngine {
e.InEngine = true
}
if st.KeepAlive {
e.KeepAlive = true
}
}
type StatusUpdater interface {
UpdateStatus(*StatusBuilder)
}
func (st *Status) WriteHTML(w io.Writer) {
f := func(format string, args ...interface{}) { fmt.Fprintf(w, format, args...) }
f(`<!DOCTYPE html>
<html lang="en">
<head>
<title>Tailscale State</title>
<style>
body { font-family: monospace; }
.owner { text-decoration: underline; }
.tailaddr { font-style: italic; }
.acenter { text-align: center; }
.aright { text-align: right; }
table, th, td { border: 1px solid black; border-spacing : 0; border-collapse : collapse; }
thead { background-color: #FFA500; }
th, td { padding: 5px; }
td { vertical-align: top; }
table tbody tr:nth-child(even) td { background-color: #f5f5f5; }
</style>
</head>
<body>
<h1>Tailscale State</h1>
`)
//f("<p><b>logid:</b> %s</p>\n", logid)
//f("<p><b>opts:</b> <code>%s</code></p>\n", html.EscapeString(fmt.Sprintf("%+v", opts)))
f("<table>\n<thead>\n")
f("<tr><th>Peer</th><th>Node</th><th>Owner</th><th>Rx</th><th>Tx</th><th>Activity</th><th>Endpoints</th></tr>\n")
f("</thead>\n<tbody>\n")
now := time.Now()
for _, peer := range st.Peers() {
ps := st.Peer[peer]
var actAgo string
if !ps.LastWrite.IsZero() {
ago := now.Sub(ps.LastWrite)
actAgo = ago.Round(time.Second).String() + " ago"
if ago < 5*time.Minute {
actAgo = "<b>" + actAgo + "</b>"
}
}
var owner string
if up, ok := st.User[ps.UserID]; ok {
owner = up.LoginName
if i := strings.Index(owner, "@"); i != -1 {
owner = owner[:i]
}
}
f("<tr><td>%s</td><td>%s %s<br><span class=\"tailaddr\">%s</span></td><td class=\"acenter owner\">%s</td><td class=\"aright\">%v</td><td class=\"aright\">%v</td><td class=\"aright\">%v</td>",
peer.ShortString(),
html.EscapeString(ps.SimpleHostName()),
osEmoji(ps.OS),
ps.TailAddr,
html.EscapeString(owner),
ps.RxBytes,
ps.TxBytes,
actAgo,
)
f("<td class=\"aright\">")
// TODO: let server report this active bool instead
active := !ps.LastWrite.IsZero() && time.Since(ps.LastWrite) < 2*time.Minute
relay := ps.Relay
if relay != "" {
if active && ps.CurAddr == "" {
f("🔗 <b>derp-%v</b><br>", html.EscapeString(relay))
} else {
f("derp-%v<br>", html.EscapeString(relay))
}
}
match := false
for _, addr := range ps.Addrs {
if addr == ps.CurAddr {
match = true
f("🔗 <b>%s</b><br>", addr)
} else {
f("%s<br>", addr)
}
}
if ps.CurAddr != "" && !match {
f("<b>%s</b> \xf0\x9f\xa7\xb3<br>", ps.CurAddr)
}
f("</td>") // end Addrs
f("</tr>\n")
}
f("</tbody>\n</table>\n")
f("</body>\n</html>\n")
}
func osEmoji(os string) string {
switch os {
case "linux":
return "🐧"
case "macOS":
return "🍎"
case "windows":
return "🖥️"
case "iOS":
return "📱"
case "android":
return "🤖"
case "freebsd":
return "👿"
case "openbsd":
return "🐡"
}
return "👽"
}

File diff suppressed because it is too large Load Diff

View File

@@ -13,7 +13,9 @@ import (
"log"
"time"
"golang.org/x/oauth2"
"tailscale.com/types/logger"
"tailscale.com/types/structs"
"tailscale.com/version"
)
@@ -34,15 +36,25 @@ type FakeExpireAfterArgs struct {
// Command is a command message that is JSON encoded and sent by a
// frontend to a backend.
type Command struct {
_ structs.Incomparable
// Version is the binary version of the frontend (the client).
Version string
// AllowVersionSkew controls whether it's permitted for the
// client and server to have a different version. The default
// (false) means to be strict.
AllowVersionSkew bool
// Exactly one of the following must be non-nil.
Quit *NoArgs
Start *StartArgs
StartLoginInteractive *NoArgs
Login *oauth2.Token
Logout *NoArgs
SetPrefs *SetPrefsArgs
RequestEngineStatus *NoArgs
RequestStatus *NoArgs
FakeExpireAfter *FakeExpireAfterArgs
}
@@ -65,26 +77,38 @@ func (bs *BackendServer) send(n Notify) {
n.Version = version.LONG
b, err := json.Marshal(n)
if err != nil {
log.Fatalf("Failed json.Marshal(notify): %v\n%#v\n", err, n)
log.Fatalf("Failed json.Marshal(notify): %v\n%#v", err, n)
}
bs.sendNotifyMsg(b)
}
func (bs *BackendServer) SendErrorMessage(msg string) {
bs.send(Notify{ErrMessage: &msg})
}
// GotCommandMsg parses the incoming message b as a JSON Command and
// calls GotCommand with it.
func (bs *BackendServer) GotCommandMsg(b []byte) error {
cmd := &Command{}
if len(b) == 0 {
return nil
}
if err := json.Unmarshal(b, cmd); err != nil {
return err
}
return bs.GotCommand(cmd)
}
func (bs *BackendServer) GotFakeCommand(cmd *Command) error {
cmd.Version = version.LONG
return bs.GotCommand(cmd)
}
func (bs *BackendServer) GotCommand(cmd *Command) error {
if cmd.Version != version.LONG {
vs := fmt.Sprintf("Version mismatch! frontend=%#v backend=%#v\n",
if cmd.Version != version.LONG && !cmd.AllowVersionSkew {
vs := fmt.Sprintf("GotCommand: Version mismatch! frontend=%#v backend=%#v",
cmd.Version, version.LONG)
bs.logf("%s\n", vs)
bs.logf("%s", vs)
// ignore the command, but send a message back to the
// caller so it can realize the version mismatch too.
// We don't want to exit because it might cause a crash
@@ -106,6 +130,9 @@ func (bs *BackendServer) GotCommand(cmd *Command) error {
} else if c := cmd.StartLoginInteractive; c != nil {
bs.b.StartLoginInteractive()
return nil
} else if c := cmd.Login; c != nil {
bs.b.Login(c)
return nil
} else if c := cmd.Logout; c != nil {
bs.b.Logout()
return nil
@@ -115,6 +142,9 @@ func (bs *BackendServer) GotCommand(cmd *Command) error {
} else if c := cmd.RequestEngineStatus; c != nil {
bs.b.RequestEngineStatus()
return nil
} else if c := cmd.RequestStatus; c != nil {
bs.b.RequestStatus()
return nil
} else if c := cmd.FakeExpireAfter; c != nil {
bs.b.FakeExpireAfter(c.Duration)
return nil
@@ -126,13 +156,17 @@ func (bs *BackendServer) GotCommand(cmd *Command) error {
func (bs *BackendServer) Reset() error {
// Tell the backend we got a Logout command, which will cause it
// to forget all its authentication information.
return bs.GotCommand(&Command{Logout: &NoArgs{}})
return bs.GotFakeCommand(&Command{Logout: &NoArgs{}})
}
type BackendClient struct {
logf logger.Logf
sendCommandMsg func(jsonb []byte)
notify func(Notify)
// AllowVersionSkew controls whether to allow mismatched
// frontend & backend versions.
AllowVersionSkew bool
}
func NewBackendClient(logf logger.Logf, sendCommandMsg func(jsonb []byte)) *BackendClient {
@@ -143,14 +177,18 @@ func NewBackendClient(logf logger.Logf, sendCommandMsg func(jsonb []byte)) *Back
}
func (bc *BackendClient) GotNotifyMsg(b []byte) {
if len(b) == 0 {
// not interesting
return
}
n := Notify{}
if err := json.Unmarshal(b, &n); err != nil {
log.Fatalf("BackendClient.Notify: cannot decode message")
log.Fatalf("BackendClient.Notify: cannot decode message (length=%d)\n%#v", len(b), string(b))
}
if n.Version != version.LONG {
vs := fmt.Sprintf("Version mismatch! frontend=%#v backend=%#v",
if n.Version != version.LONG && !bc.AllowVersionSkew {
vs := fmt.Sprintf("GotNotify: Version mismatch! frontend=%#v backend=%#v",
version.LONG, n.Version)
bc.logf("%s\n", vs)
bc.logf("%s", vs)
// delete anything in the notification except the version,
// to prevent incorrect operation.
n = Notify{
@@ -172,6 +210,10 @@ func (bc *BackendClient) send(cmd Command) {
bc.sendCommandMsg(b)
}
func (bc *BackendClient) SetNotifyCallback(fn func(Notify)) {
bc.notify = fn
}
func (bc *BackendClient) Quit() error {
bc.send(Command{Quit: &NoArgs{}})
return nil
@@ -188,6 +230,10 @@ func (bc *BackendClient) StartLoginInteractive() {
bc.send(Command{StartLoginInteractive: &NoArgs{}})
}
func (bc *BackendClient) Login(token *oauth2.Token) {
bc.send(Command{Login: token})
}
func (bc *BackendClient) Logout() {
bc.send(Command{Logout: &NoArgs{}})
}
@@ -200,6 +246,10 @@ func (bc *BackendClient) RequestEngineStatus() {
bc.send(Command{RequestEngineStatus: &NoArgs{}})
}
func (bc *BackendClient) RequestStatus() {
bc.send(Command{AllowVersionSkew: true, RequestStatus: &NoArgs{}})
}
func (bc *BackendClient) FakeExpireAfter(x time.Duration) {
bc.send(Command{FakeExpireAfter: &FakeExpireAfterArgs{Duration: x}})
}
@@ -220,10 +270,13 @@ func ReadMsg(r io.Reader) ([]byte, error) {
return nil, fmt.Errorf("ipn.Read: message too large: %v bytes", n)
}
b := make([]byte, n)
_, err = io.ReadFull(r, b)
nn, err := io.ReadFull(r, b)
if err != nil {
return nil, err
}
if nn != int(n) {
return nil, fmt.Errorf("ipn.Read: expected %v bytes, got %v", n, nn)
}
return b, nil
}

View File

@@ -9,14 +9,14 @@ import (
"testing"
"time"
"tailscale.com/testy"
"golang.org/x/oauth2"
"tailscale.com/tstest"
)
func TestReadWrite(t *testing.T) {
testy.FixLogs(t)
defer testy.UnfixLogs(t)
tstest.PanicOnLog()
rc := testy.NewResourceCheck()
rc := tstest.NewResourceCheck()
defer rc.Assert(t)
buf := bytes.Buffer{}
@@ -62,10 +62,9 @@ func TestReadWrite(t *testing.T) {
}
func TestClientServer(t *testing.T) {
testy.FixLogs(t)
defer testy.UnfixLogs(t)
tstest.PanicOnLog()
rc := testy.NewResourceCheck()
rc := tstest.NewResourceCheck()
defer rc.Assert(t)
b := &FakeBackend{}
@@ -179,4 +178,10 @@ func TestClientServer(t *testing.T) {
h.Logout()
flushUntil(NeedsLogin)
h.Login(&oauth2.Token{
AccessToken: "google_id_token",
TokenType: GoogleIDTokenType,
})
flushUntil(Running)
}

42
ipn/policy/policy.go Normal file
View File

@@ -0,0 +1,42 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package policy contains various policy decisions that need to be
// shared between the node client & control server.
package policy
import "tailscale.com/tailcfg"
// IsInterestingService reports whether service s on the given operating
// system (a version.OS value) is an interesting enough port to report
// to our peer nodes for discovery purposes.
func IsInterestingService(s tailcfg.Service, os string) bool {
if s.Proto != tailcfg.TCP {
return false
}
if os != "windows" {
// For non-Windows machines, assume all TCP listeners
// are interesting enough. We don't see listener spam
// there.
return true
}
// Windows has tons of TCP listeners. We need to move to a blacklist
// model later, but for now we just whitelist some common ones:
switch s.Port {
case 22, // ssh
80, // http
443, // https (but no hostname, so little useless)
3389, // rdp
5900, // vnc
32400, // plex
// And now some arbitary HTTP dev server ports:
// Eventually we'll remove this and make all ports
// work, once we nicely filter away noisy system
// ports.
8000, 8080, 8443, 8888:
return true
}
return false
}

Some files were not shown because too many files have changed in this diff Show More