diff --git a/internal/proxy/httpform.go b/internal/proxy/httpform.go index 4b6132c..f752cbb 100644 --- a/internal/proxy/httpform.go +++ b/internal/proxy/httpform.go @@ -70,3 +70,38 @@ func originForm(data []byte) (hostPort string, out []byte, err error) { out = append([]byte(b.String()), body...) return host, out, nil } + +// closeAfterResponse asks the target to close the connection after its +// response. A tunnel through a SOCKS5 proxy or the hosted gateway reaches one +// target, but a client may reuse its connection to the local proxy for a +// plain HTTP request to another host. Once the target closes, the client +// opens a new connection, and so a new tunnel, for its next request. An +// upgrade request (a WebSocket, for example) is left as it is: the upgraded +// connection stays with one target. +func closeAfterResponse(req []byte) []byte { + headEnd := bytes.Index(req, []byte("\r\n\r\n")) + if headEnd == -1 { + return req + } + lines := strings.Split(string(req[:headEnd]), "\r\n") + + var b strings.Builder + b.WriteString(lines[0] + "\r\n") + for _, l := range lines[1:] { + name, value, _ := strings.Cut(l, ":") + switch strings.ToLower(strings.TrimSpace(name)) { + case "connection": + for _, token := range strings.Split(value, ",") { + if strings.EqualFold(strings.TrimSpace(token), "upgrade") { + return req + } + } + continue + case "keep-alive": + continue + } + b.WriteString(l + "\r\n") + } + b.WriteString("Connection: close\r\n\r\n") + return append([]byte(b.String()), req[headEnd+4:]...) +} diff --git a/internal/proxy/plain_http_test.go b/internal/proxy/plain_http_test.go new file mode 100644 index 0000000..5e0629d --- /dev/null +++ b/internal/proxy/plain_http_test.go @@ -0,0 +1,295 @@ +package proxy + +import ( + "bufio" + "encoding/base64" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "sync" + "testing" + + "github.com/shellroute/shellroute-cli/internal/meter" + "github.com/shellroute/shellroute-cli/internal/proxy/proxytest" +) + +// tunnelRequest is a request the fake gateway received inside a tunnel. +type tunnelRequest struct { + tunnel string // CONNECT target of the tunnel it arrived on + requestURI string + host string + close bool + proxyAuth string +} + +// connectOnlyGateway imitates the hosted gateway: every method except CONNECT +// gets 405. Inside a tunnel it plays the target web server. It answers each +// request with the tunnel's CONNECT target and, like a keep-alive server, +// keeps the connection open unless the request asked to close it. +type connectOnlyGateway struct { + addr string + + mu sync.Mutex + connects []string // CONNECT targets, in order + auths []string // Proxy-Authorization of each CONNECT + requests []tunnelRequest + refused int // non-CONNECT requests answered with 405 +} + +func startConnectOnlyGateway(t *testing.T) *connectOnlyGateway { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + g := &connectOnlyGateway{addr: ln.Addr().String()} + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + go g.handle(c) + } + }() + return g +} + +func (g *connectOnlyGateway) handle(c net.Conn) { + defer c.Close() + br := bufio.NewReader(c) + req, err := http.ReadRequest(br) + if err != nil { + return + } + if req.Method != http.MethodConnect { + g.mu.Lock() + g.refused++ + g.mu.Unlock() + io.WriteString(c, "HTTP/1.1 405 Method Not Allowed\r\nContent-Length: 0\r\n\r\n") + return + } + g.mu.Lock() + g.connects = append(g.connects, req.Host) + g.auths = append(g.auths, req.Header.Get("Proxy-Authorization")) + g.mu.Unlock() + io.WriteString(c, "HTTP/1.1 200 Connection established\r\n\r\n") + + for { + in, err := http.ReadRequest(br) + if err != nil { + return + } + io.Copy(io.Discard, in.Body) + g.mu.Lock() + g.requests = append(g.requests, tunnelRequest{ + tunnel: req.Host, + requestURI: in.RequestURI, + host: in.Host, + close: in.Close, + proxyAuth: in.Header.Get("Proxy-Authorization"), + }) + g.mu.Unlock() + + resp := fmt.Sprintf("HTTP/1.1 200 OK\r\nContent-Length: %d\r\n", len(req.Host)) + if in.Close { + resp += "Connection: close\r\n" + } + io.WriteString(c, resp+"\r\n"+req.Host) + if in.Close { + return + } + } +} + +func startHostedServer(t *testing.T, gwAddr string) (*Server, string) { + t.Helper() + s := NewServer(&Config{ + ListenPort: freePort(t), + Upstream: NewHostedUpstream(gwAddr, false, "test-token"), + Meter: meter.New(), + }) + return s, startServer(t, s) +} + +func getBody(t *testing.T, client *http.Client, url string) (int, string) { + t.Helper() + resp, err := client.Get(url) + if err != nil { + t.Fatalf("GET %s through local proxy: %v", url, err) + } + defer resp.Body.Close() + body, _ := io.ReadAll(resp.Body) + return resp.StatusCode, string(body) +} + +// The hosted gateway accepts only CONNECT. A plain HTTP request must reach +// it as a tunnel to port 80 carrying the request in origin form. +func TestServer_HostedPlainHTTPGoesThroughConnect(t *testing.T) { + g := startConnectOnlyGateway(t) + s, addr := startHostedServer(t, g.addr) + + status, body := getBody(t, viaLocalProxy(t, addr, nil), "http://example.test/path?q=1") + if status != http.StatusOK || body != "example.test:80" { + t.Fatalf("got %d %q, want 200 from a tunnel to example.test:80", status, body) + } + + g.mu.Lock() + defer g.mu.Unlock() + if g.refused != 0 { + t.Errorf("gateway refused %d requests that were not CONNECT", g.refused) + } + wantAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte("_:test-token")) + if len(g.connects) != 1 || g.connects[0] != "example.test:80" || g.auths[0] != wantAuth { + t.Errorf("CONNECTs %v with auth %v, want one to example.test:80 with the session token", g.connects, g.auths) + } + if len(g.requests) != 1 { + t.Fatalf("requests inside tunnels = %d, want 1", len(g.requests)) + } + r := g.requests[0] + if r.requestURI != "/path?q=1" || r.host != "example.test" { + t.Errorf("target saw %q with Host %q, want origin form /path?q=1 with Host example.test", r.requestURI, r.host) + } + if !r.close { + t.Error("request did not ask the target to close after its response") + } + if r.proxyAuth != "" { + t.Error("proxy credentials reached the target") + } + if s.BytesTotal() == 0 { + t.Error("relay metered no bytes") + } +} + +// A client may reuse its connection to the local proxy for a plain HTTP +// request to another host. Each request must still reach its own host. +func TestServer_HostedPlainHTTPToTwoHostsUsesTwoTunnels(t *testing.T) { + g := startConnectOnlyGateway(t) + _, addr := startHostedServer(t, g.addr) + client := viaLocalProxy(t, addr, nil) + + for _, host := range []string{"a.test", "b.test"} { + if _, body := getBody(t, client, "http://"+host+"/"); body != host+":80" { + t.Errorf("request for %s was answered through the tunnel to %q", host, body) + } + } + g.mu.Lock() + defer g.mu.Unlock() + if len(g.connects) != 2 { + t.Errorf("CONNECTs = %v, want one per host", g.connects) + } +} + +// A user's own SOCKS5 proxy also tunnels, so the same holds there. +func TestServer_SOCKS5PlainHTTPToTwoHostsUsesTwoTunnels(t *testing.T) { + var urls []string + for _, name := range []string{"a", "b"} { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, name) + })) + t.Cleanup(srv.Close) + urls = append(urls, srv.URL) + } + sp := proxytest.StartSOCKS5(t, "", "") + s := NewServer(&Config{ + ListenPort: freePort(t), + Upstream: NewSOCKS5Upstream(sp.Addr, "", "", "socks5"), + Meter: meter.New(), + FailureThreshold: OwnFailureThreshold, + }) + addr := startServer(t, s) + client := viaLocalProxy(t, addr, nil) + + for i, want := range []string{"a", "b"} { + if _, body := getBody(t, client, urls[i]+"/"); body != want { + t.Errorf("request for server %s was answered by server %q", want, body) + } + } + if n := sp.Connects.Load(); n != 2 { + t.Errorf("SOCKS5 connects = %d, want one per request", n) + } +} + +// A user's own HTTP proxy still gets a plain HTTP request as it is: in +// absolute form, with its credentials, and with the client's connection +// handling. +func TestServer_OwnHTTPProxyStillGetsAbsoluteForm(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + got := make(chan *http.Request, 1) + go func() { + c, err := ln.Accept() + if err != nil { + return + } + defer c.Close() + req, err := http.ReadRequest(bufio.NewReader(c)) + if err != nil { + return + } + got <- req + io.WriteString(c, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") + }() + + s := NewServer(&Config{ + ListenPort: freePort(t), + Upstream: NewHTTPUpstream(ln.Addr().String(), false, "u", "p", "own"), + Meter: meter.New(), + FailureThreshold: OwnFailureThreshold, + }) + addr := startServer(t, s) + + if status, body := getBody(t, viaLocalProxy(t, addr, nil), "http://example.test/x"); status != http.StatusOK || body != "ok" { + t.Fatalf("got %d %q, want 200 ok", status, body) + } + req := <-got + if req.Method != http.MethodGet || req.RequestURI != "http://example.test/x" { + t.Errorf("own proxy got %s %s, want GET http://example.test/x", req.Method, req.RequestURI) + } + if want := "Basic " + base64.StdEncoding.EncodeToString([]byte("u:p")); req.Header.Get("Proxy-Authorization") != want { + t.Errorf("own proxy got Proxy-Authorization %q, want %q", req.Header.Get("Proxy-Authorization"), want) + } + if req.Close { + t.Error("request to the own proxy was changed to close the connection") + } +} + +func TestCloseAfterResponse(t *testing.T) { + cases := []struct { + name, in, want string + }{ + { + "adds the header", + "GET / HTTP/1.1\r\nHost: a\r\n\r\n", + "GET / HTTP/1.1\r\nHost: a\r\nConnection: close\r\n\r\n", + }, + { + "replaces keep-alive and keeps the body", + "POST / HTTP/1.1\r\nHost: a\r\nConnection: keep-alive\r\nKeep-Alive: timeout=5\r\nContent-Length: 2\r\n\r\nhi", + "POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 2\r\nConnection: close\r\n\r\nhi", + }, + { + "leaves an upgrade request alone", + "GET /ws HTTP/1.1\r\nHost: a\r\nConnection: keep-alive, Upgrade\r\nUpgrade: websocket\r\n\r\n", + "GET /ws HTTP/1.1\r\nHost: a\r\nConnection: keep-alive, Upgrade\r\nUpgrade: websocket\r\n\r\n", + }, + { + "leaves an incomplete head alone", + "GET / HTTP/1.1\r\nHost: a", + "GET / HTTP/1.1\r\nHost: a", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := string(closeAfterResponse([]byte(tc.in))); got != tc.want { + t.Errorf("got %q\nwant %q", got, tc.want) + } + }) + } +} diff --git a/internal/proxy/server.go b/internal/proxy/server.go index 5a96b6d..442843e 100644 --- a/internal/proxy/server.go +++ b/internal/proxy/server.go @@ -433,7 +433,7 @@ func (s *Server) handleHTTP(ctx context.Context, clientConn net.Conn, initialDat var upstreamConn net.Conn var req []byte - if hp, ok := up.(HTTPProxyUpstream); ok { + if hp, ok := up.(HTTPProxyUpstream); ok && hp.ForwardsPlainHTTP() { conn, err := hp.DialProxy(ctx) if err != nil { s.handleDialError(clientConn, err) @@ -449,11 +449,15 @@ func (s *Server) handleHTTP(ctx context.Context, clientConn net.Conn, initialDat req = []byte(text) } } else { + // SOCKS5, or the hosted gateway, which accepts only CONNECT: open a + // tunnel to the target and send the request in origin form, one + // request per tunnel. target, origin, err := originForm(initialData) if err != nil { clientConn.Write([]byte("HTTP/1.1 400 Bad Request\r\n\r\n")) return } + origin = closeAfterResponse(origin) conn, err := up.DialTarget(ctx, target) if err != nil { s.handleDialError(clientConn, err) diff --git a/internal/proxy/upstream.go b/internal/proxy/upstream.go index eabb1d2..39b74de 100644 --- a/internal/proxy/upstream.go +++ b/internal/proxy/upstream.go @@ -24,7 +24,7 @@ type Upstream interface { } // HTTPProxyUpstream is implemented by upstreams that are HTTP proxies -// themselves and can take a plain HTTP request in absolute form directly. +// themselves. type HTTPProxyUpstream interface { Upstream // DialProxy opens a raw connection to the proxy itself. @@ -32,6 +32,10 @@ type HTTPProxyUpstream interface { // ProxyAuthorization returns the Proxy-Authorization header value, or "" // when the proxy takes no credentials. ProxyAuthorization() string + // ForwardsPlainHTTP reports whether the proxy takes a plain HTTP request + // in absolute form directly. The hosted gateway accepts only CONNECT, so + // a plain HTTP request goes through a tunnel to its target instead. + ForwardsPlainHTTP() bool } // OwnFailureThreshold is how many consecutive upstream failures mark a diff --git a/internal/proxy/upstream_http.go b/internal/proxy/upstream_http.go index 7bfb522..b30ddc6 100644 --- a/internal/proxy/upstream_http.go +++ b/internal/proxy/upstream_http.go @@ -60,6 +60,10 @@ func (u *HTTPUpstream) ProxyAuthorization() string { return "Basic " + u.auth } +// ForwardsPlainHTTP is true for a user's own HTTP or HTTPS proxy and false +// for the hosted gateway, which accepts only CONNECT. +func (u *HTTPUpstream) ForwardsPlainHTTP() bool { return !u.hosted } + func (u *HTTPUpstream) setExitIPCallback(f func(string)) { u.onExitIP = f } // setTLSConfig overrides TLS verification; used by tests with a private CA. diff --git a/internal/session/keepalive.go b/internal/session/keepalive.go new file mode 100644 index 0000000..6e9da48 --- /dev/null +++ b/internal/session/keepalive.go @@ -0,0 +1,33 @@ +package session + +import ( + "context" + "time" + + "github.com/shellroute/shellroute-cli/internal/api" +) + +// keepAliveInterval is how often a hosted session started by `shellroute +// proxy` or `shellroute run` tells the service it is still in use. The +// service ends a hosted session that goes a few minutes without this signal, +// whether or not traffic flows. The interactive shell sends the same signal +// from its balance monitor. +var keepAliveInterval = 60 * time.Second + +// keepAlive sends the session's keep-alive every interval until ctx ends. +// A failed call is not retried early; the next tick sends another. +func keepAlive(ctx context.Context, client *api.Client, sessionID, ipType string, interval time.Duration) { + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + if ctx.Err() != nil { + return + } + _, _ = client.GetBalance(api.BalanceOpts{IPType: ipType, SessionID: sessionID}) + } + } +} diff --git a/internal/session/keepalive_test.go b/internal/session/keepalive_test.go new file mode 100644 index 0000000..5dc01b2 --- /dev/null +++ b/internal/session/keepalive_test.go @@ -0,0 +1,202 @@ +package session + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "sync" + "testing" + "time" + + "github.com/shellroute/shellroute-cli/internal/api" +) + +// serviceWindow stands in for the few minutes after which the service ends a +// hosted session that sends no keep-alive, scaled down with the keep-alive +// interval so the tests run in about a second. +const serviceWindow = 250 * time.Millisecond + +type keepAliveCall struct { + at time.Time + sessionID string + ipType string +} + +// fakeService answers the API calls a hosted session makes and records each +// keep-alive. +type fakeService struct { + mu sync.Mutex + created time.Time + calls []keepAliveCall + ended bool +} + +func startFakeService(t *testing.T) (*fakeService, *api.Client) { + t.Helper() + f := &fakeService{} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + defer f.mu.Unlock() + switch { + case r.Method == http.MethodPost && r.URL.Path == "/v1/sessions/create": + f.created = time.Now() + w.WriteHeader(http.StatusCreated) + io.WriteString(w, `{"session_id":"sess-1","gateway":{"endpoint":"127.0.0.1:1","token":"tok"},"exit_ip":"203.0.113.7","country":"US","type":"residential","byte_budget":1000000}`) + case r.Method == http.MethodGet && r.URL.Path == "/v1/account/balance": + if id := r.URL.Query().Get("session_id"); id != "" { + f.calls = append(f.calls, keepAliveCall{at: time.Now(), sessionID: id, ipType: r.URL.Query().Get("type")}) + } + io.WriteString(w, `{"balance_usd":5}`) + case r.Method == http.MethodDelete && r.URL.Path == "/v1/sessions/sess-1": + f.ended = true + io.WriteString(w, `{"session_id":"sess-1"}`) + case r.Method == http.MethodPost && r.URL.Path == "/v1/sessions/connect-report": + w.WriteHeader(http.StatusNoContent) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(srv.Close) + return f, api.New(srv.URL, "pk_test") +} + +func (f *fakeService) keepAlives() []keepAliveCall { + f.mu.Lock() + defer f.mu.Unlock() + return append([]keepAliveCall(nil), f.calls...) +} + +func (f *fakeService) sessionEnded() bool { + f.mu.Lock() + defer f.mu.Unlock() + return f.ended +} + +// longestSilence is the longest stretch, from session creation until now, +// in which the service heard no keep-alive. +func (f *fakeService) longestSilence(now time.Time) time.Duration { + f.mu.Lock() + defer f.mu.Unlock() + calls := append(append([]keepAliveCall(nil), f.calls...), keepAliveCall{at: now}) + last, longest := f.created, time.Duration(0) + for _, c := range calls { + if gap := c.at.Sub(last); gap > longest { + longest = gap + } + last = c.at + } + return longest +} + +func setKeepAliveInterval(t *testing.T, d time.Duration) { + t.Helper() + old := keepAliveInterval + keepAliveInterval = d + t.Cleanup(func() { keepAliveInterval = old }) +} + +func waitFor(t *testing.T, cond func() bool) { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + for !cond() { + if time.Now().After(deadline) { + t.Fatal("condition not reached within 2s") + } + time.Sleep(5 * time.Millisecond) + } +} + +func startHosted(t *testing.T, client *api.Client, mode string) *Session { + t.Helper() + t.Setenv("SHELLROUTE_HOME", t.TempDir()) + sess, err := Start(context.Background(), client, &api.SessionCreateRequest{Country: "US", Type: "residential"}, 0, StartOpts{Mode: mode}) + if err != nil { + t.Fatalf("Start: %v", err) + } + return sess +} + +// A hosted session from `shellroute proxy` or `shellroute run` must outlive +// the service window: it sends its own keep-alive for as long as it runs, +// and stops when the session ends. +func TestStart_ProxyAndRunModesKeepSessionAlive(t *testing.T) { + setKeepAliveInterval(t, 10*time.Millisecond) + for _, mode := range []string{"proxy", "run"} { + t.Run(mode, func(t *testing.T) { + svc, client := startFakeService(t) + sess := startHosted(t, client, mode) + + time.Sleep(4 * serviceWindow) + if gap := svc.longestSilence(time.Now()); gap >= serviceWindow { + t.Errorf("longest stretch without a keep-alive = %v, want under %v", gap, serviceWindow) + } + for _, c := range svc.keepAlives() { + if c.sessionID != "sess-1" || c.ipType != "residential" { + t.Fatalf("keep-alive for session %q type %q, want sess-1 residential", c.sessionID, c.ipType) + } + } + + if _, err := sess.Stop(); err != nil { + t.Fatalf("Stop: %v", err) + } + if !svc.sessionEnded() { + t.Error("Stop did not end the session") + } + time.Sleep(3 * keepAliveInterval) // let a call sent before Stop arrive + after := len(svc.keepAlives()) + time.Sleep(10 * keepAliveInterval) + if n := len(svc.keepAlives()); n != after { + t.Errorf("%d keep-alives sent after Stop", n-after) + } + }) + } +} + +// The interactive shell's controller sends the keep-alive from its balance +// monitor; its sessions must not send a second one. +func TestStart_InteractiveSessionLeavesKeepAliveToController(t *testing.T) { + setKeepAliveInterval(t, 10*time.Millisecond) + svc, client := startFakeService(t) + sess := startHosted(t, client, "") + defer sess.Stop() + + time.Sleep(10 * keepAliveInterval) + if n := len(svc.keepAlives()); n != 0 { + t.Errorf("interactive session sent %d keep-alives itself", n) + } +} + +func TestKeepAlive_StopsWhenContextEnds(t *testing.T) { + svc, client := startFakeService(t) + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + keepAlive(ctx, client, "sess-1", "datacenter", 5*time.Millisecond) + close(done) + }() + + waitFor(t, func() bool { return len(svc.keepAlives()) >= 2 }) + cancel() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("keepAlive still running 1s after its context ended") + } + after := len(svc.keepAlives()) + time.Sleep(50 * time.Millisecond) + if n := len(svc.keepAlives()); n != after { + t.Errorf("%d keep-alives sent after the context ended", n-after) + } + if c := svc.keepAlives()[0]; c.ipType != "datacenter" { + t.Errorf("keep-alive type = %q, want datacenter", c.ipType) + } +} + +// The service ends a session after a few minutes without a keep-alive; one +// minute leaves room for missed calls. +func TestKeepAliveInterval_LeavesRoomForMissedCalls(t *testing.T) { + if keepAliveInterval > time.Minute { + t.Errorf("keepAliveInterval = %v, want at most 1m", keepAliveInterval) + } +} diff --git a/internal/session/session.go b/internal/session/session.go index a9147da..c4959b5 100644 --- a/internal/session/session.go +++ b/internal/session/session.go @@ -89,7 +89,7 @@ type Info struct { type StartOpts struct { TrackRelays bool // true for run mode — enables force-close of active relay conns ConnectTimeout time.Duration // override exit IP detection timeout (default 45s) - Mode string // "proxy", "run", or "" (interactive) + Mode string // "proxy", "run", or "" (interactive); hosted proxy and run sessions send their own keep-alive SkipExitIP bool // own routes: do not probe the exit IP } @@ -183,6 +183,13 @@ func startWithResponse(ctx context.Context, client *api.Client, resp *api.Sessio } }() + // The interactive shell keeps its session alive from the controller's + // balance monitor. proxy and run mode have no controller, so the session + // sends the keep-alive itself until Stop. + if opts.Mode != "" { + go keepAlive(ctx, client, s.ID, s.Type, keepAliveInterval) + } + // Wait for the tunnel to be ready. // If the API already returned an exit IP (gateway had a pool entry), skip // the slow detectExitIPRetry — the tunnel is proven healthy. diff --git a/scripts/test-upstreams.sh b/scripts/test-upstreams.sh index b271f75..a3c4bfc 100755 --- a/scripts/test-upstreams.sh +++ b/scripts/test-upstreams.sh @@ -95,13 +95,25 @@ fi # A second marker runs on the host for the NO_PROXY check: reached directly it # sees the host's own address; reached through a proxy container it does not. HOST_MARK_PORT=$(free_port) -python3 scripts/upstreams/marker.py "$HOST_MARK_PORT" & PIDS+=($!) +python3 scripts/upstreams/marker.py "$HOST_MARK_PORT" 2>"$TMP/host-marker.log" & PIDS+=($!) LAN_IP=$(python3 -c 'import socket s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.connect(("10.255.255.255", 1)); print(s.getsockname()[0]) except Exception: print("")') case "$LAN_IP" in 127.*|"") LAN_IP="";; esac +# C-06 needs the host marker to answer on the LAN address. On macOS the +# firewall can block incoming connections for a python3 build, which breaks +# the direct request with no proxy or shellroute involved: skip C-06 there and +# say why. CI has no such firewall, so the check stays strict there. +if [ -n "$LAN_IP" ] && [ -z "${GITHUB_ACTIONS:-}" ]; then + wait_port "$HOST_MARK_PORT" || true + direct=$(curl -s --noproxy '*' --max-time 5 "http://$LAN_IP:$HOST_MARK_PORT/direct" | json_field source) + if [ "$direct" != "$LAN_IP" ]; then + C06_SKIP="the host marker does not answer on the LAN address even directly; the firewall likely blocks incoming connections for $(command -v python3)" + LAN_IP="" + fi +fi # --- proxies --- say "== start proxies ==" @@ -273,7 +285,7 @@ run_checks() { } say "== checks ==" -[ -n "$LAN_IP" ] || say " no LAN address found: C-06 is skipped" +[ -n "$LAN_IP" ] || say " C-06 is skipped: ${C06_SKIP:-no LAN address found}" run_checks "3proxy http+auth" "http://alice:s3cret@127.0.0.1:$P3_HTTP" sr-3proxy run_checks "3proxy socks5+auth" "socks5://alice:s3cret@127.0.0.1:$P3_SOCKS" sr-3proxy run_checks "3proxy socks5 open" "socks5://127.0.0.1:$P3_SOCKS_OPEN" sr-3proxy