Skip to content

Commit

Permalink
feat: add url proxy to mobileproxy (#187)
Browse files Browse the repository at this point in the history
  • Loading branch information
fortuna authored Feb 22, 2024
1 parent b7fe02b commit a85885b
Show file tree
Hide file tree
Showing 3 changed files with 94 additions and 8 deletions.
9 changes: 6 additions & 3 deletions x/examples/http2transport/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import (
func main() {
transportFlag := flag.String("transport", "", "Transport config")
addrFlag := flag.String("localAddr", "localhost:1080", "Local proxy address")
urlProxyPrefixFlag := flag.String("urlProxyPrefix", "/proxy", "Path where to run the URL proxy. Set to empty (\"\") to disable it.")
flag.Parse()

dialer, err := config.NewStreamDialer(*transportFlag)
Expand All @@ -45,9 +46,11 @@ func main() {
defer listener.Close()
log.Printf("Proxy listening on %v", listener.Addr().String())

handler := httpproxy.NewProxyHandler(dialer)
handler.FallbackHandler = httpproxy.NewPathHandler(dialer)
server := http.Server{Handler: handler}
proxyHandler := httpproxy.NewProxyHandler(dialer)
if *urlProxyPrefixFlag != "" {
proxyHandler.FallbackHandler = http.StripPrefix(*urlProxyPrefixFlag, httpproxy.NewPathHandler(dialer))
}
server := http.Server{Handler: proxyHandler}
go func() {
if err := server.Serve(listener); err != nil && err != http.ErrServerClosed {
log.Fatalf("Error running web server: %v", err)
Expand Down
51 changes: 51 additions & 0 deletions x/examples/run-mobileproxy/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Copyright 2023 Jigsaw Operations LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
"flag"
"log"
"os"
"os/signal"

"github.com/Jigsaw-Code/outline-sdk/x/mobileproxy"
)

func main() {
transportFlag := flag.String("transport", "", "Transport config")
addrFlag := flag.String("localAddr", "localhost:8080", "Local proxy address")
urlProxyPrefixFlag := flag.String("proxyPath", "/proxy", "Path where to run the URL proxy. Set to empty (\"\") to disable it.")
flag.Parse()

dialer, err := mobileproxy.NewStreamDialerFromConfig(*transportFlag)
if err != nil {
log.Fatalf("NewStreamDialerFromConfig failed: %v", err)
}
proxy, err := mobileproxy.RunProxy(*addrFlag, dialer)
if err != nil {
log.Fatalf("RunProxy failed: %v", err)
}
if *urlProxyPrefixFlag != "" {
proxy.AddURLProxy(*urlProxyPrefixFlag, dialer)
}
log.Printf("Proxy listening on %v", proxy.Address())

// Wait for interrupt signal to stop the proxy.
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt)
<-sig
log.Print("Shutting down")
proxy.Stop(2)
}
42 changes: 37 additions & 5 deletions x/mobileproxy/mobileproxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,10 @@ import (

// Proxy enables you to get the actual address bound by the server and stop the service when no longer needed.
type Proxy struct {
host string
port int
server *http.Server
host string
port int
proxyHandler *httpproxy.ProxyHandler
server *http.Server
}

// Address returns the IP and port the server is bound to.
Expand All @@ -58,6 +59,30 @@ func (p *Proxy) Port() int {
return p.port
}

// AddURLProxy sets up a URL-based proxy handler that activates when an incoming HTTP request matches
// the specified path prefix. The pattern must represent a path segment, which is checked against
// the path of the incoming request.
//
// This function is particularly useful for libraries or components that accept URLs but do not support proxy
// configuration directly. By leveraging AddURLProxy, such components can route requests through a proxy by
// constructing URLs in the format "http://${HOST}:${PORT}/${PATH}/${URL}", where "${URL}" is the target resource.
// For instance, using "http://localhost:8080/proxy/https://example.com" routes the request for "https://example.com"
// through a proxy at "http://localhost:8080/proxy".
//
// The path should start with a forward slash ('/') for clarity, but one will be added if missing.
//
// The function associates the given 'dialer' with the specified 'path', allowing different dialers to be used for
// different path-based proxies within the same application in the future. currently we only support one URL proxy.
func (p *Proxy) AddURLProxy(path string, dialer *StreamDialer) {
if len(path) == 0 || path[0] != '/' {
path = "/" + path
}
// TODO(fortuna): Add support for multiple paths. I tried http.ServeMux, but it does request sanitization,
// which breaks the URL extraction: https://pkg.go.dev/net/http#hdr-Request_sanitizing.
// We can consider forking http.StripPrefix to provide a fallback instead of NotFound, and chaing them.
p.proxyHandler.FallbackHandler = http.StripPrefix(path, httpproxy.NewPathHandler(dialer.StreamDialer))
}

// Stop gracefully stops the proxy service, waiting for at most timeout seconds before forcefully closing it.
// The function takes a timeoutSeconds number instead of a [time.Duration] so it's compatible with Go Mobile.
func (p *Proxy) Stop(timeoutSeconds int) {
Expand All @@ -77,7 +102,9 @@ func RunProxy(localAddress string, dialer *StreamDialer) (*Proxy, error) {
return nil, fmt.Errorf("could not listen on address %v: %v", localAddress, err)
}

server := &http.Server{Handler: httpproxy.NewProxyHandler(dialer)}
proxyHandler := httpproxy.NewProxyHandler(dialer)
proxyHandler.FallbackHandler = http.NotFoundHandler()
server := &http.Server{Handler: proxyHandler}
go server.Serve(listener)

host, portStr, err := net.SplitHostPort(listener.Addr().String())
Expand All @@ -88,7 +115,12 @@ func RunProxy(localAddress string, dialer *StreamDialer) (*Proxy, error) {
if err != nil {
return nil, fmt.Errorf("could not parse proxy port '%v': %v", portStr, err)
}
return &Proxy{host: host, port: port, server: server}, nil
return &Proxy{
host: host,
port: port,
server: server,
proxyHandler: proxyHandler,
}, nil
}

// StreamDialer encapsulates the logic to create stream connections (like TCP).
Expand Down

0 comments on commit a85885b

Please sign in to comment.