package tsbridge import ( "context" "crypto/tls" "encoding/json" "errors" "fmt" "log" "net" "net/http" "net/netip" "os" "strings" "sync" "time" "tailscale.com/tsnet" ) // The gomobile-facing surface. gomobile has no shared state objects across // calls, so the server is a package-level singleton and all state is exposed // through Status() as a JSON string that Kotlin parses. const ( // maxLogLines is how many recent log lines Status() reports. maxLogLines = 40 // authURLMarker is the substring tsnet logs right before the interactive // login URL when no auth key is set. authURLMarker = "or go to: " // httpsDefaultPort and plainHTTPPort are the ports whose URLs need no // explicit port suffix. httpsDefaultPort = 443 plainHTTPPort = 80 ) type serverState struct { running bool hostname string ip4 string ip6 string certDomain string url string httpURL string loginURL string lastError string logLines []string } var ( mu sync.Mutex curSrv *tsnet.Server curHTTP *http.Server // curCancel cancels the current Start attempt's connect context; Stop // and fail() call it so a goroutine blocked waiting for login unblocks // instead of leaking. curCancel context.CancelFunc st serverState // gen counts Start attempts; goroutines from a superseded Start exit // instead of racing a newer one. gen uint64 ) // Start joins the tailnet as `hostname` and serves the webapp over HTTPS, // plus the same handler over plain HTTP on port 80. // // It blocks until the TLS listener is ready — including provisioning the // Let's Encrypt certificate — or fails with a clear error. With an empty // authKey, tsnet logs an interactive login URL which Status() exposes; Start // keeps waiting until the login is completed and the listener comes up, so // callers must be able to wait (Kotlin calls this on a background thread). // // authKey may also be a Tailscale OAuth client secret (starts with // "tskey-client-"); tsnet then mints an auth key via the OAuth2 client // credentials flow. That requires non-empty tags (comma-separated tailnet // tags, e.g. "tag:server"), since the minted key applies them. The secret's // query attributes (?ephemeral=BOOL&preauthorized=BOOL) control the minted // key; see tailscale's feature/oauthkey package. // // stateDir holds tsnet's persistent node state (pass the app's filesDir); // cacheDir is used as TMPDIR (Android has no /tmp). intifaceTarget is the // ws:// or wss:// URL of Intiface Central's WebSocket server (empty selects // ws://localhost:12345). servePort is the HTTPS port; use 443 (userspace // netstack needs no privileges). webappDir is the directory whose files are // served as the webapp (must contain index.html; see validateWebappDir). // Plain HTTP is served on port 80 alongside HTTPS, so http:/// works // as well — the webapp picks ws:// or wss:// from the page's own scheme. func Start(stateDir, cacheDir, hostname, authKey, tags string, servePort int32, intifaceTarget, webappDir string) error { if strings.TrimSpace(hostname) == "" { return errors.New("hostname must not be empty") } if stateDir == "" { return errors.New("stateDir must not be empty") } if strings.HasPrefix(authKey, "tskey-client-") && strings.TrimSpace(tags) == "" { return errors.New("OAuth client secrets (tskey-client-...) require tags (e.g. tag:server) so the minted auth key can apply them") } if err := os.MkdirAll(stateDir, 0o700); err != nil { return fmt.Errorf("create state dir: %w", err) } if cacheDir != "" { if err := os.MkdirAll(cacheDir, 0o700); err != nil { return fmt.Errorf("create cache dir: %w", err) } // Android has no /tmp and no TMPDIR; tsnet and its dependencies // need a writable temp directory. os.Setenv("TMPDIR", cacheDir) } var advertised []string for _, t := range strings.Split(tags, ",") { if t = strings.TrimSpace(t); t != "" { advertised = append(advertised, t) } } mu.Lock() if curSrv != nil { mu.Unlock() return errors.New("tsbridge already running; stop it first") } target, err := parseIntifaceTarget(intifaceTarget) if err != nil { mu.Unlock() return err } if err := validateWebappDir(webappDir); err != nil { mu.Unlock() return err } gen++ myGen := gen st = serverState{hostname: hostname} capture := &logCapture{gen: myGen} s := &tsnet.Server{ Dir: stateDir, Hostname: hostname, AuthKey: authKey, AdvertiseTags: advertised, Logf: capture.Logf, UserLogf: capture.Logf, } curSrv = s srvCtx, cancel := context.WithCancel(context.Background()) curCancel = cancel mu.Unlock() go func() { if err := s.Start(); err != nil { fail(myGen, "tsnet start: %v", err) return } // Wait for the tailnet connection with our own context so Stop() // can unblock the interactive-login wait. When Running, the second // (context.Background) Up inside ListenTLS returns immediately. if _, err := s.Up(srvCtx); err != nil { fail(myGen, "tsnet connect: %v", err) return } // Provision the ts.net TLS certificate. tsnet's own ListenTLS path // cannot fetch certs on Android (upstream stubs the localapi cert // endpoint there; tailscale#18245), so we run the ACME dns-01 order // ourselves via the documented SetDNS escape hatch — see certs.go. // This blocks until the cert is cached on disk, so "running" in the // status always means handshakes can succeed. domains := s.CertDomains() if len(domains) == 0 { fail(myGen, "no certificate domains: HTTPS must be enabled in the tailnet admin console (MagicDNS + HTTPS)") return } lc, err := s.LocalClient() if err != nil { fail(myGen, "local client: %v", err) return } certMgr, err := newCertManager(lc, domains[0], stateDir) if err != nil { fail(myGen, "cert manager: %v", err) return } if err := retryBackoff(srvCtx, 3, 8*time.Second, func() error { if err := certMgr.ensure(srvCtx); err != nil { appendLog("certificate provisioning attempt failed: %v", err) return err } return nil }); err != nil { fail(myGen, "certificate provisioning for %s failed: %v", domains[0], err) return } go certMgr.runRenewals(srvCtx, capture.Logf) ln, err := s.Listen("tcp", fmt.Sprintf(":%d", servePort)) if err != nil { fail(myGen, "tsnet listen: %v", err) return } // Also serve the same handler over plain HTTP, so the webapp and its // WebSocket proxy are reachable at http:/// without the // certificate handshake. Plain HTTP is an extra rather than a // requirement: if it cannot be set up, HTTPS keeps serving. var plainLn net.Listener if servePort == plainHTTPPort { appendLog("plain HTTP not served separately: HTTPS is already on :%d", plainHTTPPort) } else if ln80, err := s.Listen("tcp", fmt.Sprintf(":%d", plainHTTPPort)); err != nil { appendLog("plain HTTP listener unavailable on :%d: %v", plainHTTPPort, err) } else { plainLn = ln80 } mu.Lock() if myGen != gen { mu.Unlock() ln.Close() if plainLn != nil { plainLn.Close() } return } domain := domains[0] httpSrv := &http.Server{ Handler: newHandler(nil, target, webappDir), // Surface TLS handshake failures (bad cert, wrong SNI, …) in // the in-app status log instead of only logcat. ErrorLog: log.New(&captureWriter{capture}, "", 0), } curHTTP = httpSrv ip4, ip6 := s.TailscaleIPs() st.running = true st.certDomain = domain st.url = publicURL("https", domain, int(servePort)) if plainLn != nil { st.httpURL = publicURL("http", domain, plainHTTPPort) } st.ip4 = ipAddrString(ip4) st.ip6 = ipAddrString(ip6) st.loginURL = "" st.lastError = "" mu.Unlock() if plainLn != nil { appendLog("serving %s on :%d (HTTPS) and :%d (HTTP)", domain, servePort, plainHTTPPort) } else { appendLog("serving %s on :%d (HTTPS only)", domain, servePort) } if plainLn != nil { go servePlainHTTP(myGen, httpSrv, plainLn) } if err := httpSrv.Serve(tls.NewListener(ln, certMgr.TLSConfig())); err != nil && err != http.ErrServerClosed { fail(myGen, "http serve: %v", err) } }() return nil } // servePlainHTTP serves the shared handler on the plain-HTTP listener until // the server or the listener closes. It runs alongside the HTTPS Serve call on // the same http.Server, which Close (from Stop) tears down together. A failure // here leaves HTTPS serving, so it is logged instead of being fatal. func servePlainHTTP(myGen uint64, srv *http.Server, ln net.Listener) { err := srv.Serve(ln) switch { case err == nil, errors.Is(err, http.ErrServerClosed), errors.Is(err, net.ErrClosed): return } mu.Lock() current := myGen == gen mu.Unlock() if current { appendLog("plain HTTP serve: %v", err) } } // publicURL renders the address a browser should open for domain on port, // omitting the port when it is the scheme's default. func publicURL(scheme, domain string, port int) string { if (scheme == "https" && port == httpsDefaultPort) || (scheme == "http" && port == plainHTTPPort) { return scheme + "://" + domain } return fmt.Sprintf("%s://%s:%d", scheme, domain, port) } // Stop shuts the server down. Idempotent. func Stop() error { mu.Lock() s := curSrv hs := curHTTP cancel := curCancel curSrv = nil curHTTP = nil curCancel = nil gen++ mu.Unlock() if cancel != nil { cancel() } if s == nil { return nil } if hs != nil { hs.Close() } if err := s.Close(); err != nil { mu.Lock() st.lastError = fmt.Sprintf("tsnet close: %v", err) st.running = false mu.Unlock() return err } mu.Lock() st.running = false mu.Unlock() return nil } // Status returns server state as a JSON string: // {running, hostname, ip4, ip6, certDomain, url, httpURL, loginURL, lastError, // lastLogLines}. url is the https:// address; httpURL is the plain-HTTP one // (empty when it is not being served). // Callers poll this (Kotlin every 1-2 s) rather than holding server objects. func Status() string { mu.Lock() defer mu.Unlock() lines := st.logLines if len(lines) > 20 { lines = lines[len(lines)-20:] } b, err := json.Marshal(struct { Running bool `json:"running"` Hostname string `json:"hostname"` IP4 string `json:"ip4"` IP6 string `json:"ip6"` CertDomain string `json:"certDomain"` URL string `json:"url"` HTTPURL string `json:"httpURL"` LoginURL string `json:"loginURL"` LastError string `json:"lastError"` LastLogLines []string `json:"lastLogLines"` }{ Running: st.running, Hostname: st.hostname, IP4: st.ip4, IP6: st.ip6, CertDomain: st.certDomain, URL: st.url, HTTPURL: st.httpURL, LoginURL: st.loginURL, LastError: st.lastError, LastLogLines: lines, }) if err != nil { return `{"running":false,"lastError":"status marshal failed"}` } return string(b) } // logCapture forwards tsnet log lines into the status ring buffer and // extracts the interactive login URL from tsnet's auth loop lines // ("To start this tsnet server, restart with TS_AUTHKEY set, or go to: "). type logCapture struct { gen uint64 } func (c *logCapture) Logf(format string, args ...any) { line := fmt.Sprintf(format, args...) if idx := strings.Index(line, authURLMarker); idx >= 0 { if u := strings.TrimSpace(line[idx+len(authURLMarker):]); strings.HasPrefix(u, "http") { mu.Lock() if c.gen == gen { st.loginURL = u } mu.Unlock() } } appendLog("%s", line) } // appendLog appends a line to the status ring buffer. func appendLog(format string, args ...any) { mu.Lock() defer mu.Unlock() st.logLines = append(st.logLines, fmt.Sprintf("%s %s", time.Now().UTC().Format("15:04:05"), fmt.Sprintf(format, args...))) if len(st.logLines) > maxLogLines { st.logLines = st.logLines[len(st.logLines)-maxLogLines:] } } // captureWriter adapts the status log ring buffer to the io.Writer that // http.Server's ErrorLog expects. type captureWriter struct { c *logCapture } func (w *captureWriter) Write(p []byte) (int, error) { appendLog("%s", strings.TrimSpace(string(p))) return len(p), nil } // fail records a fatal error for a Start attempt and releases the singleton // so the user can retry Start (e.g. after enabling MagicDNS+HTTPS or fixing // the auth key). Superseded attempts leave state alone. func fail(myGen uint64, format string, args ...any) { msg := fmt.Sprintf(format, args...) mu.Lock() if myGen == gen { st.lastError = msg st.running = false } s := curSrv cancel := curCancel curSrv = nil curHTTP = nil curCancel = nil mu.Unlock() if cancel != nil { cancel() } if s != nil { s.Close() } appendLog("error: %s", msg) } func ipAddrString(a netip.Addr) string { if !a.IsValid() { return "" } return a.String() }