Skip to content

Commit

Permalink
Use cached discovered records on temporary discovery failure
Browse files Browse the repository at this point in the history
When client run in endpoint discovery mode (-discover flag), it caches
SRV records lookup result on success; if in next time when client starts
with the same discover argument it temporarily fails to get SRV records
(i.e. network is down), it will use previously cached results instead of
failing.

This makes case or running client as a service on a laptop that change
networks often or may be offline more reliable.
  • Loading branch information
artyom committed Jul 2, 2019
1 parent e1a0653 commit 1a173ee
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
2 changes: 2 additions & 0 deletions go.mod
Expand Up @@ -10,3 +10,5 @@ require (
)

replace github.com/armon/go-socks5 => github.com/artyom/go-socks5 v0.0.0-20171215124554-5ab49e6379c2

go 1.13
36 changes: 36 additions & 0 deletions main.go
Expand Up @@ -72,6 +72,7 @@ package main

import (
"context"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"errors"
Expand All @@ -84,6 +85,7 @@ import (
"net"
"net/http"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
Expand Down Expand Up @@ -159,6 +161,13 @@ func runClient(args clientArgs, servers []string) error {
return r.LookupSRV(ctx, service, proto, name)
}
cname, recs, err := lookup("tlstun", "tcp", args.Discover)
if te, ok := err.(interface{ Temporary() bool }); ok && te.Temporary() {
if cached := loadDiscoverCache(args.Discover); len(cached) > 0 {
log.Printf("using cached server list, temporary discover failure: %v", err)
servers = cached
goto hasServers
}
}
if err != nil {
return err
}
Expand All @@ -170,7 +179,9 @@ func runClient(args clientArgs, servers []string) error {
servers = append(servers, net.JoinHostPort(rec.Target,
strconv.FormatUint(uint64(rec.Port), 10)))
}
saveDiscoverCache(args.Discover, servers)
}
hasServers:
for _, addr := range servers {
host, port, err := net.SplitHostPort(addr)
if err != nil {
Expand Down Expand Up @@ -639,6 +650,31 @@ func (sr socksResolver) Resolve(ctx context.Context, name string) (context.Conte
return ctx, ips[0].IP, nil
}

func loadDiscoverCache(name string) []string {
dir, err := os.UserCacheDir()
if err != nil {
return nil
}
file := filepath.Join(dir, "tlstun",
fmt.Sprintf("%x", sha256.Sum256([]byte(name))))
b, err := ioutil.ReadFile(file)
if err != nil {
return nil
}
return strings.Split(string(b), "\n")
}

func saveDiscoverCache(name string, vals []string) {
dir, err := os.UserCacheDir()
if err != nil {
return
}
file := filepath.Join(dir, "tlstun",
fmt.Sprintf("%x", sha256.Sum256([]byte(name))))
_ = os.MkdirAll(filepath.Dir(file), 0700)
_ = ioutil.WriteFile(file, []byte(strings.Join(vals, "\n")), 0600)
}

func usageMain(serverFlags, clientFlags *flag.FlagSet) {
fmt.Fprint(os.Stderr, usageHead)
fmt.Fprint(os.Stderr, "\nTo run client:\n\n")
Expand Down

0 comments on commit 1a173ee

Please sign in to comment.