File size: 3,774 Bytes
4e5b86f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
package main

import (
	"encoding/json"
	"io"
	"log"
	"net/http"
	"sync"
	"sync/atomic"
	"time"

	"github.com/gorilla/websocket"
)

type Request struct {
	ID      uint64              `json:"id"`
	Method  string              `json:"method"`
	Path    string              `json:"path"`
	Headers map[string][]string `json:"headers"`
	Body    []byte              `json:"body"`
}

type Response struct {
	ID      uint64              `json:"id"`
	Status  int                 `json:"status"`
	Headers map[string][]string `json:"headers"`
	Body    []byte              `json:"body"`
}

type Tunnel struct {
	conn     *websocket.Conn
	mu       sync.Mutex
	pending  map[uint64]chan Response
	pendMu   sync.RWMutex
	counter  uint64
	lastPing time.Time
}

var (
	tunnel   *Tunnel
	tunnelMu sync.RWMutex
	upgrader = websocket.Upgrader{
		CheckOrigin:     func(r *http.Request) bool { return true },
		ReadBufferSize:  65536,
		WriteBufferSize: 65536,
	}
	authToken = "your-secret-token-change-me"
)

func main() {
	http.HandleFunc("/", handler)
	log.Println("Server starting on :7860")
	log.Fatal(http.ListenAndServe(":7860", nil))
}

func handler(w http.ResponseWriter, r *http.Request) {
	switch r.URL.Path {
	case "/_tunnel":
		handleTunnel(w, r)
	case "/_health":
		handleHealth(w)
	default:
		handleProxy(w, r)
	}
}

func handleHealth(w http.ResponseWriter) {
	tunnelMu.RLock()
	connected := tunnel != nil
	tunnelMu.RUnlock()

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]any{
		"status":    "ok",
		"connected": connected,
		"time":      time.Now().Unix(),
	})
}

func handleTunnel(w http.ResponseWriter, r *http.Request) {
	if r.Header.Get("X-Tunnel-Token") != authToken {
		http.Error(w, "unauthorized", http.StatusUnauthorized)
		return
	}

	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Printf("upgrade failed: %v", err)
		return
	}

	t := &Tunnel{
		conn:     conn,
		pending:  make(map[uint64]chan Response),
		lastPing: time.Now(),
	}

	tunnelMu.Lock()
	if tunnel != nil {
		tunnel.conn.Close()
	}
	tunnel = t
	tunnelMu.Unlock()

	log.Println("client connected")
	t.readLoop()

	tunnelMu.Lock()
	if tunnel == t {
		tunnel = nil
	}
	tunnelMu.Unlock()
	log.Println("client disconnected")
}

func (t *Tunnel) readLoop() {
	defer t.conn.Close()

	for {
		_, data, err := t.conn.ReadMessage()
		if err != nil {
			return
		}

		var resp Response
		if json.Unmarshal(data, &resp) != nil {
			continue
		}

		t.pendMu.RLock()
		ch, ok := t.pending[resp.ID]
		t.pendMu.RUnlock()

		if ok {
			select {
			case ch <- resp:
			default:
			}
		}
	}
}

func (t *Tunnel) send(req Request) (Response, error) {
	ch := make(chan Response, 1)

	t.pendMu.Lock()
	t.pending[req.ID] = ch
	t.pendMu.Unlock()

	defer func() {
		t.pendMu.Lock()
		delete(t.pending, req.ID)
		t.pendMu.Unlock()
	}()

	data, _ := json.Marshal(req)

	t.mu.Lock()
	err := t.conn.WriteMessage(websocket.TextMessage, data)
	t.mu.Unlock()

	if err != nil {
		return Response{}, err
	}

	select {
	case resp := <-ch:
		return resp, nil
	case <-time.After(60 * time.Second):
		return Response{Status: 504}, nil
	}
}

func handleProxy(w http.ResponseWriter, r *http.Request) {
	tunnelMu.RLock()
	t := tunnel
	tunnelMu.RUnlock()

	if t == nil {
		http.Error(w, "tunnel not connected", http.StatusBadGateway)
		return
	}

	body, _ := io.ReadAll(r.Body)

	req := Request{
		ID:      atomic.AddUint64(&t.counter, 1),
		Method:  r.Method,
		Path:    r.URL.RequestURI(),
		Headers: r.Header,
		Body:    body,
	}

	resp, err := t.send(req)
	if err != nil {
		http.Error(w, "tunnel error", http.StatusBadGateway)
		return
	}

	for k, vals := range resp.Headers {
		for _, v := range vals {
			w.Header().Add(k, v)
		}
	}

	w.WriteHeader(resp.Status)
	w.Write(resp.Body)
}