Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: create WebSocket Reverse Proxy #202

Merged
merged 8 commits into from
Apr 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions x/examples/ws2endpoint/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# WebSocket Reverse Proxy

This package contains a command-line tool to expose a WebSocket endpoint that connects to
any endpoint over a transport.

```sh
go run ./examples/ws2endpoint --endpoint ipinfo.io:443 --transport tls
```

Then, on a browser console, you can do:

```js
s = new WebSocket("ws://localhost:8080");
s.onmessage = (m) => console.log(m.data);
s.onopen = () => { s.send("GET /json HTTP/1.1\r\nHost: ipinfo.io\r\n\r\n"); }
```

And you will see the response. For example:

```http
HTTP/1.1 200 OK
server: nginx/1.24.0
date: Fri, 22 Mar 2024 22:07:18 GMT
content-type: application/json; charset=utf-8
Content-Length: 321
access-control-allow-origin: *
x-content-type-options: nosniff
x-envoy-upstream-service-time: 3
via: 1.1 google
strict-transport-security: max-age=2592000; includeSubDomains
Alt-Svc: h3=":443"; ma=2592000,h3-29=":443"; ma=2592000

{
"ip": "[REDACTED]",
"hostname": "[REDACTED]",
"city": "New York City",
"region": "New York",
"country": "US",
...
"timezone": "America/New_York",
"readme": "https://ipinfo.io/missingauth"
}
```

You can expose your WebSockets on Cloudflare with [clourdflared](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/do-more-with-tunnels/trycloudflare/). For example:
jyyi1 marked this conversation as resolved.
Show resolved Hide resolved

```console
% cloudflared tunnel --url http://localhost:8080

2024-03-22T22:06:27Z INF Thank you for trying Cloudflare Tunnel. Doing so, without a Cloudflare account, is a quick way to experiment and try it out. However, be aware that these account-less Tunnels have no uptime guarantee. If you intend to use Tunnels in production you should use a pre-created named tunnel by following: https://developers.cloudflare.com/cloudflare-one/connections/connect-apps
2024-03-22T22:06:27Z INF Requesting new quick Tunnel on trycloudflare.com...
2024-03-22T22:06:28Z INF +--------------------------------------------------------------------------------------------+
2024-03-22T22:06:28Z INF | Your quick Tunnel has been created! Visit it at (it may take some time to be reachable): |
2024-03-22T22:06:28Z INF | https://recorders-uganda-starring-stopping.trycloudflare.com |
2024-03-22T22:06:28Z INF +--------------------------------------------------------------------------------------------+
```

In this case, use `wss://recorders-uganda-starring-stopping.trycloudflare.com` as the WebSocket url.


Note that the Cloudflare tunnel does not add any user authentication mechanism. You must implement authentication yourself
if you would like to prevent unauthorized access to your service.
93 changes: 93 additions & 0 deletions x/examples/ws2endpoint/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
// Copyright 2024 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 (
"context"
"flag"
"io"
"log"
"net"
"net/http"
"os"
"os/signal"
"time"

"github.com/Jigsaw-Code/outline-sdk/transport"
"github.com/Jigsaw-Code/outline-sdk/x/config"
"golang.org/x/net/websocket"
)

func main() {
addrFlag := flag.String("localAddr", "localhost:8080", "Local proxy address")
transportFlag := flag.String("transport", "", "Transport config")
endpointFlag := flag.String("endpoint", "", "Address of the target endpoint")
pathPrefix := flag.String("path", "/", "Path where to run the Websocket forwarder")
flag.Parse()

dialer, err := config.NewStreamDialer(*transportFlag)
if err != nil {
log.Fatalf("Could not create dialer: %v", err)
}
if *endpointFlag == "" {
log.Fatal("Must specify flag -endpoint")
}
endpoint := transport.StreamDialerEndpoint{Dialer: dialer, Address: *endpointFlag}

listener, err := net.Listen("tcp", *addrFlag)
if err != nil {
log.Fatalf("Could not listen on address %v: %v", *addrFlag, err)
}
defer listener.Close()
log.Printf("Proxy listening on %v\n", listener.Addr().String())

handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("Got request: %v\n", r)
handler := func(wsConn *websocket.Conn) {
targetConn, err := endpoint.ConnectStream(r.Context())
if err != nil {
log.Printf("Failed to upgrade: %v\n", err)
w.WriteHeader(http.StatusBadGateway)
jyyi1 marked this conversation as resolved.
Show resolved Hide resolved
return
}
defer targetConn.Close()
go func() {
io.Copy(targetConn, wsConn)
targetConn.CloseWrite()
}()
io.Copy(wsConn, targetConn)
wsConn.Close()
}
websocket.Server{Handler: handler}.ServeHTTP(w, r)
jyyi1 marked this conversation as resolved.
Show resolved Hide resolved
})
server := http.Server{Handler: http.StripPrefix(*pathPrefix, handler)}
go func() {
if err := server.Serve(listener); err != nil && err != http.ErrServerClosed {
log.Fatalf("Error running web server: %v", err)
}
}()

// Wait for interrupt signal to stop the proxy.
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt)
<-sig
log.Println("Shutting down")
// Gracefully shut down the server, with a 5s timeout.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
log.Fatalf("Failed to shutdown gracefully: %v", err)
}
}
Loading