Browse Source

Added options to toggle uptime monitor and websocket conn header copy

Toby Chui 3 months ago
parent
commit
815dd339ca

+ 1 - 0
api.go

@@ -59,6 +59,7 @@ func RegisterHTTPProxyAPIs(authRouter *auth.RouterDef) {
 	authRouter.HandleFunc("/api/proxy/header/handleHopByHop", HandleHopByHop)
 	authRouter.HandleFunc("/api/proxy/header/handleHostOverwrite", HandleHostOverwrite)
 	authRouter.HandleFunc("/api/proxy/header/handlePermissionPolicy", HandlePermissionPolicy)
+	authRouter.HandleFunc("/api/proxy/header/handleWsHeaderBehavior", HandleWsHeaderBehavior)
 	/* Reverse proxy auth related */
 	authRouter.HandleFunc("/api/proxy/auth/exceptions/list", ListProxyBasicAuthExceptionPaths)
 	authRouter.HandleFunc("/api/proxy/auth/exceptions/add", AddProxyBasicAuthExceptionPaths)

+ 1 - 1
def.go

@@ -43,7 +43,7 @@ const (
 	/* Build Constants */
 	SYSTEM_NAME       = "Zoraxy"
 	SYSTEM_VERSION    = "3.1.5"
-	DEVELOPMENT_BUILD = false /* Development: Set to false to use embedded web fs */
+	DEVELOPMENT_BUILD = true /* Development: Set to false to use embedded web fs */
 
 	/* System Constants */
 	DATABASE_PATH              = "sys.db"

+ 19 - 18
mod/dynamicproxy/default.go

@@ -42,23 +42,24 @@ func GetDefaultHeaderRewriteRules() *HeaderRewriteRules {
 func GetDefaultProxyEndpoint() ProxyEndpoint {
 	randomPrefix := uuid.New().String()
 	return ProxyEndpoint{
-		ProxyType:              ProxyTypeHost,
-		RootOrMatchingDomain:   randomPrefix + ".internal",
-		MatchingDomainAlias:    []string{},
-		ActiveOrigins:          []*loadbalance.Upstream{},
-		InactiveOrigins:        []*loadbalance.Upstream{},
-		UseStickySession:       false,
-		UseActiveLoadBalance:   false,
-		Disabled:               false,
-		BypassGlobalTLS:        false,
-		VirtualDirectories:     []*VirtualDirectoryEndpoint{},
-		HeaderRewriteRules:     GetDefaultHeaderRewriteRules(),
-		AuthenticationProvider: GetDefaultAuthenticationProvider(),
-		RequireRateLimit:       false,
-		RateLimit:              0,
-		DisableUptimeMonitor:   false,
-		AccessFilterUUID:       "default",
-		DefaultSiteOption:      DefaultSite_InternalStaticWebServer,
-		DefaultSiteValue:       "",
+		ProxyType:                    ProxyTypeHost,
+		RootOrMatchingDomain:         randomPrefix + ".internal",
+		MatchingDomainAlias:          []string{},
+		ActiveOrigins:                []*loadbalance.Upstream{},
+		InactiveOrigins:              []*loadbalance.Upstream{},
+		UseStickySession:             false,
+		UseActiveLoadBalance:         false,
+		Disabled:                     false,
+		BypassGlobalTLS:              false,
+		VirtualDirectories:           []*VirtualDirectoryEndpoint{},
+		HeaderRewriteRules:           GetDefaultHeaderRewriteRules(),
+		EnableWebsocketCustomHeaders: false,
+		AuthenticationProvider:       GetDefaultAuthenticationProvider(),
+		RequireRateLimit:             false,
+		RateLimit:                    0,
+		DisableUptimeMonitor:         false,
+		AccessFilterUUID:             "default",
+		DefaultSiteOption:            DefaultSite_InternalStaticWebServer,
+		DefaultSiteValue:             "",
 	}
 }

+ 8 - 3
mod/dynamicproxy/proxyRequestHandler.go

@@ -152,7 +152,7 @@ func (h *ProxyHandler) hostRequest(w http.ResponseWriter, r *http.Request, targe
 		wspHandler := websocketproxy.NewProxy(u, websocketproxy.Options{
 			SkipTLSValidation:  selectedUpstream.SkipCertValidations,
 			SkipOriginCheck:    selectedUpstream.SkipWebSocketOriginCheck,
-			CopyAllHeaders:     domainsniff.RequireWebsocketHeaderCopy(r),
+			CopyAllHeaders:     target.EnableWebsocketCustomHeaders,
 			UserDefinedHeaders: target.HeaderRewriteRules.UserDefinedHeaders,
 			Logger:             h.Parent.Option.Logger,
 		})
@@ -232,11 +232,16 @@ func (h *ProxyHandler) vdirRequest(w http.ResponseWriter, r *http.Request, targe
 		if target.RequireTLS {
 			u, _ = url.Parse("wss://" + wsRedirectionEndpoint + r.URL.String())
 		}
+
+		if target.parent.HeaderRewriteRules != nil {
+			target.parent.HeaderRewriteRules = GetDefaultHeaderRewriteRules()
+		}
+
 		h.Parent.logRequest(r, true, 101, "vdir-websocket", target.Domain)
 		wspHandler := websocketproxy.NewProxy(u, websocketproxy.Options{
 			SkipTLSValidation:  target.SkipCertValidations,
-			SkipOriginCheck:    true,                                      //You should not use websocket via virtual directory. But keep this to true for compatibility
-			CopyAllHeaders:     domainsniff.RequireWebsocketHeaderCopy(r), //Left this as default to prevent nginx user setting / as vdir
+			SkipOriginCheck:    target.parent.EnableWebsocketCustomHeaders, //You should not use websocket via virtual directory. But keep this to true for compatibility
+			CopyAllHeaders:     domainsniff.RequireWebsocketHeaderCopy(r),  //Left this as default to prevent nginx user setting / as vdir
 			UserDefinedHeaders: target.parent.HeaderRewriteRules.UserDefinedHeaders,
 			Logger:             h.Parent.Option.Logger,
 		})

+ 9 - 1
mod/dynamicproxy/typedef.go

@@ -1,5 +1,12 @@
 package dynamicproxy
 
+/*
+	typdef.go
+
+	This script handle the type definition for dynamic proxy and endpoints
+
+	If you are looking for the default object initailization, please refer to default.go
+*/
 import (
 	_ "embed"
 	"net"
@@ -165,7 +172,8 @@ type ProxyEndpoint struct {
 	VirtualDirectories []*VirtualDirectoryEndpoint
 
 	//Custom Headers
-	HeaderRewriteRules *HeaderRewriteRules
+	HeaderRewriteRules           *HeaderRewriteRules
+	EnableWebsocketCustomHeaders bool //Enable custom headers for websocket connections as well (default only http reqiests)
 
 	//Authentication
 	AuthenticationProvider *AuthenticationProvider

+ 27 - 12
mod/websocketproxy/websocketproxy.go

@@ -172,6 +172,11 @@ func (w *WebsocketProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
 	if req.Host != "" {
 		requestHeader.Set("Host", req.Host)
 	}
+	if userAgent := req.Header.Get("User-Agent"); userAgent != "" {
+		requestHeader.Set("User-Agent", userAgent)
+	} else {
+		requestHeader.Set("User-Agent", "zoraxy-wsproxy/1.1")
+	}
 
 	// Pass X-Forwarded-For headers too, code below is a part of
 	// httputil.ReverseProxy. See http://en.wikipedia.org/wiki/X-Forwarded-For
@@ -195,19 +200,29 @@ func (w *WebsocketProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
 		requestHeader.Set("X-Forwarded-Proto", "https")
 	}
 
-	// Enable the director to copy any additional headers it desires for
-	// forwarding to the remote server.
-	if w.Director != nil {
-		w.Director(req, requestHeader)
-	}
-
 	// Replace header variables and copy user-defined headers
-	rewrittenUserDefinedHeaders := rewrite.PopulateRequestHeaderVariables(req, w.Options.UserDefinedHeaders)
-	upstreamHeaders, _ := rewrite.SplitUpDownStreamHeaders(&rewrite.HeaderRewriteOptions{
-		UserDefinedHeaders: rewrittenUserDefinedHeaders,
-	})
-	for _, headerValuePair := range upstreamHeaders {
-		requestHeader.Set(headerValuePair[0], headerValuePair[1])
+	if w.Options.CopyAllHeaders {
+		// Rewrite the user defined headers
+		// This is reported to be not compatible with Proxmox and Home Assistant
+		// but required by some other projects like MeshCentral
+		// we will make this optional
+		rewrittenUserDefinedHeaders := rewrite.PopulateRequestHeaderVariables(req, w.Options.UserDefinedHeaders)
+		upstreamHeaders, _ := rewrite.SplitUpDownStreamHeaders(&rewrite.HeaderRewriteOptions{
+			UserDefinedHeaders: rewrittenUserDefinedHeaders,
+		})
+		for _, headerValuePair := range upstreamHeaders {
+			//Do not copy Upgrade and Connection headers, it will be handled by the upgrader
+			if strings.EqualFold(headerValuePair[0], "Upgrade") || strings.EqualFold(headerValuePair[0], "Connection") {
+				continue
+			}
+			requestHeader.Set(headerValuePair[0], headerValuePair[1])
+		}
+
+		// Enable the director to copy any additional headers it desires for
+		// forwarding to the remote server.
+		if w.Director != nil {
+			w.Director(req, requestHeader)
+		}
 	}
 
 	// Connect to the backend URL, also pass the headers we get from the requst

+ 43 - 0
reverseproxy.go

@@ -467,6 +467,12 @@ func ReverseProxyHandleEditEndpoint(w http.ResponseWriter, r *http.Request) {
 	}
 	bypassGlobalTLS := (bpgtls == "true")
 
+	//Disable uptime monitor
+	disbleUtm, err := utils.PostBool(r, "dutm")
+	if err != nil {
+		disbleUtm = false
+	}
+
 	// Auth Provider
 	authProviderTypeStr, _ := utils.PostPara(r, "authprovider")
 	if authProviderTypeStr == "" {
@@ -532,6 +538,7 @@ func ReverseProxyHandleEditEndpoint(w http.ResponseWriter, r *http.Request) {
 	newProxyEndpoint.RequireRateLimit = requireRateLimit
 	newProxyEndpoint.RateLimit = proxyRateLimit
 	newProxyEndpoint.UseStickySession = useStickySession
+	newProxyEndpoint.DisableUptimeMonitor = disbleUtm
 
 	//Prepare to replace the current routing rule
 	readyRoutingRule, err := dynamicProxyRouter.PrepareProxyRoute(newProxyEndpoint)
@@ -1553,3 +1560,39 @@ func HandlePermissionPolicy(w http.ResponseWriter, r *http.Request) {
 
 	http.Error(w, "405 - Method not allowed", http.StatusMethodNotAllowed)
 }
+
+func HandleWsHeaderBehavior(w http.ResponseWriter, r *http.Request) {
+	domain, err := utils.PostPara(r, "domain")
+	if err != nil {
+		domain, err = utils.GetPara(r, "domain")
+		if err != nil {
+			utils.SendErrorResponse(w, "domain or matching rule not defined")
+			return
+		}
+	}
+
+	targetProxyEndpoint, err := dynamicProxyRouter.LoadProxy(domain)
+	if err != nil {
+		utils.SendErrorResponse(w, "target endpoint not exists")
+		return
+	}
+
+	if r.Method == http.MethodGet {
+		js, _ := json.Marshal(targetProxyEndpoint.EnableWebsocketCustomHeaders)
+		utils.SendJSONResponse(w, string(js))
+	} else if r.Method == http.MethodPost {
+		enableWsHeader, err := utils.PostBool(r, "enable")
+		if err != nil {
+			utils.SendErrorResponse(w, "invalid enable state given")
+			return
+		}
+
+		targetProxyEndpoint.EnableWebsocketCustomHeaders = enableWsHeader
+		SaveReverseProxyConfig(targetProxyEndpoint)
+		targetProxyEndpoint.UpdateToRuntime()
+		utils.SendOK(w)
+
+	} else {
+		http.Error(w, "405 - Method not allowed", http.StatusMethodNotAllowed)
+	}
+}

+ 0 - 0
tools/flow-emulator/go.mod → tools/benchmark/go.mod


+ 0 - 0
tools/flow-emulator/main.go → tools/benchmark/main.go


+ 0 - 0
tools/flow-emulator/server.go → tools/benchmark/server.go


+ 0 - 201
tools/tcpcpy/LICENSE

@@ -1,201 +0,0 @@
-                                 Apache License
-                           Version 2.0, January 2004
-                        http://www.apache.org/licenses/
-
-   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-   1. Definitions.
-
-      "License" shall mean the terms and conditions for use, reproduction,
-      and distribution as defined by Sections 1 through 9 of this document.
-
-      "Licensor" shall mean the copyright owner or entity authorized by
-      the copyright owner that is granting the License.
-
-      "Legal Entity" shall mean the union of the acting entity and all
-      other entities that control, are controlled by, or are under common
-      control with that entity. For the purposes of this definition,
-      "control" means (i) the power, direct or indirect, to cause the
-      direction or management of such entity, whether by contract or
-      otherwise, or (ii) ownership of fifty percent (50%) or more of the
-      outstanding shares, or (iii) beneficial ownership of such entity.
-
-      "You" (or "Your") shall mean an individual or Legal Entity
-      exercising permissions granted by this License.
-
-      "Source" form shall mean the preferred form for making modifications,
-      including but not limited to software source code, documentation
-      source, and configuration files.
-
-      "Object" form shall mean any form resulting from mechanical
-      transformation or translation of a Source form, including but
-      not limited to compiled object code, generated documentation,
-      and conversions to other media types.
-
-      "Work" shall mean the work of authorship, whether in Source or
-      Object form, made available under the License, as indicated by a
-      copyright notice that is included in or attached to the work
-      (an example is provided in the Appendix below).
-
-      "Derivative Works" shall mean any work, whether in Source or Object
-      form, that is based on (or derived from) the Work and for which the
-      editorial revisions, annotations, elaborations, or other modifications
-      represent, as a whole, an original work of authorship. For the purposes
-      of this License, Derivative Works shall not include works that remain
-      separable from, or merely link (or bind by name) to the interfaces of,
-      the Work and Derivative Works thereof.
-
-      "Contribution" shall mean any work of authorship, including
-      the original version of the Work and any modifications or additions
-      to that Work or Derivative Works thereof, that is intentionally
-      submitted to Licensor for inclusion in the Work by the copyright owner
-      or by an individual or Legal Entity authorized to submit on behalf of
-      the copyright owner. For the purposes of this definition, "submitted"
-      means any form of electronic, verbal, or written communication sent
-      to the Licensor or its representatives, including but not limited to
-      communication on electronic mailing lists, source code control systems,
-      and issue tracking systems that are managed by, or on behalf of, the
-      Licensor for the purpose of discussing and improving the Work, but
-      excluding communication that is conspicuously marked or otherwise
-      designated in writing by the copyright owner as "Not a Contribution."
-
-      "Contributor" shall mean Licensor and any individual or Legal Entity
-      on behalf of whom a Contribution has been received by Licensor and
-      subsequently incorporated within the Work.
-
-   2. Grant of Copyright License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      copyright license to reproduce, prepare Derivative Works of,
-      publicly display, publicly perform, sublicense, and distribute the
-      Work and such Derivative Works in Source or Object form.
-
-   3. Grant of Patent License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      (except as stated in this section) patent license to make, have made,
-      use, offer to sell, sell, import, and otherwise transfer the Work,
-      where such license applies only to those patent claims licensable
-      by such Contributor that are necessarily infringed by their
-      Contribution(s) alone or by combination of their Contribution(s)
-      with the Work to which such Contribution(s) was submitted. If You
-      institute patent litigation against any entity (including a
-      cross-claim or counterclaim in a lawsuit) alleging that the Work
-      or a Contribution incorporated within the Work constitutes direct
-      or contributory patent infringement, then any patent licenses
-      granted to You under this License for that Work shall terminate
-      as of the date such litigation is filed.
-
-   4. Redistribution. You may reproduce and distribute copies of the
-      Work or Derivative Works thereof in any medium, with or without
-      modifications, and in Source or Object form, provided that You
-      meet the following conditions:
-
-      (a) You must give any other recipients of the Work or
-          Derivative Works a copy of this License; and
-
-      (b) You must cause any modified files to carry prominent notices
-          stating that You changed the files; and
-
-      (c) You must retain, in the Source form of any Derivative Works
-          that You distribute, all copyright, patent, trademark, and
-          attribution notices from the Source form of the Work,
-          excluding those notices that do not pertain to any part of
-          the Derivative Works; and
-
-      (d) If the Work includes a "NOTICE" text file as part of its
-          distribution, then any Derivative Works that You distribute must
-          include a readable copy of the attribution notices contained
-          within such NOTICE file, excluding those notices that do not
-          pertain to any part of the Derivative Works, in at least one
-          of the following places: within a NOTICE text file distributed
-          as part of the Derivative Works; within the Source form or
-          documentation, if provided along with the Derivative Works; or,
-          within a display generated by the Derivative Works, if and
-          wherever such third-party notices normally appear. The contents
-          of the NOTICE file are for informational purposes only and
-          do not modify the License. You may add Your own attribution
-          notices within Derivative Works that You distribute, alongside
-          or as an addendum to the NOTICE text from the Work, provided
-          that such additional attribution notices cannot be construed
-          as modifying the License.
-
-      You may add Your own copyright statement to Your modifications and
-      may provide additional or different license terms and conditions
-      for use, reproduction, or distribution of Your modifications, or
-      for any such Derivative Works as a whole, provided Your use,
-      reproduction, and distribution of the Work otherwise complies with
-      the conditions stated in this License.
-
-   5. Submission of Contributions. Unless You explicitly state otherwise,
-      any Contribution intentionally submitted for inclusion in the Work
-      by You to the Licensor shall be under the terms and conditions of
-      this License, without any additional terms or conditions.
-      Notwithstanding the above, nothing herein shall supersede or modify
-      the terms of any separate license agreement you may have executed
-      with Licensor regarding such Contributions.
-
-   6. Trademarks. This License does not grant permission to use the trade
-      names, trademarks, service marks, or product names of the Licensor,
-      except as required for reasonable and customary use in describing the
-      origin of the Work and reproducing the content of the NOTICE file.
-
-   7. Disclaimer of Warranty. Unless required by applicable law or
-      agreed to in writing, Licensor provides the Work (and each
-      Contributor provides its Contributions) on an "AS IS" BASIS,
-      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-      implied, including, without limitation, any warranties or conditions
-      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
-      PARTICULAR PURPOSE. You are solely responsible for determining the
-      appropriateness of using or redistributing the Work and assume any
-      risks associated with Your exercise of permissions under this License.
-
-   8. Limitation of Liability. In no event and under no legal theory,
-      whether in tort (including negligence), contract, or otherwise,
-      unless required by applicable law (such as deliberate and grossly
-      negligent acts) or agreed to in writing, shall any Contributor be
-      liable to You for damages, including any direct, indirect, special,
-      incidental, or consequential damages of any character arising as a
-      result of this License or out of the use or inability to use the
-      Work (including but not limited to damages for loss of goodwill,
-      work stoppage, computer failure or malfunction, or any and all
-      other commercial damages or losses), even if such Contributor
-      has been advised of the possibility of such damages.
-
-   9. Accepting Warranty or Additional Liability. While redistributing
-      the Work or Derivative Works thereof, You may choose to offer,
-      and charge a fee for, acceptance of support, warranty, indemnity,
-      or other liability obligations and/or rights consistent with this
-      License. However, in accepting such obligations, You may act only
-      on Your own behalf and on Your sole responsibility, not on behalf
-      of any other Contributor, and only if You agree to indemnify,
-      defend, and hold each Contributor harmless for any liability
-      incurred by, or claims asserted against, such Contributor by reason
-      of your accepting any such warranty or additional liability.
-
-   END OF TERMS AND CONDITIONS
-
-   APPENDIX: How to apply the Apache License to your work.
-
-      To apply the Apache License to your work, attach the following
-      boilerplate notice, with the fields enclosed by brackets "{}"
-      replaced with your own identifying information. (Don't include
-      the brackets!)  The text should be enclosed in the appropriate
-      comment syntax for the file format. We also recommend that a
-      file or class name and description of purpose be included on the
-      same "printed page" as the copyright notice for easier
-      identification within third-party archives.
-
-   Copyright {yyyy} {name of copyright owner}
-
-   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
-
-       http://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.

+ 0 - 3
tools/tcpcpy/go.mod

@@ -1,3 +0,0 @@
-module imuslab.com/zoraxy/tcpcpy
-
-go 1.23.2

+ 0 - 61
tools/tcpcpy/main.go

@@ -1,61 +0,0 @@
-package main
-
-import (
-	"flag"
-	"fmt"
-	"net"
-	"os"
-)
-
-func main() {
-	//180.177.2.133 TW
-	//124.244.86.40 HK
-	ip := flag.String("ip", "180.177.2.133:62531", "IP address to send and receive UDP packets")
-	port := flag.Int("port", 8890, "Port to send and receive UDP packets")
-	flag.Parse()
-
-	if *ip == "" {
-		fmt.Println("IP address is required")
-		os.Exit(1)
-	}
-
-	addr := net.UDPAddr{
-		IP:   net.ParseIP(*ip),
-		Port: *port,
-	}
-
-	conn, err := net.DialUDP("udp", nil, &addr)
-	if err != nil {
-		fmt.Printf("Failed to connect to UDP server: %v\n", err)
-		os.Exit(1)
-	}
-	defer conn.Close()
-
-	localAddr := conn.LocalAddr().(*net.UDPAddr)
-	fmt.Printf("Local address: %s\n", localAddr.String())
-
-	message := []byte("Hello UDP Server")
-
-	go func() {
-		for {
-			_, err := conn.Write(message)
-			if err != nil {
-				fmt.Printf("Failed to send UDP packet: %v\n", err)
-				os.Exit(1)
-			}
-		}
-	}()
-
-	buffer := make([]byte, 1024)
-	for {
-		n, remoteAddr, err := conn.ReadFromUDP(buffer)
-		if err != nil {
-			fmt.Printf("Failed to read UDP packet: %v\n", err)
-			continue
-		}
-
-		if remoteAddr.IP.String() == *ip {
-			fmt.Printf("Received UDP packet from %s: %s\n", remoteAddr, string(buffer[:n]))
-		}
-	}
-}

BIN
tools/tcpcpy/tcpcpy.exe~


+ 5 - 0
tools/websocket_echo/go.mod

@@ -0,0 +1,5 @@
+module aroz.org/zoraxy/websocket-echo
+
+go 1.23.2
+
+require github.com/gorilla/websocket v1.5.3

+ 2 - 0
tools/websocket_echo/go.sum

@@ -0,0 +1,2 @@
+github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
+github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=

+ 44 - 0
tools/websocket_echo/main.go

@@ -0,0 +1,44 @@
+package main
+
+import (
+	"fmt"
+	"log"
+	"net/http"
+
+	"github.com/gorilla/websocket"
+)
+
+var upgrader = websocket.Upgrader{
+	CheckOrigin: func(r *http.Request) bool {
+		return true
+	},
+}
+
+func echo(w http.ResponseWriter, r *http.Request) {
+	conn, err := upgrader.Upgrade(w, r, nil)
+	if err != nil {
+		log.Println("Upgrade error:", err)
+		return
+	}
+	defer conn.Close()
+
+	for key, values := range r.Header {
+		for _, value := range values {
+			message := fmt.Sprintf("%s: %s", key, value)
+			if err := conn.WriteMessage(websocket.TextMessage, []byte(message)); err != nil {
+				log.Println("WriteMessage error:", err)
+				return
+			}
+		}
+	}
+
+	if err := conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")); err != nil {
+		log.Println("CloseMessage error:", err)
+		return
+	}
+}
+
+func main() {
+	http.HandleFunc("/echo", echo)
+	log.Fatal(http.ListenAndServe(":8888", nil))
+}

+ 67 - 0
tools/websocket_echo/test.html

@@ -0,0 +1,67 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>WebSocket Echo Test</title>
+</head>
+<body>
+    <h1>WebSocket Echo Test</h1>
+    <p>1. Go run main.go</p>
+    <p>2. Create a Zoraxy proxy rule (and add to hosts file) from ws.localhost (port 80) to 127.0.0.1:8888</p>
+    <p>3. Click the Connect button below to test if headers are correctly sent over</p>
+    <button id="connectBtn">Connect</button>
+    <button id="disconnectBtn" disabled>Disconnect</button>
+    <input type="text" id="messageInput" placeholder="Enter message">
+    <button id="sendBtn" disabled>Send</button>
+    <div id="output"></div>
+
+    <script>
+        let socket;
+        const connectBtn = document.getElementById('connectBtn');
+        const disconnectBtn = document.getElementById('disconnectBtn');
+        const sendBtn = document.getElementById('sendBtn');
+        const messageInput = document.getElementById('messageInput');
+        const output = document.getElementById('output');
+
+        connectBtn.addEventListener('click', () => {
+            output.innerHTML = '';
+            //socket = new WebSocket('ws://localhost:8888/echo');
+            socket = new WebSocket('ws://ws.localhost/echo');
+
+            socket.onopen = () => {
+                output.innerHTML += '<p>Connected to WebSocket server</p>';
+                connectBtn.disabled = true;
+                disconnectBtn.disabled = false;
+                sendBtn.disabled = false;
+            };
+
+            socket.onmessage = (event) => {
+                output.innerHTML += `<p>Received: ${event.data}</p>`;
+            };
+
+            socket.onclose = () => {
+                output.innerHTML += '<p>Disconnected from WebSocket server</p>';
+                connectBtn.disabled = false;
+                disconnectBtn.disabled = true;
+                sendBtn.disabled = true;
+            };
+
+            socket.onerror = (error) => {
+                output.innerHTML += `<p>Error: ${error.message}</p>`;
+            };
+        });
+
+        disconnectBtn.addEventListener('click', () => {
+            socket.close();
+        });
+
+        sendBtn.addEventListener('click', () => {
+            const message = messageInput.value;
+            socket.send(message);
+            output.innerHTML += `<p>Sent: ${message}</p>`;
+            messageInput.value = '';
+        });
+    </script>
+</body>
+</html>

+ 14 - 1
web/components/httprp.html

@@ -258,6 +258,13 @@
                 if (payload.UseStickySession){
                     useStickySessionChecked = "checked";
                 }
+
+                let enableUptimeMonitor = "";
+                //Note the config file store the uptime monitor as disable, so we need to reverse the logic
+                if (!payload.DisableUptimeMonitor){
+                    enableUptimeMonitor = "checked";
+                }
+
                 input = `<button class="ui basic compact tiny button" style="margin-left: 0.4em; margin-top: 1em;" onclick="editUpstreams('${uuid}');"><i class="grey server icon"></i> Edit Upstreams</button>
                 <div class="ui divider"></div>
                 <div class="ui checkbox" style="margin-top: 0.4em;">
@@ -265,7 +272,11 @@
                     <label>Use Sticky Session<br>
                         <small>Enable stick session on load balancing</small></label>
                 </div>
-
+                <div class="ui checkbox" style="margin-top: 0.4em;">
+                    <input type="checkbox" class="EnableUptimeMonitor" ${enableUptimeMonitor}>
+                    <label>Monitor Uptime<br>
+                        <small>Enable active uptime monitor</small></label>
+                </div>
                 `;
                 column.append(input);
                 $(column).find(".upstreamList").addClass("editing");
@@ -441,6 +452,7 @@
         
         var epttype = "host";
         let useStickySession =  $(row).find(".UseStickySession")[0].checked;
+        let DisableUptimeMonitor = !$(row).find(".EnableUptimeMonitor")[0].checked;
         let authProviderType = $(row).find(".authProviderPicker input[type='radio']:checked").val();
         let requireRateLimit = $(row).find(".RequireRateLimit")[0].checked;
         let rateLimit = $(row).find(".RateLimit").val();
@@ -453,6 +465,7 @@
                 "type": epttype,
                 "rootname": uuid,
                 "ss":useStickySession,
+                "dutm": DisableUptimeMonitor,
                 "bpgtls": bypassGlobalTLS,
                 "authprovider" :authProviderType,
                 "rate" :requireRateLimit,

+ 47 - 0
web/snippet/customHeaders.html

@@ -117,6 +117,16 @@
                                     <label>Remove Hop-by-hop Header<br>
                                     <small>This should be ON by default</small></label>
                                 </div>
+
+                                <div class="ui divider"></div>
+                                <h4> WebSocket Custom Headers</h4>
+                                <p>Copy custom headers from HTTP requests to WebSocket connections.
+                                    Might be required by some projects like MeshCentral.</p>
+                                <div class="ui toggle checkbox">
+                                    <input type="checkbox" id="copyCustomHeadersWS" name="">
+                                    <label>Enable WebSocket Custom Header<br>
+                                    <small>This should be OFF by default</small></label>
+                                </div>
                                 <div class="ui yellow message">
                                     <p><i class="exclamation triangle icon"></i>Settings in this section are for advanced users. Invalid settings might cause werid, unexpected behavior.</p>
                                 </div>
@@ -597,6 +607,7 @@
                 })
             }
 
+            /* Manual Hostname overwrite */
             function initManualHostOverwriteValue(){
                 $.get("/api/proxy/header/handleHostOverwrite?domain=" + editingEndpoint.ep, function(data){
                     if (data.error != undefined){
@@ -643,6 +654,42 @@
                 })
             }
             initHopByHopRemoverState();
+
+            /* WebSocket Custom Headers */
+            function initWebSocketCustomHeaderState(){
+                $.get("/api/proxy/header/handleWsHeaderBehavior?domain=" + editingEndpoint.ep, function(data){
+                    if (data.error != undefined){
+                        parent.msgbox(data.error);
+                    }else{
+                        if (data == true){
+                            $("#copyCustomHeadersWS").parent().checkbox("set checked");
+                        }else{
+                            $("#copyCustomHeadersWS").parent().checkbox("set unchecked");
+                        }
+                        
+                        //Bind event to the checkbox
+                        $("#copyCustomHeadersWS").on("change", function(evt){
+                            let isChecked = $(this)[0].checked;
+                            $.cjax({
+                                url: "/api/proxy/header/handleWsHeaderBehavior",
+                                method: "POST",
+                                data: {
+                                    "domain": editingEndpoint.ep,
+                                    "enable": isChecked,
+                                },
+                                success: function(data){
+                                    if (data.error != undefined){
+                                        parent.msgbox(data.error, false);
+                                    }else{
+                                        parent.msgbox("WebSocket Custom Header rule updated");
+                                    }
+                                }
+                            })
+                        })
+                    }
+                })
+            }
+            initWebSocketCustomHeaderState();
         </script>
     </body>
 </html>