tsnet
packageThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
Documentation¶
Overview¶
Package tsnet provides Tailscale as a library.
Example (Tshello)¶
Example_tshello is a full example on using tsnet. When you run this program it will printan authentication link. Open it in your favorite web browser and add it to your tailnetlike any other machine. Open another terminal window and try to ping it:
$ ping tshello -c 2PING tshello (100.105.183.159) 56(84) bytes of data.64 bytes from tshello.your-tailnet.ts.net (100.105.183.159): icmp_seq=1 ttl=64 time=25.0 ms64 bytes from tshello.your-tailnet.ts.net (100.105.183.159): icmp_seq=2 ttl=64 time=1.12 ms
Then connect to it using curl:
$ curl http://tshello<html><body><h1>Hello, world!</h1><p>You are <b>Xe</b> from <b>pneuma</b> (100.78.40.86:49214)</p>
From here you can do anything you want with the Go standard library HTTP stack, or anythingthat is compatible with it (Gin/Gonic, Gorilla/mux, etc.).
package mainimport ("flag""fmt""html""log""net/http""strings""tailscale.com/tsnet")func firstLabel(s string) string {s, _, _ = strings.Cut(s, ".")return s}// Example_tshello is a full example on using tsnet. When you run this program it will print// an authentication link. Open it in your favorite web browser and add it to your tailnet// like any other machine. Open another terminal window and try to ping it:////$ ping tshello -c 2//PING tshello (100.105.183.159) 56(84) bytes of data.//64 bytes from tshello.your-tailnet.ts.net (100.105.183.159): icmp_seq=1 ttl=64 time=25.0 ms//64 bytes from tshello.your-tailnet.ts.net (100.105.183.159): icmp_seq=2 ttl=64 time=1.12 ms//// Then connect to it using curl:////$ curl http://tshello//<html><body><h1>Hello, world!</h1>//<p>You are <b>Xe</b> from <b>pneuma</b> (100.78.40.86:49214)</p>//// From here you can do anything you want with the Go standard library HTTP stack, or anything// that is compatible with it (Gin/Gonic, Gorilla/mux, etc.).func main() {var (addr = flag.String("addr", ":80", "address to listen on")hostname = flag.String("hostname", "tshello", "hostname to use on the tailnet"))flag.Parse()s := new(tsnet.Server)s.Hostname = *hostnamedefer s.Close()ln, err := s.Listen("tcp", *addr)if err != nil {log.Fatal(err)}defer ln.Close()lc, err := s.LocalClient()if err != nil {log.Fatal(err)}log.Fatal(http.Serve(ln, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {who, err := lc.WhoIs(r.Context(), r.RemoteAddr)if err != nil {http.Error(w, err.Error(), 500)return}fmt.Fprintf(w, "<html><body><h1>Hello, tailnet!</h1>\n")fmt.Fprintf(w, "<p>You are <b>%s</b> from <b>%s</b> (%s)</p>",html.EscapeString(who.UserProfile.LoginName),html.EscapeString(firstLabel(who.Node.ComputedName)),r.RemoteAddr)})))}Index¶
- type FallbackTCPHandler
- type FunnelOption
- type Server
- func (s *Server) CapturePcap(ctx context.Context, pcapFile string) error
- func (s *Server) CertDomains() []string
- func (s *Server) Close() error
- func (s *Server) Dial(ctx context.Context, network, address string) (net.Conn, error)
- func (s *Server) GetRootPath() string
- func (s *Server) HTTPClient() *http.Client
- func (s *Server) Listen(network, addr string) (net.Listener, error)
- func (s *Server) ListenFunnel(network, addr string, opts ...FunnelOption) (net.Listener, error)
- func (s *Server) ListenPacket(network, addr string) (net.PacketConn, error)
- func (s *Server) ListenTLS(network, addr string) (net.Listener, error)
- func (s *Server) LocalClient() (*local.Client, error)
- func (s *Server) LogtailWriter() io.Writer
- func (s *Server) Loopback() (addr string, proxyCred, localAPICred string, err error)
- func (s *Server) RegisterFallbackTCPHandler(cb FallbackTCPHandler) func()
- func (s *Server) Start() error
- func (s *Server) Sys() *tsd.System
- func (s *Server) TailscaleIPs() (ip4, ip6 netip.Addr)
- func (s *Server) Up(ctx context.Context) (*ipnstate.Status, error)
Examples¶
Constants¶
This section is empty.
Variables¶
This section is empty.
Functions¶
This section is empty.
Types¶
typeFallbackTCPHandler¶added inv1.52.0
FallbackTCPHandler describes the callback whichconditionally handles an incoming TCP flow for theprovided (src/port, dst/port) 4-tuple. These are registeredas handlers of last resort, and are called only if nolistener could handle the incoming flow.
If the callback returns intercept=false, the flow is rejected.
When intercept=true, the behavior depends on whether the returned handleris non-nil: if nil, the connection is rejected. If non-nil, handler takesover the TCP conn.
typeFunnelOption¶added inv1.38.0
type FunnelOption interface {// contains filtered or unexported methods}FunnelOption is an option passed to ListenFunnel to configure the listener.
funcFunnelOnly¶added inv1.38.0
func FunnelOnly()FunnelOption
FunnelOnly configures the listener to only respond to connections from Tailscale Funnel.The local tailnet will not be able to connect to the listener.
funcFunnelTLSConfig¶added inv1.84.0
func FunnelTLSConfig(conf *tls.Config)FunnelOption
FunnelTLSConfig configures the TLS configuration forServer.ListenFunnel
This is rarely needed but can permit requiring client certificates, specificciphers suites, etc.
The provided conf should at least be able to get a certificate, settingGetCertificate, Certificates or GetConfigForClient appropriately.The most common configuration is to set GetCertificate toServer.LocalClient's GetCertificate method.
UnlessFunnelOnly is also used, the configuration is also used forin-tailnet connections that don't arrive over Funnel.
typeServer¶
type Server struct {// Dir specifies the name of the directory to use for// state. If empty, a directory is selected automatically// under os.UserConfigDir (https://golang.org/pkg/os/#UserConfigDir).// based on the name of the binary.//// If you want to use multiple tsnet services in the same// binary, you will need to make sure that Dir is set uniquely// for each service. A good pattern for this is to have a// "base" directory (such as your mutable storage folder) and// then append the hostname on the end of it.Dirstring// Store specifies the state store to use.//// If nil, a new FileStore is initialized at `Dir/tailscaled.state`.// See tailscale.com/ipn/store for supported stores.//// Logs will automatically be uploaded to log.tailscale.com,// where the configuration file for logging will be saved at// `Dir/tailscaled.log.conf`.Storeipn.StateStore// Hostname is the hostname to present to the control server.// If empty, the binary name is used.Hostnamestring// UserLogf, if non-nil, specifies the logger to use for logs generated by// the Server itself intended to be seen by the user such as the AuthURL for// login and status updates. If unset, log.Printf is used.UserLogflogger.Logf// Logf, if set is used for logs generated by the backend such as the// LocalBackend and MagicSock. It is verbose and intended for debugging.// If unset, logs are discarded.Logflogger.Logf// Ephemeral, if true, specifies that the instance should register// as an Ephemeral node (https://tailscale.com/s/ephemeral-nodes).Ephemeralbool// AuthKey, if non-empty, is the auth key to create the node// and will be preferred over the TS_AUTHKEY environment// variable. If the node is already created (from state// previously stored in Store), then this field is not// used.AuthKeystring// ControlURL optionally specifies the coordination server URL.// If empty, the Tailscale default is used.ControlURLstring// RunWebClient, if true, runs a client for managing this node over// its Tailscale interface on port 5252.RunWebClientbool// Port is the UDP port to listen on for WireGuard and peer-to-peer// traffic. If zero, a port is automatically selected. Leave this// field at zero unless you know what you are doing.Portuint16// AdvertiseTags specifies tags that should be applied to this node, for// purposes of ACL enforcement. These can be referenced from the ACL policy// document. Note that advertising a tag on the client doesn't guarantee// that the control server will allow the node to adopt that tag.AdvertiseTags []string// contains filtered or unexported fields}Server is an embedded Tailscale server.
Its exported fields may be changed until the first method call.
Example¶
ExampleServer shows you how to construct a ready-to-use tsnet instance.
package mainimport ("log""tailscale.com/tsnet")func main() {srv := new(tsnet.Server)if err := srv.Start(); err != nil {log.Fatalf("can't start tsnet server: %v", err)}defer srv.Close()}Example (Dir)¶
ExampleServer_dir shows you how to configure the persistent directory fora tsnet application. This is where the Tailscale node information is storedso that your application can reconnect to your tailnet when the applicationis restarted.
By default, tsnet will store data in your user configuration directory basedon the name of the binary. Note that this folder must already exist or tsnetcalls will fail.
package mainimport ("log""os""path/filepath""tailscale.com/tsnet")func main() {dir := filepath.Join("/data", "tsnet")if err := os.MkdirAll(dir, 0700); err != nil {log.Fatal(err)}srv := &tsnet.Server{Dir: dir,}// do something with srv_ = srv}Example (Hostname)¶
ExampleServer_hostname shows you how to set a tsnet server's hostname.
This setting lets you control the host name of your program on yourtailnet. By default this will be the name of your program (such as foofor a program stored at /usr/local/bin/foo). You can also override thisby setting the Hostname field.
package mainimport ("tailscale.com/tsnet")func main() {srv := &tsnet.Server{Hostname: "kirito",}// do something with srv_ = srv}Example (IgnoreLogsSometimes)¶
ExampleServer_ignoreLogsSometimes shows you how to ignore all of the log messageswritten by a tsnet instance, but allows you to opt-into them if a command-lineflag is set.
package mainimport ("flag""fmt""log""os""tailscale.com/tsnet")func main() {tsnetVerbose := flag.Bool("tsnet-verbose", false, "if set, verbosely log tsnet information")hostname := flag.String("tsnet-hostname", "hikari", "hostname to use on the tailnet")srv := &tsnet.Server{Hostname: *hostname,}if *tsnetVerbose {srv.Logf = log.New(os.Stderr, fmt.Sprintf("[tsnet:%s] ", *hostname), log.LstdFlags).Printf}}Example (MultipleInstances)¶
ExampleServer_multipleInstances shows you how to configure multiple instancesof tsnet per program. This allows you to have multiple Tailscale nodes in thesame process/container.
package mainimport ("log""os""path/filepath""tailscale.com/tsnet")func main() {baseDir := "/data"var servers []*tsnet.Serverfor _, hostname := range []string{"ichika", "nino", "miku", "yotsuba", "itsuki"} {os.MkdirAll(filepath.Join(baseDir, hostname), 0700)srv := &tsnet.Server{Hostname: hostname,AuthKey: os.Getenv("TS_AUTHKEY"),Ephemeral: true,Dir: filepath.Join(baseDir, hostname),}if err := srv.Start(); err != nil {log.Fatalf("can't start tsnet server: %v", err)}servers = append(servers, srv)}// When you're done, close the instancesdefer func() {for _, srv := range servers {srv.Close()}}()}func (*Server)CapturePcap¶added inv1.56.0
CapturePcap can be called by the application code compiled with tsnet to save a pcapof packets which the netstack within tsnet sees. This is expected to be useful duringdebugging, probably not useful for production.
Packets will be written to the pcap until the process exits. The pcap needs a Lua dissectorto be installed in WireShark in order to decode properly: wgengine/capture/ts-dissector.luain this repository.https://tailscale.com/kb/1023/troubleshooting/#can-i-examine-network-traffic-inside-the-encrypted-tunnel
func (*Server)CertDomains¶added inv1.38.0
CertDomains returns the list of domains for which the server canprovide TLS certificates. These are also the DNS names for theServer.If the server is not running, it returns nil.
func (*Server)Close¶added inv1.24.0
Close stops the server.
It must not be called before or concurrently with Start.
func (*Server)Dial¶added inv1.20.0
Dial connects to the address on the tailnet.It will start the server if it has not been started yet.
func (*Server)GetRootPath¶added inv1.88.0
GetRootPath returns the root path of the tsnet server.This is where the state file and other data is stored.
func (*Server)HTTPClient¶added inv1.36.0
HTTPClient returns an HTTP client that is configured to connect over Tailscale.
This is useful if you need to have your tsnet services connect to other devices onyour tailnet.
Example¶
ExampleServer_HTTPClient shows you how to make HTTP requests over your tailnet.
If you want to make outgoing HTTP connections to resources on your tailnet, usethe HTTP client that the tsnet.Server exposes.
package mainimport ("log""tailscale.com/tsnet")func main() {srv := &tsnet.Server{}cli := srv.HTTPClient()resp, err := cli.Get("https://hello.ts.net")if resp == nil {log.Fatal(err)}// do something with resp_ = resp}func (*Server)Listen¶
Listen announces only on the Tailscale network.It will start the server if it has not been started yet.
Listeners which do not specify an IP address will match for trafficfor the local node (that is, a destination address of the IPv4 orIPv6 address of this node) only. To listen for traffic on other addressessuch as those routed inbound via subnet routes, explicitly specifythe listening address or use RegisterFallbackTCPHandler.
Example¶
ExampleServer_Listen shows you how to create a TCP listener on your tailnet andthen makes an HTTP server on top of that.
package mainimport ("fmt""log""net/http""tailscale.com/tsnet")func main() {srv := &tsnet.Server{Hostname: "tadaima",}ln, err := srv.Listen("tcp", ":80")if err != nil {log.Fatal(err)}log.Fatal(http.Serve(ln, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {fmt.Fprintln(w, "Hi there! Welcome to the tailnet!")})))}func (*Server)ListenFunnel¶added inv1.38.0
ListenFunnel announces on the public internet using Tailscale Funnel.
It also by default listens on your local tailnet, so connections cancome from either inside or outside your network. To restrict connectionsto be just from the internet, use the FunnelOnly option.
Currently (2023-03-10), Funnel only supports TCP on ports 443, 8443, and 10000.The supported host name is limited to that configured for the tsnet.Server.As such, the standard way to create funnel is:
s.ListenFunnel("tcp", ":443")and the only other supported addrs currently are ":8443" and ":10000".
It will start the server if it has not been started yet.
Example¶
ExampleServer_ListenFunnel shows you how to create an HTTPS service on both your tailnetand the public internet via Funnel.
package mainimport ("fmt""log""net/http""tailscale.com/tsnet")func main() {srv := &tsnet.Server{Hostname: "ophion",}ln, err := srv.ListenFunnel("tcp", ":443")if err != nil {log.Fatal(err)}log.Fatal(http.Serve(ln, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {fmt.Fprintln(w, "Hi there! Welcome to the tailnet!")})))}Example (FunnelOnly)¶
ExampleServer_ListenFunnel_funnelOnly shows you how to create a funnel-only HTTPS service.
package mainimport ("fmt""log""net/http""tailscale.com/tsnet")func main() {srv := new(tsnet.Server)srv.Hostname = "ophion"ln, err := srv.ListenFunnel("tcp", ":443", tsnet.FunnelOnly())if err != nil {log.Fatal(err)}log.Fatal(http.Serve(ln, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {fmt.Fprintln(w, "Hi there! Welcome to the tailnet!")})))}func (*Server)ListenPacket¶added inv1.68.0
func (s *Server) ListenPacket(network, addrstring) (net.PacketConn,error)
ListenPacket announces on the Tailscale network.
The network must be "udp", "udp4" or "udp6". The addr must be of the form"ip:port" (or "[ip]:port") where ip is a valid IPv4 or IPv6 addresscorresponding to "udp4" or "udp6" respectively. IP must be specified.
If s has not been started yet, it will be started.
func (*Server)ListenTLS¶added inv1.38.0
ListenTLS announces only on the Tailscale network.It returns a TLS listener wrapping the tsnet listener.It will start the server if it has not been started yet.
Example¶
ExampleServer_ListenTLS shows you how to create a TCP listener on your tailnet andthen makes an HTTPS server on top of that.
package mainimport ("fmt""log""net/http""tailscale.com/tsnet")func main() {srv := &tsnet.Server{Hostname: "aegis",}ln, err := srv.ListenTLS("tcp", ":443")if err != nil {log.Fatal(err)}log.Fatal(http.Serve(ln, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {fmt.Fprintln(w, "Hi there! Welcome to the tailnet!")})))}func (*Server)LocalClient¶added inv1.26.0
LocalClient returns a LocalClient that speaks to s.
It will start the server if it has not been started yet. If the server'salready been started successfully, it doesn't return an error.
func (*Server)LogtailWriter¶added inv1.90.0
LogtailWriter returns anio.Writer that writes to Tailscale's logging service and will be only visible to Tailscale'ssupport team. Logs written there cannot be retrieved by the user. This method always returns a non-nil value.
func (*Server)Loopback¶added inv1.38.0
Loopback starts a routing server on a loopback address.
The server has multiple functions.
It can be used as a SOCKS5 proxy onto the tailnet.Authentication is required with the username "tsnet" andthe value of proxyCred used as the password.
The HTTP server also serves out the "LocalAPI" on /localapi.As the LocalAPI is powerful, access to endpoints requires BOTH passing a"Sec-Tailscale: localapi" HTTP header and passing localAPICred as basic auth.
If you only need to use the LocalAPI from Go, then prefer LocalClientas it does not require communication via TCP.
func (*Server)RegisterFallbackTCPHandler¶added inv1.52.0
func (s *Server) RegisterFallbackTCPHandler(cbFallbackTCPHandler) func()
RegisterFallbackTCPHandler registers a callback which will be calledto handle a TCP flow to this tsnet node, for which no listeners will handle.
If multiple fallback handlers are registered, they will be called in anundefined order. See FallbackTCPHandler for details on handling a flow.
The returned function can be used to deregister this callback.
func (*Server)Start¶added inv1.20.0
Start connects the server to the tailnet.Optional: any calls to Dial/Listen will also call Start.
Example¶
ExampleServer_Start demonstrates the Start method, which should be called ifyou need to explicitly start it. Note that the Start method is implicitlycalled if needed.
package mainimport ("log""tailscale.com/tsnet")func main() {srv := new(tsnet.Server)if err := srv.Start(); err != nil {log.Fatal(err)}// Be sure to close the server instance at some point. It will stay open until// either the OS process ends or the server is explicitly closed.defer srv.Close()}func (*Server)Sys¶added inv1.78.0
Sys returns a handle to the Tailscale subsystems of this node.
This is not a stable API, nor are the APIs of the returned subsystems.
func (*Server)TailscaleIPs¶added inv1.38.0
TailscaleIPs returns IPv4 and IPv6 addresses for this node. If the nodehas not yet joined a tailnet or is otherwise unaware of its own IP addresses,the returned ip4, ip6 will be !netip.IsValid().
Directories¶
| Path | Synopsis |
|---|---|
example | |
tshellocommand The tshello server demonstrates how to use Tailscale as a library. | The tshello server demonstrates how to use Tailscale as a library. |
tsnet-funnelcommand The tsnet-funnel server demonstrates how to use tsnet with Funnel. | The tsnet-funnel server demonstrates how to use tsnet with Funnel. |
tsnet-http-clientcommand The tshello server demonstrates how to use Tailscale as a library. | The tshello server demonstrates how to use Tailscale as a library. |
web-clientcommand The web-client command demonstrates serving the Tailscale web client over tsnet. | The web-client command demonstrates serving the Tailscale web client over tsnet. |