Spaces:
Running

File size: 9,750 Bytes
7e79d39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
package proxy

import (
	"context"
	"errors"
	"fmt"
	"net"
	"net/http"
	"net/http/httputil"
	"net/url"
	"os"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/gorilla/websocket"

	"panelthtuanit/internal/config"
	"panelthtuanit/internal/httpx"
	"panelthtuanit/internal/store"
)

var domainRegex = regexp.MustCompile(`^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$`)

var sharedTransport = &http.Transport{
	Proxy: nil,
	DialContext: (&net.Dialer{
		Timeout:   5 * time.Second,
		KeepAlive: 30 * time.Second,
	}).DialContext,
	MaxIdleConns:          512,
	MaxIdleConnsPerHost:   128,
	IdleConnTimeout:       90 * time.Second,
	ResponseHeaderTimeout: 30 * time.Second,
	ExpectContinueTimeout: 1 * time.Second,
	DisableCompression:    true,
}

var wsUpgrader = websocket.Upgrader{
	ReadBufferSize:  32 * 1024,
	WriteBufferSize: 32 * 1024,
	CheckOrigin:     func(r *http.Request) bool { return true },
}

// CleanDomain normalizes a domain string by stripping scheme, paths, and ports.
func CleanDomain(raw string) string {
	d := strings.ToLower(strings.TrimSpace(raw))
	if strings.HasPrefix(d, "https://") {
		d = d[len("https://"):]
	} else if strings.HasPrefix(d, "http://") {
		d = d[len("http://"):]
	}
	if idx := strings.IndexByte(d, '/'); idx >= 0 {
		d = d[:idx]
	}
	if idx := strings.IndexByte(d, ':'); idx >= 0 {
		d = d[:idx]
	}
	return strings.TrimSpace(d)
}

// IsValidDomain validates syntax and rejects localhost / *.hf.space / *.huggingface.co.
func IsValidDomain(domain string) bool {
	if domain == "" || len(domain) > 253 {
		return false
	}
	switch domain {
	case "localhost", "127.0.0.1", "0.0.0.0":
		return false
	}
	if strings.HasSuffix(domain, ".hf.space") || strings.HasSuffix(domain, ".huggingface.co") {
		return false
	}
	return domainRegex.MatchString(domain)
}

func clientIP(r *http.Request) string {
	if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil && host != "" {
		return host
	}
	if r.RemoteAddr != "" {
		return r.RemoteAddr
	}
	return "127.0.0.1"
}

func requestProto(r *http.Request, defaultProto string) string {
	if proto := r.Header.Get("X-Forwarded-Proto"); proto != "" {
		return strings.TrimSpace(strings.Split(proto, ",")[0])
	}
	if r.TLS != nil {
		return "https"
	}
	return defaultProto
}

func isTimeoutErr(err error) bool {
	if err == nil {
		return false
	}
	if errors.Is(err, context.DeadlineExceeded) || os.IsTimeout(err) {
		return true
	}
	var netErr net.Error
	return errors.As(err, &netErr) && netErr.Timeout()
}

// DomainProxyMiddleware intercepts custom domain HTTP/WebSocket traffic and routes it to the mapped zone port.
func DomainProxyMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		rawHost := r.Header.Get("X-Forwarded-Host")
		if rawHost == "" {
			rawHost = r.Host
		}
		firstHost := strings.Split(rawHost, ",")[0]
		domain := CleanDomain(firstHost)

		mapping, ok := store.LookupDomain(domain)
		if !ok {
			next.ServeHTTP(w, r)
			return
		}

		if httpx.IsWebSocketUpgrade(r) {
			proxyWS(w, r, mapping.Port, r.URL.Path, r.URL.RawQuery, fmt.Sprintf("Không thể kết nối WebSocket tới port %d", mapping.Port))
			return
		}

		target, _ := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", mapping.Port))
		rp := &httputil.ReverseProxy{
			Transport:     sharedTransport,
			FlushInterval: -1,
			Rewrite: func(pr *httputil.ProxyRequest) {
				pr.SetURL(target)
				pr.Out.Host = fmt.Sprintf("127.0.0.1:%d", mapping.Port)
				pr.Out.Header.Set("X-Forwarded-For", clientIP(pr.In))
				pr.Out.Header.Set("X-Forwarded-Proto", requestProto(pr.In, "https"))
				pr.Out.Header.Set("X-Forwarded-Host", domain)
			},
			ErrorHandler: func(rw http.ResponseWriter, req *http.Request, err error) {
				rw.Header().Set("Content-Type", "text/plain; charset=utf-8")
				if isTimeoutErr(err) {
					rw.WriteHeader(http.StatusGatewayTimeout)
					_, _ = fmt.Fprintf(rw, "504 Gateway Timeout: Cổng %d phản hồi quá lâu.", mapping.Port)
					return
				}
				rw.WriteHeader(http.StatusBadGateway)
				_, _ = fmt.Fprintf(rw, "502 Bad Gateway: Không thể kết nối tới port %d trong zone '%s'. Hãy đảm bảo ứng dụng đã chạy.", mapping.Port, mapping.Zone)
			},
		}
		rp.ServeHTTP(w, r)
	})
}

func validateProxyAccess(zoneName string, port int) error {
	if port < config.MinPort || port > config.MaxPort {
		return fmt.Errorf("Port must be between %d and %d", config.MinPort, config.MaxPort)
	}
	meta := store.LoadMeta()
	info, ok := meta[zoneName]
	if !ok || info == nil {
		return fmt.Errorf("Zone '%s' does not exist", zoneName)
	}
	for _, p := range info.Ports {
		if p.Port == port {
			return nil
		}
	}
	return errors.New("Port not mapped")
}

// HandlePortProxy serves HTTP and WebSocket reverse proxy requests under /port/{zone_name}/{port}[/{subpath...}].
func HandlePortProxy(w http.ResponseWriter, r *http.Request) {
	zoneName := r.PathValue("zone_name")
	portStr := r.PathValue("port")
	port, err := strconv.Atoi(portStr)
	if err != nil {
		if httpx.IsWebSocketUpgrade(r) {
			if conn, uerr := wsUpgrader.Upgrade(w, r, nil); uerr == nil {
				_ = conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(4004, "Invalid port"), time.Now().Add(2*time.Second))
				_ = conn.Close()
			}
			return
		}
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.WriteHeader(http.StatusNotFound)
		_, _ = fmt.Fprintf(w, "Port not mapped or invalid: invalid port")
		return
	}

	if err := validateProxyAccess(zoneName, port); err != nil {
		if httpx.IsWebSocketUpgrade(r) {
			if conn, uerr := wsUpgrader.Upgrade(w, r, nil); uerr == nil {
				_ = conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(4004, err.Error()), time.Now().Add(2*time.Second))
				_ = conn.Close()
			}
			return
		}
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.WriteHeader(http.StatusNotFound)
		_, _ = fmt.Fprintf(w, "Port not mapped or invalid: %s", err.Error())
		return
	}

	prefix := fmt.Sprintf("/port/%s/%d", zoneName, port)
	subpath := strings.TrimPrefix(r.URL.Path, prefix)
	if subpath == "" {
		subpath = "/"
	}

	if httpx.IsWebSocketUpgrade(r) {
		proxyWS(w, r, port, subpath, r.URL.RawQuery, fmt.Sprintf("Cannot connect WebSocket to port %d", port))
		return
	}

	target, _ := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", port))
	portToken := fmt.Sprintf(":%d", port)

	rp := &httputil.ReverseProxy{
		Transport:     sharedTransport,
		FlushInterval: -1,
		Rewrite: func(pr *httputil.ProxyRequest) {
			pr.SetURL(target)
			pr.Out.URL.Path = subpath
			pr.Out.URL.RawPath = ""
			pr.Out.URL.RawQuery = pr.In.URL.RawQuery
			pr.Out.Host = fmt.Sprintf("127.0.0.1:%d", port)
			pr.Out.Header.Set("X-Forwarded-For", clientIP(pr.In))
			pr.Out.Header.Set("X-Forwarded-Proto", requestProto(pr.In, "http"))
			pr.Out.Header.Set("X-Forwarded-Prefix", prefix)
		},
		ModifyResponse: func(resp *http.Response) error {
			if loc := resp.Header.Get("Location"); loc != "" {
				if strings.HasPrefix(loc, "/") {
					resp.Header.Set("Location", prefix+loc)
				} else if idx := strings.Index(loc, portToken); idx >= 0 {
					rest := loc[idx+len(portToken):]
					resp.Header.Set("Location", prefix+rest)
				}
			}
			return nil
		},
		ErrorHandler: func(rw http.ResponseWriter, req *http.Request, err error) {
			rw.Header().Set("Content-Type", "text/plain; charset=utf-8")
			if isTimeoutErr(err) {
				rw.WriteHeader(http.StatusGatewayTimeout)
				_, _ = fmt.Fprintf(rw, "Timeout connecting to port %d", port)
				return
			}
			rw.WriteHeader(http.StatusBadGateway)
			_, _ = fmt.Fprintf(rw, "Cannot connect to port %d. Make sure your server is running in zone '%s'.", port, zoneName)
		},
	}
	rp.ServeHTTP(w, r)
}

var skipWSDialHeaders = map[string]bool{
	"Upgrade":                  true,
	"Connection":               true,
	"Sec-Websocket-Key":        true,
	"Sec-Websocket-Version":    true,
	"Sec-Websocket-Extensions": true,
	"Sec-Websocket-Accept":     true,
	"Sec-Websocket-Protocol":   true,
}

func proxyWS(w http.ResponseWriter, r *http.Request, port int, path, rawQuery, connectErrMsg string) {
	subprotocols := websocket.Subprotocols(r)
	var respHeader http.Header
	if len(subprotocols) > 0 {
		respHeader = http.Header{}
		respHeader.Set("Sec-WebSocket-Protocol", subprotocols[0])
	}

	clientConn, err := wsUpgrader.Upgrade(w, r, respHeader)
	if err != nil {
		return
	}
	defer clientConn.Close()

	if !strings.HasPrefix(path, "/") {
		path = "/" + path
	}
	targetURL := fmt.Sprintf("ws://127.0.0.1:%d%s", port, path)
	if rawQuery != "" {
		targetURL += "?" + rawQuery
	}

	dialHeader := http.Header{}
	for k, vals := range r.Header {
		ck := http.CanonicalHeaderKey(k)
		if skipWSDialHeaders[ck] || ck == "Host" {
			continue
		}
		for _, v := range vals {
			dialHeader.Add(ck, v)
		}
	}

	dialer := websocket.Dialer{
		HandshakeTimeout: 10 * time.Second,
		Subprotocols:     subprotocols,
	}
	backendConn, _, err := dialer.Dial(targetURL, dialHeader)
	if err != nil {
		_ = clientConn.WriteJSON(map[string]string{"error": connectErrMsg})
		return
	}
	defer backendConn.Close()

	var wg sync.WaitGroup
	wg.Add(2)

	pump := func(dst, src *websocket.Conn) {
		defer wg.Done()
		for {
			msgType, payload, rerr := src.ReadMessage()
			if rerr != nil {
				var closeErr *websocket.CloseError
				if errors.As(rerr, &closeErr) {
					_ = dst.WriteControl(
						websocket.CloseMessage,
						websocket.FormatCloseMessage(closeErr.Code, closeErr.Text),
						time.Now().Add(time.Second),
					)
				}
				_ = dst.Close()
				return
			}
			if werr := dst.WriteMessage(msgType, payload); werr != nil {
				return
			}
		}
	}

	go pump(backendConn, clientConn)
	go pump(clientConn, backendConn)
	wg.Wait()
}