mirror of
https://github.com/tobychui/zoraxy.git
synced 2025-07-10 16:21:45 +02:00
Compare commits
37 Commits
Author | SHA1 | Date | |
---|---|---|---|
a7285438af | |||
693dba07b7 | |||
9b64278200 | |||
d04eff2bda | |||
3320b56b19 | |||
99728144b3 | |||
05511ed4ca | |||
70abfe6fcf | |||
6ab91c377f | |||
1863af0d63 | |||
2a9d87787d | |||
f753becd66 | |||
bb2d0d5b46 | |||
07dc63a82c | |||
97a6cf016a | |||
8df68f1f4e | |||
e4ad505f2a | |||
a402c4f326 | |||
791fbfa1b4 | |||
c49f2fd1db | |||
7d9f240d56 | |||
e20f816080 | |||
eeb438eb18 | |||
bfd64a885e | |||
45f61b3053 | |||
0d4c71d0f6 | |||
d1e5581eea | |||
be5797c8a5 | |||
ebd316a7f1 | |||
84aec4387a | |||
30dfb9cb65 | |||
0b1768ab5b | |||
ad4721820b | |||
1d4c275db3 | |||
b3ad97743c | |||
1a6a87e79b | |||
749fd4b7af |
5
.gitignore
vendored
5
.gitignore
vendored
@ -40,3 +40,8 @@ src/www/html/index.html
|
|||||||
src/sys.uuid
|
src/sys.uuid
|
||||||
src/zoraxy
|
src/zoraxy
|
||||||
src/log/
|
src/log/
|
||||||
|
|
||||||
|
|
||||||
|
# dev-tags
|
||||||
|
/Dockerfile
|
||||||
|
/Entrypoint.sh
|
13
CHANGELOG.md
13
CHANGELOG.md
@ -1,3 +1,16 @@
|
|||||||
|
# v3.1.5 28 Dec 2024
|
||||||
|
|
||||||
|
+ Fixed hostname case sensitive bug [#435](https://github.com/tobychui/zoraxy/issues/435)
|
||||||
|
+ Fixed ACME table too wide css bug [#422](https://github.com/tobychui/zoraxy/issues/422)
|
||||||
|
+ Fixed HSTS toggle button bug [#415](https://github.com/tobychui/zoraxy/issues/415)
|
||||||
|
+ Fixed slow GeoIP resolve mode concurrent r/w bug [#401](https://github.com/tobychui/zoraxy/issues/401)
|
||||||
|
+ Added close connection as default site option [#430](https://github.com/tobychui/zoraxy/issues/430)
|
||||||
|
+ Added experimental authelia support [#384](https://github.com/tobychui/zoraxy/issues/384)
|
||||||
|
+ Added custom header support to websocket [#426](https://github.com/tobychui/zoraxy/issues/426)
|
||||||
|
+ Added levelDB as database implementation (not currently used)
|
||||||
|
+ Added external GeoIP db loading support
|
||||||
|
+ Restructured a lot of modules
|
||||||
|
|
||||||
# v3.1.4 24 Nov 2024
|
# v3.1.4 24 Nov 2024
|
||||||
|
|
||||||
+ **Added Dark Theme Mode** [#390](https://github.com/tobychui/zoraxy/issues/390) [#82](https://github.com/tobychui/zoraxy/issues/82)
|
+ **Added Dark Theme Mode** [#390](https://github.com/tobychui/zoraxy/issues/390) [#82](https://github.com/tobychui/zoraxy/issues/82)
|
||||||
|
@ -1,5 +1,14 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
trap cleanup TERM INT
|
||||||
|
|
||||||
|
cleanup() {
|
||||||
|
echo "Shutting down..."
|
||||||
|
kill -TERM "$(pidof zoraxy)" &> /dev/null && echo "Zoraxy stopped."
|
||||||
|
kill -TERM "$(pidof zerotier-one)" &> /dev/null && echo "ZeroTier-One stopped."
|
||||||
|
exit 0
|
||||||
|
}
|
||||||
|
|
||||||
update-ca-certificates
|
update-ca-certificates
|
||||||
echo "CA certificates updated."
|
echo "CA certificates updated."
|
||||||
|
|
||||||
@ -11,12 +20,13 @@ if [ "$ZEROTIER" = "true" ]; then
|
|||||||
mkdir -p /opt/zoraxy/config/zerotier/
|
mkdir -p /opt/zoraxy/config/zerotier/
|
||||||
fi
|
fi
|
||||||
ln -s /opt/zoraxy/config/zerotier/ /var/lib/zerotier-one
|
ln -s /opt/zoraxy/config/zerotier/ /var/lib/zerotier-one
|
||||||
zerotier-one -d
|
zerotier-one -d &
|
||||||
|
zerotierpid=$!
|
||||||
echo "ZeroTier daemon started."
|
echo "ZeroTier daemon started."
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo "Starting Zoraxy..."
|
echo "Starting Zoraxy..."
|
||||||
exec zoraxy \
|
zoraxy \
|
||||||
-autorenew="$AUTORENEW" \
|
-autorenew="$AUTORENEW" \
|
||||||
-cfgupgrade="$CFGUPGRADE" \
|
-cfgupgrade="$CFGUPGRADE" \
|
||||||
-db="$DB" \
|
-db="$DB" \
|
||||||
@ -33,5 +43,10 @@ exec zoraxy \
|
|||||||
-webfm="$WEBFM" \
|
-webfm="$WEBFM" \
|
||||||
-webroot="$WEBROOT" \
|
-webroot="$WEBROOT" \
|
||||||
-ztauth="$ZTAUTH" \
|
-ztauth="$ZTAUTH" \
|
||||||
-ztport="$ZTPORT"
|
-ztport="$ZTPORT" \
|
||||||
|
&
|
||||||
|
|
||||||
|
zoraxypid=$!
|
||||||
|
wait $zoraxypid
|
||||||
|
wait $zerotierpid
|
||||||
|
|
||||||
|
@ -59,6 +59,7 @@ func RegisterHTTPProxyAPIs(authRouter *auth.RouterDef) {
|
|||||||
authRouter.HandleFunc("/api/proxy/header/handleHopByHop", HandleHopByHop)
|
authRouter.HandleFunc("/api/proxy/header/handleHopByHop", HandleHopByHop)
|
||||||
authRouter.HandleFunc("/api/proxy/header/handleHostOverwrite", HandleHostOverwrite)
|
authRouter.HandleFunc("/api/proxy/header/handleHostOverwrite", HandleHostOverwrite)
|
||||||
authRouter.HandleFunc("/api/proxy/header/handlePermissionPolicy", HandlePermissionPolicy)
|
authRouter.HandleFunc("/api/proxy/header/handlePermissionPolicy", HandlePermissionPolicy)
|
||||||
|
authRouter.HandleFunc("/api/proxy/header/handleWsHeaderBehavior", HandleWsHeaderBehavior)
|
||||||
/* Reverse proxy auth related */
|
/* Reverse proxy auth related */
|
||||||
authRouter.HandleFunc("/api/proxy/auth/exceptions/list", ListProxyBasicAuthExceptionPaths)
|
authRouter.HandleFunc("/api/proxy/auth/exceptions/list", ListProxyBasicAuthExceptionPaths)
|
||||||
authRouter.HandleFunc("/api/proxy/auth/exceptions/add", AddProxyBasicAuthExceptionPaths)
|
authRouter.HandleFunc("/api/proxy/auth/exceptions/add", AddProxyBasicAuthExceptionPaths)
|
||||||
@ -87,6 +88,7 @@ func RegisterRedirectionAPIs(authRouter *auth.RouterDef) {
|
|||||||
authRouter.HandleFunc("/api/redirect/list", handleListRedirectionRules)
|
authRouter.HandleFunc("/api/redirect/list", handleListRedirectionRules)
|
||||||
authRouter.HandleFunc("/api/redirect/add", handleAddRedirectionRule)
|
authRouter.HandleFunc("/api/redirect/add", handleAddRedirectionRule)
|
||||||
authRouter.HandleFunc("/api/redirect/delete", handleDeleteRedirectionRule)
|
authRouter.HandleFunc("/api/redirect/delete", handleDeleteRedirectionRule)
|
||||||
|
authRouter.HandleFunc("/api/redirect/edit", handleEditRedirectionRule)
|
||||||
authRouter.HandleFunc("/api/redirect/regex", handleToggleRedirectRegexpSupport)
|
authRouter.HandleFunc("/api/redirect/regex", handleToggleRedirectRegexpSupport)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -48,12 +48,17 @@ func LoadReverseProxyConfig(configFilepath string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//Parse it into dynamic proxy endpoint
|
//Parse it into dynamic proxy endpoint
|
||||||
thisConfigEndpoint := dynamicproxy.ProxyEndpoint{}
|
thisConfigEndpoint := dynamicproxy.GetDefaultProxyEndpoint()
|
||||||
err = json.Unmarshal(endpointConfig, &thisConfigEndpoint)
|
err = json.Unmarshal(endpointConfig, &thisConfigEndpoint)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//Make sure the tags are not nil
|
||||||
|
if thisConfigEndpoint.Tags == nil {
|
||||||
|
thisConfigEndpoint.Tags = []string{}
|
||||||
|
}
|
||||||
|
|
||||||
//Matching domain not set. Assume root
|
//Matching domain not set. Assume root
|
||||||
if thisConfigEndpoint.RootOrMatchingDomain == "" {
|
if thisConfigEndpoint.RootOrMatchingDomain == "" {
|
||||||
thisConfigEndpoint.RootOrMatchingDomain = "/"
|
thisConfigEndpoint.RootOrMatchingDomain = "/"
|
||||||
@ -129,31 +134,23 @@ func RemoveReverseProxyConfig(endpoint string) error {
|
|||||||
// Get the default root config that point to the internal static web server
|
// Get the default root config that point to the internal static web server
|
||||||
// this will be used if root config is not found (new deployment / missing root.config file)
|
// this will be used if root config is not found (new deployment / missing root.config file)
|
||||||
func GetDefaultRootConfig() (*dynamicproxy.ProxyEndpoint, error) {
|
func GetDefaultRootConfig() (*dynamicproxy.ProxyEndpoint, error) {
|
||||||
//Default Authentication Provider
|
//Get the default proxy endpoint
|
||||||
defaultAuth := &dynamicproxy.AuthenticationProvider{
|
rootProxyEndpointConfig := dynamicproxy.GetDefaultProxyEndpoint()
|
||||||
AuthMethod: dynamicproxy.AuthMethodNone,
|
rootProxyEndpointConfig.ProxyType = dynamicproxy.ProxyTypeRoot
|
||||||
BasicAuthCredentials: []*dynamicproxy.BasicAuthCredentials{},
|
rootProxyEndpointConfig.RootOrMatchingDomain = "/"
|
||||||
BasicAuthExceptionRules: []*dynamicproxy.BasicAuthExceptionRule{},
|
rootProxyEndpointConfig.ActiveOrigins = []*loadbalance.Upstream{
|
||||||
}
|
|
||||||
//Default settings
|
|
||||||
rootProxyEndpoint, err := dynamicProxyRouter.PrepareProxyRoute(&dynamicproxy.ProxyEndpoint{
|
|
||||||
ProxyType: dynamicproxy.ProxyTypeRoot,
|
|
||||||
RootOrMatchingDomain: "/",
|
|
||||||
ActiveOrigins: []*loadbalance.Upstream{
|
|
||||||
{
|
{
|
||||||
OriginIpOrDomain: "127.0.0.1:" + staticWebServer.GetListeningPort(),
|
OriginIpOrDomain: "127.0.0.1:" + staticWebServer.GetListeningPort(),
|
||||||
RequireTLS: false,
|
RequireTLS: false,
|
||||||
SkipCertValidations: false,
|
SkipCertValidations: false,
|
||||||
Weight: 0,
|
Weight: 0,
|
||||||
},
|
},
|
||||||
},
|
}
|
||||||
InactiveOrigins: []*loadbalance.Upstream{},
|
rootProxyEndpointConfig.DefaultSiteOption = dynamicproxy.DefaultSite_InternalStaticWebServer
|
||||||
BypassGlobalTLS: false,
|
rootProxyEndpointConfig.DefaultSiteValue = ""
|
||||||
VirtualDirectories: []*dynamicproxy.VirtualDirectoryEndpoint{},
|
|
||||||
AuthenticationProvider: defaultAuth,
|
//Default settings
|
||||||
DefaultSiteOption: dynamicproxy.DefaultSite_InternalStaticWebServer,
|
rootProxyEndpoint, err := dynamicProxyRouter.PrepareProxyRoute(&rootProxyEndpointConfig)
|
||||||
DefaultSiteValue: "",
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -175,12 +172,16 @@ func ExportConfigAsZip(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Specify the folder path to be zipped
|
// Specify the folder path to be zipped
|
||||||
folderPath := "./conf/"
|
if !utils.FileExists("./conf") {
|
||||||
|
SystemWideLogger.PrintAndLog("Backup", "Configuration folder not found", nil)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
folderPath := "./conf"
|
||||||
|
|
||||||
// Set the Content-Type header to indicate it's a zip file
|
// Set the Content-Type header to indicate it's a zip file
|
||||||
w.Header().Set("Content-Type", "application/zip")
|
w.Header().Set("Content-Type", "application/zip")
|
||||||
// Set the Content-Disposition header to specify the file name
|
// Set the Content-Disposition header to specify the file name, add timestamp to the filename
|
||||||
w.Header().Set("Content-Disposition", "attachment; filename=\"config.zip\"")
|
w.Header().Set("Content-Disposition", "attachment; filename=\"zoraxy-config-"+time.Now().Format("2006-01-02-15-04-05")+".zip\"")
|
||||||
|
|
||||||
// Create a zip writer
|
// Create a zip writer
|
||||||
zipWriter := zip.NewWriter(w)
|
zipWriter := zip.NewWriter(w)
|
||||||
@ -230,7 +231,7 @@ func ExportConfigAsZip(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Open the file on disk
|
// Open the file on disk
|
||||||
file, err := os.Open("sys.db")
|
file, err := os.Open("./sys.db")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
SystemWideLogger.PrintAndLog("Backup", "Unable to open sysdb", err)
|
SystemWideLogger.PrintAndLog("Backup", "Unable to open sysdb", err)
|
||||||
return
|
return
|
||||||
@ -279,6 +280,8 @@ func ImportConfigFromZip(w http.ResponseWriter, r *http.Request) {
|
|||||||
targetDir := "./conf"
|
targetDir := "./conf"
|
||||||
if utils.FileExists(targetDir) {
|
if utils.FileExists(targetDir) {
|
||||||
//Backup the old config to old
|
//Backup the old config to old
|
||||||
|
//backupPath := filepath.Dir(*path_conf) + filepath.Base(*path_conf) + ".old_" + strconv.Itoa(int(time.Now().Unix()))
|
||||||
|
//os.Rename(*path_conf, backupPath)
|
||||||
os.Rename("./conf", "./conf.old_"+strconv.Itoa(int(time.Now().Unix())))
|
os.Rename("./conf", "./conf.old_"+strconv.Itoa(int(time.Now().Unix())))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
16
src/def.go
16
src/def.go
@ -42,11 +42,10 @@ import (
|
|||||||
const (
|
const (
|
||||||
/* Build Constants */
|
/* Build Constants */
|
||||||
SYSTEM_NAME = "Zoraxy"
|
SYSTEM_NAME = "Zoraxy"
|
||||||
SYSTEM_VERSION = "3.1.5"
|
SYSTEM_VERSION = "3.1.7"
|
||||||
DEVELOPMENT_BUILD = false /* Development: Set to false to use embedded web fs */
|
DEVELOPMENT_BUILD = false /* Development: Set to false to use embedded web fs */
|
||||||
|
|
||||||
/* System Constants */
|
/* System Constants */
|
||||||
DATABASE_PATH = "sys.db"
|
|
||||||
TMP_FOLDER = "./tmp"
|
TMP_FOLDER = "./tmp"
|
||||||
WEBSERV_DEFAULT_PORT = 5487
|
WEBSERV_DEFAULT_PORT = 5487
|
||||||
MDNS_HOSTNAME_PREFIX = "zoraxy_" /* Follow by node UUID */
|
MDNS_HOSTNAME_PREFIX = "zoraxy_" /* Follow by node UUID */
|
||||||
@ -59,7 +58,6 @@ const (
|
|||||||
ACME_AUTORENEW_CONFIG_PATH = "./conf/acme_conf.json"
|
ACME_AUTORENEW_CONFIG_PATH = "./conf/acme_conf.json"
|
||||||
CSRF_COOKIENAME = "zoraxy_csrf"
|
CSRF_COOKIENAME = "zoraxy_csrf"
|
||||||
LOG_PREFIX = "zr"
|
LOG_PREFIX = "zr"
|
||||||
LOG_FOLDER = "./log"
|
|
||||||
LOG_EXTENSION = ".log"
|
LOG_EXTENSION = ".log"
|
||||||
|
|
||||||
/* Configuration Folder Storage Path Constants */
|
/* Configuration Folder Storage Path Constants */
|
||||||
@ -86,10 +84,20 @@ var (
|
|||||||
acmeAutoRenewInterval = flag.Int("autorenew", 86400, "ACME auto TLS/SSL certificate renew check interval (seconds)")
|
acmeAutoRenewInterval = flag.Int("autorenew", 86400, "ACME auto TLS/SSL certificate renew check interval (seconds)")
|
||||||
acmeCertAutoRenewDays = flag.Int("earlyrenew", 30, "Number of days to early renew a soon expiring certificate (days)")
|
acmeCertAutoRenewDays = flag.Int("earlyrenew", 30, "Number of days to early renew a soon expiring certificate (days)")
|
||||||
enableHighSpeedGeoIPLookup = flag.Bool("fastgeoip", false, "Enable high speed geoip lookup, require 1GB extra memory (Not recommend for low end devices)")
|
enableHighSpeedGeoIPLookup = flag.Bool("fastgeoip", false, "Enable high speed geoip lookup, require 1GB extra memory (Not recommend for low end devices)")
|
||||||
staticWebServerRoot = flag.String("webroot", "./www", "Static web server root folder. Only allow chnage in start paramters")
|
|
||||||
allowWebFileManager = flag.Bool("webfm", true, "Enable web file manager for static web server root folder")
|
allowWebFileManager = flag.Bool("webfm", true, "Enable web file manager for static web server root folder")
|
||||||
enableAutoUpdate = flag.Bool("cfgupgrade", true, "Enable auto config upgrade if breaking change is detected")
|
enableAutoUpdate = flag.Bool("cfgupgrade", true, "Enable auto config upgrade if breaking change is detected")
|
||||||
|
|
||||||
|
/* Default Configuration Flags */
|
||||||
|
defaultInboundPort = flag.Int("default_inbound_port", 443, "Default web server listening port")
|
||||||
|
defaultEnableInboundTraffic = flag.Bool("default_inbound_enabled", true, "If web server is enabled by default")
|
||||||
|
|
||||||
|
/* Path Configuration Flags */
|
||||||
|
//path_database = flag.String("dbpath", "./sys.db", "Database path")
|
||||||
|
//path_conf = flag.String("conf", "./conf", "Configuration folder path")
|
||||||
|
path_uuid = flag.String("uuid", "./sys.uuid", "sys.uuid file path")
|
||||||
|
path_logFile = flag.String("log", "./log", "Log folder path")
|
||||||
|
path_webserver = flag.String("webroot", "./www", "Static web server root folder. Only allow change in start paramters")
|
||||||
|
|
||||||
/* Maintaince Function Flags */
|
/* Maintaince Function Flags */
|
||||||
geoDbUpdate = flag.Bool("update_geoip", false, "Download the latest GeoIP data and exit")
|
geoDbUpdate = flag.Bool("update_geoip", false, "Download the latest GeoIP data and exit")
|
||||||
)
|
)
|
||||||
|
@ -86,7 +86,7 @@ func main() {
|
|||||||
SetupCloseHandler()
|
SetupCloseHandler()
|
||||||
|
|
||||||
//Read or create the system uuid
|
//Read or create the system uuid
|
||||||
uuidRecord := "./sys.uuid"
|
uuidRecord := *path_uuid
|
||||||
if !utils.FileExists(uuidRecord) {
|
if !utils.FileExists(uuidRecord) {
|
||||||
newSystemUUID := uuid.New().String()
|
newSystemUUID := uuid.New().String()
|
||||||
os.WriteFile(uuidRecord, []byte(newSystemUUID), 0775)
|
os.WriteFile(uuidRecord, []byte(newSystemUUID), 0775)
|
||||||
|
@ -209,23 +209,18 @@ func (h *ProxyHandler) handleRootRouting(w http.ResponseWriter, r *http.Request)
|
|||||||
http.Redirect(w, r, redirectTarget, http.StatusTemporaryRedirect)
|
http.Redirect(w, r, redirectTarget, http.StatusTemporaryRedirect)
|
||||||
case DefaultSite_NotFoundPage:
|
case DefaultSite_NotFoundPage:
|
||||||
//Serve the not found page, use template if exists
|
//Serve the not found page, use template if exists
|
||||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
h.serve404PageWithTemplate(w, r)
|
||||||
w.WriteHeader(http.StatusNotFound)
|
|
||||||
template, err := os.ReadFile(filepath.Join(h.Parent.Option.WebDirectory, "templates/notfound.html"))
|
|
||||||
if err != nil {
|
|
||||||
w.Write(page_hosterror)
|
|
||||||
} else {
|
|
||||||
w.Write(template)
|
|
||||||
}
|
|
||||||
case DefaultSite_NoResponse:
|
case DefaultSite_NoResponse:
|
||||||
//No response. Just close the connection
|
//No response. Just close the connection
|
||||||
h.Parent.logRequest(r, false, 444, "root-noresponse", domainOnly)
|
h.Parent.logRequest(r, false, 444, "root-no_resp", domainOnly)
|
||||||
hijacker, ok := w.(http.Hijacker)
|
hijacker, ok := w.(http.Hijacker)
|
||||||
if !ok {
|
if !ok {
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
conn, _, err := hijacker.Hijack()
|
conn, _, err := hijacker.Hijack()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
conn.Close()
|
conn.Close()
|
||||||
@ -239,3 +234,15 @@ func (h *ProxyHandler) handleRootRouting(w http.ResponseWriter, r *http.Request)
|
|||||||
http.Error(w, "544 - No Route Defined", 544)
|
http.Error(w, "544 - No Route Defined", 544)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Serve 404 page with template if exists
|
||||||
|
func (h *ProxyHandler) serve404PageWithTemplate(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
template, err := os.ReadFile(filepath.Join(h.Parent.Option.WebDirectory, "templates/notfound.html"))
|
||||||
|
if err != nil {
|
||||||
|
w.Write(page_hosterror)
|
||||||
|
} else {
|
||||||
|
w.Write(template)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
65
src/mod/dynamicproxy/default.go
Normal file
65
src/mod/dynamicproxy/default.go
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
package dynamicproxy
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"imuslab.com/zoraxy/mod/dynamicproxy/loadbalance"
|
||||||
|
"imuslab.com/zoraxy/mod/dynamicproxy/rewrite"
|
||||||
|
)
|
||||||
|
|
||||||
|
/*
|
||||||
|
Default Provider
|
||||||
|
|
||||||
|
This script provide the default options for all datatype
|
||||||
|
provided by dynamicproxy module
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
// GetDefaultAuthenticationProvider return a default authentication provider
|
||||||
|
func GetDefaultAuthenticationProvider() *AuthenticationProvider {
|
||||||
|
return &AuthenticationProvider{
|
||||||
|
AuthMethod: AuthMethodNone,
|
||||||
|
BasicAuthCredentials: []*BasicAuthCredentials{},
|
||||||
|
BasicAuthExceptionRules: []*BasicAuthExceptionRule{},
|
||||||
|
BasicAuthGroupIDs: []string{},
|
||||||
|
AutheliaURL: "",
|
||||||
|
UseHTTPS: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetDefaultHeaderRewriteRules return a default header rewrite rules
|
||||||
|
func GetDefaultHeaderRewriteRules() *HeaderRewriteRules {
|
||||||
|
return &HeaderRewriteRules{
|
||||||
|
UserDefinedHeaders: []*rewrite.UserDefinedHeader{},
|
||||||
|
RequestHostOverwrite: "",
|
||||||
|
HSTSMaxAge: 0,
|
||||||
|
EnablePermissionPolicyHeader: false,
|
||||||
|
PermissionPolicy: nil,
|
||||||
|
DisableHopByHopHeaderRemoval: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetDefaultProxyEndpoint return a default proxy endpoint
|
||||||
|
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(),
|
||||||
|
EnableWebsocketCustomHeaders: false,
|
||||||
|
AuthenticationProvider: GetDefaultAuthenticationProvider(),
|
||||||
|
RequireRateLimit: false,
|
||||||
|
RateLimit: 0,
|
||||||
|
DisableUptimeMonitor: false,
|
||||||
|
AccessFilterUUID: "default",
|
||||||
|
DefaultSiteOption: DefaultSite_InternalStaticWebServer,
|
||||||
|
DefaultSiteValue: "",
|
||||||
|
}
|
||||||
|
}
|
@ -99,6 +99,23 @@ func DomainUsesTLS(targetURL string) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
WebSocket Header Sniff
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Check if the requst is a special case where
|
||||||
|
// user defined header shall not be passed over
|
||||||
|
|
||||||
|
func RequireWebsocketHeaderCopy(r *http.Request) bool {
|
||||||
|
//Return false for proxmox
|
||||||
|
if IsProxmox(r) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
//Add more edge cases here
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Request Handlers
|
Request Handlers
|
||||||
*/
|
*/
|
||||||
|
@ -17,5 +17,6 @@ func IsProxmox(r *http.Request) bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
@ -2,6 +2,7 @@ package dpcore
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
"errors"
|
"errors"
|
||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
@ -11,6 +12,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"golang.org/x/net/http2"
|
||||||
"imuslab.com/zoraxy/mod/dynamicproxy/domainsniff"
|
"imuslab.com/zoraxy/mod/dynamicproxy/domainsniff"
|
||||||
"imuslab.com/zoraxy/mod/dynamicproxy/permissionpolicy"
|
"imuslab.com/zoraxy/mod/dynamicproxy/permissionpolicy"
|
||||||
)
|
)
|
||||||
@ -84,6 +86,7 @@ type requestCanceler interface {
|
|||||||
type DpcoreOptions struct {
|
type DpcoreOptions struct {
|
||||||
IgnoreTLSVerification bool //Disable all TLS verification when request pass through this proxy router
|
IgnoreTLSVerification bool //Disable all TLS verification when request pass through this proxy router
|
||||||
FlushInterval time.Duration //Duration to flush in normal requests. Stream request or keep-alive request will always flush with interval of -1 (immediately)
|
FlushInterval time.Duration //Duration to flush in normal requests. Stream request or keep-alive request will always flush with interval of -1 (immediately)
|
||||||
|
UseH2CRoundTripper bool //Use H2C RoundTripper for HTTP/2.0 connection
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewDynamicProxyCore(target *url.URL, prepender string, dpcOptions *DpcoreOptions) *ReverseProxy {
|
func NewDynamicProxyCore(target *url.URL, prepender string, dpcOptions *DpcoreOptions) *ReverseProxy {
|
||||||
@ -100,8 +103,17 @@ func NewDynamicProxyCore(target *url.URL, prepender string, dpcOptions *DpcoreOp
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//Hack the default transporter to handle more connections
|
|
||||||
thisTransporter := http.DefaultTransport
|
thisTransporter := http.DefaultTransport
|
||||||
|
if dpcOptions.UseH2CRoundTripper {
|
||||||
|
thisTransporter = &http2.Transport{
|
||||||
|
DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
|
||||||
|
return net.Dial(network, addr)
|
||||||
|
},
|
||||||
|
AllowHTTP: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//Hack the default transporter to handle more connections
|
||||||
optimalConcurrentConnection := 32
|
optimalConcurrentConnection := 32
|
||||||
thisTransporter.(*http.Transport).MaxIdleConns = optimalConcurrentConnection * 2
|
thisTransporter.(*http.Transport).MaxIdleConns = optimalConcurrentConnection * 2
|
||||||
thisTransporter.(*http.Transport).MaxIdleConnsPerHost = optimalConcurrentConnection
|
thisTransporter.(*http.Transport).MaxIdleConnsPerHost = optimalConcurrentConnection
|
||||||
|
@ -157,12 +157,18 @@ func (router *Router) StartProxyService() error {
|
|||||||
router.Option.Logger.PrintAndLog("dprouter", "failed to get upstream for hostname", err)
|
router.Option.Logger.PrintAndLog("dprouter", "failed to get upstream for hostname", err)
|
||||||
router.logRequest(r, false, 404, "vdir-http", r.Host)
|
router.logRequest(r, false, 404, "vdir-http", r.Host)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
endpointProxyRewriteRules := GetDefaultHeaderRewriteRules()
|
||||||
|
if sep.HeaderRewriteRules != nil {
|
||||||
|
endpointProxyRewriteRules = sep.HeaderRewriteRules
|
||||||
|
}
|
||||||
|
|
||||||
selectedUpstream.ServeHTTP(w, r, &dpcore.ResponseRewriteRuleSet{
|
selectedUpstream.ServeHTTP(w, r, &dpcore.ResponseRewriteRuleSet{
|
||||||
ProxyDomain: selectedUpstream.OriginIpOrDomain,
|
ProxyDomain: selectedUpstream.OriginIpOrDomain,
|
||||||
OriginalHost: originalHostHeader,
|
OriginalHost: originalHostHeader,
|
||||||
UseTLS: selectedUpstream.RequireTLS,
|
UseTLS: selectedUpstream.RequireTLS,
|
||||||
HostHeaderOverwrite: sep.HeaderRewriteRules.RequestHostOverwrite,
|
HostHeaderOverwrite: endpointProxyRewriteRules.RequestHostOverwrite,
|
||||||
NoRemoveHopByHop: sep.HeaderRewriteRules.DisableHopByHopHeaderRemoval,
|
NoRemoveHopByHop: endpointProxyRewriteRules.DisableHopByHopHeaderRemoval,
|
||||||
PathPrefix: "",
|
PathPrefix: "",
|
||||||
Version: sep.parent.Option.HostVersion,
|
Version: sep.parent.Option.HostVersion,
|
||||||
})
|
})
|
||||||
@ -185,11 +191,28 @@ func (router *Router) StartProxyService() error {
|
|||||||
w.Write([]byte("400 - Bad Request"))
|
w.Write([]byte("400 - Bad Request"))
|
||||||
} else {
|
} else {
|
||||||
//No defined sub-domain
|
//No defined sub-domain
|
||||||
|
if router.Root.DefaultSiteOption == DefaultSite_NoResponse {
|
||||||
|
//No response. Just close the connection
|
||||||
|
hijacker, ok := w.(http.Hijacker)
|
||||||
|
if !ok {
|
||||||
|
w.Header().Set("Connection", "close")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
conn, _, err := hijacker.Hijack()
|
||||||
|
if err != nil {
|
||||||
|
w.Header().Set("Connection", "close")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
conn.Close()
|
||||||
|
} else {
|
||||||
|
//Default behavior
|
||||||
http.NotFound(w, r)
|
http.NotFound(w, r)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
}),
|
}),
|
||||||
ReadTimeout: 3 * time.Second,
|
ReadTimeout: 3 * time.Second,
|
||||||
WriteTimeout: 3 * time.Second,
|
WriteTimeout: 3 * time.Second,
|
||||||
@ -331,7 +354,7 @@ func (router *Router) LoadProxy(matchingDomain string) (*ProxyEndpoint, error) {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
if key == matchingDomain {
|
if key == strings.ToLower(matchingDomain) {
|
||||||
targetProxyEndpoint = v
|
targetProxyEndpoint = v
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
|
@ -27,7 +27,12 @@ import (
|
|||||||
|
|
||||||
// Check if a user define header exists in this endpoint, ignore case
|
// Check if a user define header exists in this endpoint, ignore case
|
||||||
func (ep *ProxyEndpoint) UserDefinedHeaderExists(key string) bool {
|
func (ep *ProxyEndpoint) UserDefinedHeaderExists(key string) bool {
|
||||||
for _, header := range ep.HeaderRewriteRules.UserDefinedHeaders {
|
endpointProxyRewriteRules := GetDefaultHeaderRewriteRules()
|
||||||
|
if ep.HeaderRewriteRules != nil {
|
||||||
|
endpointProxyRewriteRules = ep.HeaderRewriteRules
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, header := range endpointProxyRewriteRules.UserDefinedHeaders {
|
||||||
if strings.EqualFold(header.Key, key) {
|
if strings.EqualFold(header.Key, key) {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@ -38,6 +43,9 @@ func (ep *ProxyEndpoint) UserDefinedHeaderExists(key string) bool {
|
|||||||
// Remvoe a user defined header from the list
|
// Remvoe a user defined header from the list
|
||||||
func (ep *ProxyEndpoint) RemoveUserDefinedHeader(key string) error {
|
func (ep *ProxyEndpoint) RemoveUserDefinedHeader(key string) error {
|
||||||
newHeaderList := []*rewrite.UserDefinedHeader{}
|
newHeaderList := []*rewrite.UserDefinedHeader{}
|
||||||
|
if ep.HeaderRewriteRules == nil {
|
||||||
|
ep.HeaderRewriteRules = GetDefaultHeaderRewriteRules()
|
||||||
|
}
|
||||||
for _, header := range ep.HeaderRewriteRules.UserDefinedHeaders {
|
for _, header := range ep.HeaderRewriteRules.UserDefinedHeaders {
|
||||||
if !strings.EqualFold(header.Key, key) {
|
if !strings.EqualFold(header.Key, key) {
|
||||||
newHeaderList = append(newHeaderList, header)
|
newHeaderList = append(newHeaderList, header)
|
||||||
@ -55,6 +63,9 @@ func (ep *ProxyEndpoint) AddUserDefinedHeader(newHeaderRule *rewrite.UserDefined
|
|||||||
ep.RemoveUserDefinedHeader(newHeaderRule.Key)
|
ep.RemoveUserDefinedHeader(newHeaderRule.Key)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ep.HeaderRewriteRules == nil {
|
||||||
|
ep.HeaderRewriteRules = GetDefaultHeaderRewriteRules()
|
||||||
|
}
|
||||||
newHeaderRule.Key = cases.Title(language.Und, cases.NoLower).String(newHeaderRule.Key)
|
newHeaderRule.Key = cases.Title(language.Und, cases.NoLower).String(newHeaderRule.Key)
|
||||||
ep.HeaderRewriteRules.UserDefinedHeaders = append(ep.HeaderRewriteRules.UserDefinedHeaders, newHeaderRule)
|
ep.HeaderRewriteRules.UserDefinedHeaders = append(ep.HeaderRewriteRules.UserDefinedHeaders, newHeaderRule)
|
||||||
return nil
|
return nil
|
||||||
@ -106,7 +117,7 @@ func (ep *ProxyEndpoint) RemoveVirtualDirectoryRuleByMatchingPath(matchingPath s
|
|||||||
return errors.New("target virtual directory routing rule not found")
|
return errors.New("target virtual directory routing rule not found")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete a vdir rule by its matching path
|
// Add a vdir rule by its matching path
|
||||||
func (ep *ProxyEndpoint) AddVirtualDirectoryRule(vdir *VirtualDirectoryEndpoint) (*ProxyEndpoint, error) {
|
func (ep *ProxyEndpoint) AddVirtualDirectoryRule(vdir *VirtualDirectoryEndpoint) (*ProxyEndpoint, error) {
|
||||||
//Check for matching path duplicate
|
//Check for matching path duplicate
|
||||||
if ep.GetVirtualDirectoryRuleByMatchingPath(vdir.MatchingPath) != nil {
|
if ep.GetVirtualDirectoryRuleByMatchingPath(vdir.MatchingPath) != nil {
|
||||||
@ -256,7 +267,8 @@ func (ep *ProxyEndpoint) Clone() *ProxyEndpoint {
|
|||||||
|
|
||||||
// Remove this proxy endpoint from running proxy endpoint list
|
// Remove this proxy endpoint from running proxy endpoint list
|
||||||
func (ep *ProxyEndpoint) Remove() error {
|
func (ep *ProxyEndpoint) Remove() error {
|
||||||
ep.parent.ProxyEndpoints.Delete(ep.RootOrMatchingDomain)
|
lookupHostname := strings.ToLower(ep.RootOrMatchingDomain)
|
||||||
|
ep.parent.ProxyEndpoints.Delete(lookupHostname)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -10,6 +10,7 @@ import (
|
|||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"imuslab.com/zoraxy/mod/dynamicproxy/domainsniff"
|
||||||
"imuslab.com/zoraxy/mod/dynamicproxy/dpcore"
|
"imuslab.com/zoraxy/mod/dynamicproxy/dpcore"
|
||||||
"imuslab.com/zoraxy/mod/dynamicproxy/rewrite"
|
"imuslab.com/zoraxy/mod/dynamicproxy/rewrite"
|
||||||
"imuslab.com/zoraxy/mod/netutils"
|
"imuslab.com/zoraxy/mod/netutils"
|
||||||
@ -143,10 +144,15 @@ func (h *ProxyHandler) hostRequest(w http.ResponseWriter, r *http.Request, targe
|
|||||||
u, _ = url.Parse("wss://" + wsRedirectionEndpoint + requestURL)
|
u, _ = url.Parse("wss://" + wsRedirectionEndpoint + requestURL)
|
||||||
}
|
}
|
||||||
h.Parent.logRequest(r, true, 101, "host-websocket", selectedUpstream.OriginIpOrDomain)
|
h.Parent.logRequest(r, true, 101, "host-websocket", selectedUpstream.OriginIpOrDomain)
|
||||||
|
|
||||||
|
if target.HeaderRewriteRules == nil {
|
||||||
|
target.HeaderRewriteRules = GetDefaultHeaderRewriteRules()
|
||||||
|
}
|
||||||
|
|
||||||
wspHandler := websocketproxy.NewProxy(u, websocketproxy.Options{
|
wspHandler := websocketproxy.NewProxy(u, websocketproxy.Options{
|
||||||
SkipTLSValidation: selectedUpstream.SkipCertValidations,
|
SkipTLSValidation: selectedUpstream.SkipCertValidations,
|
||||||
SkipOriginCheck: selectedUpstream.SkipWebSocketOriginCheck,
|
SkipOriginCheck: selectedUpstream.SkipWebSocketOriginCheck,
|
||||||
CopyAllHeaders: true,
|
CopyAllHeaders: target.EnableWebsocketCustomHeaders,
|
||||||
UserDefinedHeaders: target.HeaderRewriteRules.UserDefinedHeaders,
|
UserDefinedHeaders: target.HeaderRewriteRules.UserDefinedHeaders,
|
||||||
Logger: h.Parent.Option.Logger,
|
Logger: h.Parent.Option.Logger,
|
||||||
})
|
})
|
||||||
@ -163,15 +169,19 @@ func (h *ProxyHandler) hostRequest(w http.ResponseWriter, r *http.Request, targe
|
|||||||
}
|
}
|
||||||
|
|
||||||
//Populate the user-defined headers with the values from the request
|
//Populate the user-defined headers with the values from the request
|
||||||
rewrittenUserDefinedHeaders := rewrite.PopulateRequestHeaderVariables(r, target.HeaderRewriteRules.UserDefinedHeaders)
|
headerRewriteOptions := GetDefaultHeaderRewriteRules()
|
||||||
|
if target.HeaderRewriteRules != nil {
|
||||||
|
headerRewriteOptions = target.HeaderRewriteRules
|
||||||
|
}
|
||||||
|
rewrittenUserDefinedHeaders := rewrite.PopulateRequestHeaderVariables(r, headerRewriteOptions.UserDefinedHeaders)
|
||||||
|
|
||||||
//Build downstream and upstream header rules
|
//Build downstream and upstream header rules
|
||||||
upstreamHeaders, downstreamHeaders := rewrite.SplitUpDownStreamHeaders(&rewrite.HeaderRewriteOptions{
|
upstreamHeaders, downstreamHeaders := rewrite.SplitUpDownStreamHeaders(&rewrite.HeaderRewriteOptions{
|
||||||
UserDefinedHeaders: rewrittenUserDefinedHeaders,
|
UserDefinedHeaders: rewrittenUserDefinedHeaders,
|
||||||
HSTSMaxAge: target.HeaderRewriteRules.HSTSMaxAge,
|
HSTSMaxAge: headerRewriteOptions.HSTSMaxAge,
|
||||||
HSTSIncludeSubdomains: target.ContainsWildcardName(true),
|
HSTSIncludeSubdomains: target.ContainsWildcardName(true),
|
||||||
EnablePermissionPolicyHeader: target.HeaderRewriteRules.EnablePermissionPolicyHeader,
|
EnablePermissionPolicyHeader: headerRewriteOptions.EnablePermissionPolicyHeader,
|
||||||
PermissionPolicy: target.HeaderRewriteRules.PermissionPolicy,
|
PermissionPolicy: headerRewriteOptions.PermissionPolicy,
|
||||||
})
|
})
|
||||||
|
|
||||||
//Handle the request reverse proxy
|
//Handle the request reverse proxy
|
||||||
@ -183,8 +193,8 @@ func (h *ProxyHandler) hostRequest(w http.ResponseWriter, r *http.Request, targe
|
|||||||
PathPrefix: "",
|
PathPrefix: "",
|
||||||
UpstreamHeaders: upstreamHeaders,
|
UpstreamHeaders: upstreamHeaders,
|
||||||
DownstreamHeaders: downstreamHeaders,
|
DownstreamHeaders: downstreamHeaders,
|
||||||
HostHeaderOverwrite: target.HeaderRewriteRules.RequestHostOverwrite,
|
HostHeaderOverwrite: headerRewriteOptions.RequestHostOverwrite,
|
||||||
NoRemoveHopByHop: target.HeaderRewriteRules.DisableHopByHopHeaderRemoval,
|
NoRemoveHopByHop: headerRewriteOptions.DisableHopByHopHeaderRemoval,
|
||||||
Version: target.parent.Option.HostVersion,
|
Version: target.parent.Option.HostVersion,
|
||||||
})
|
})
|
||||||
|
|
||||||
@ -222,11 +232,16 @@ func (h *ProxyHandler) vdirRequest(w http.ResponseWriter, r *http.Request, targe
|
|||||||
if target.RequireTLS {
|
if target.RequireTLS {
|
||||||
u, _ = url.Parse("wss://" + wsRedirectionEndpoint + r.URL.String())
|
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)
|
h.Parent.logRequest(r, true, 101, "vdir-websocket", target.Domain)
|
||||||
wspHandler := websocketproxy.NewProxy(u, websocketproxy.Options{
|
wspHandler := websocketproxy.NewProxy(u, websocketproxy.Options{
|
||||||
SkipTLSValidation: target.SkipCertValidations,
|
SkipTLSValidation: target.SkipCertValidations,
|
||||||
SkipOriginCheck: true, //You should not use websocket via virtual directory. But keep this to true for compatibility
|
SkipOriginCheck: target.parent.EnableWebsocketCustomHeaders, //You should not use websocket via virtual directory. But keep this to true for compatibility
|
||||||
CopyAllHeaders: true,
|
CopyAllHeaders: domainsniff.RequireWebsocketHeaderCopy(r), //Left this as default to prevent nginx user setting / as vdir
|
||||||
UserDefinedHeaders: target.parent.HeaderRewriteRules.UserDefinedHeaders,
|
UserDefinedHeaders: target.parent.HeaderRewriteRules.UserDefinedHeaders,
|
||||||
Logger: h.Parent.Option.Logger,
|
Logger: h.Parent.Option.Logger,
|
||||||
})
|
})
|
||||||
@ -243,15 +258,20 @@ func (h *ProxyHandler) vdirRequest(w http.ResponseWriter, r *http.Request, targe
|
|||||||
}
|
}
|
||||||
|
|
||||||
//Populate the user-defined headers with the values from the request
|
//Populate the user-defined headers with the values from the request
|
||||||
rewrittenUserDefinedHeaders := rewrite.PopulateRequestHeaderVariables(r, target.parent.HeaderRewriteRules.UserDefinedHeaders)
|
headerRewriteOptions := GetDefaultHeaderRewriteRules()
|
||||||
|
if target.parent.HeaderRewriteRules != nil {
|
||||||
|
headerRewriteOptions = target.parent.HeaderRewriteRules
|
||||||
|
}
|
||||||
|
|
||||||
|
rewrittenUserDefinedHeaders := rewrite.PopulateRequestHeaderVariables(r, headerRewriteOptions.UserDefinedHeaders)
|
||||||
|
|
||||||
//Build downstream and upstream header rules, use the parent (subdomain) endpoint's headers
|
//Build downstream and upstream header rules, use the parent (subdomain) endpoint's headers
|
||||||
upstreamHeaders, downstreamHeaders := rewrite.SplitUpDownStreamHeaders(&rewrite.HeaderRewriteOptions{
|
upstreamHeaders, downstreamHeaders := rewrite.SplitUpDownStreamHeaders(&rewrite.HeaderRewriteOptions{
|
||||||
UserDefinedHeaders: rewrittenUserDefinedHeaders,
|
UserDefinedHeaders: rewrittenUserDefinedHeaders,
|
||||||
HSTSMaxAge: target.parent.HeaderRewriteRules.HSTSMaxAge,
|
HSTSMaxAge: headerRewriteOptions.HSTSMaxAge,
|
||||||
HSTSIncludeSubdomains: target.parent.ContainsWildcardName(true),
|
HSTSIncludeSubdomains: target.parent.ContainsWildcardName(true),
|
||||||
EnablePermissionPolicyHeader: target.parent.HeaderRewriteRules.EnablePermissionPolicyHeader,
|
EnablePermissionPolicyHeader: headerRewriteOptions.EnablePermissionPolicyHeader,
|
||||||
PermissionPolicy: target.parent.HeaderRewriteRules.PermissionPolicy,
|
PermissionPolicy: headerRewriteOptions.PermissionPolicy,
|
||||||
})
|
})
|
||||||
|
|
||||||
//Handle the virtual directory reverse proxy request
|
//Handle the virtual directory reverse proxy request
|
||||||
@ -262,7 +282,7 @@ func (h *ProxyHandler) vdirRequest(w http.ResponseWriter, r *http.Request, targe
|
|||||||
PathPrefix: target.MatchingPath,
|
PathPrefix: target.MatchingPath,
|
||||||
UpstreamHeaders: upstreamHeaders,
|
UpstreamHeaders: upstreamHeaders,
|
||||||
DownstreamHeaders: downstreamHeaders,
|
DownstreamHeaders: downstreamHeaders,
|
||||||
HostHeaderOverwrite: target.parent.HeaderRewriteRules.RequestHostOverwrite,
|
HostHeaderOverwrite: headerRewriteOptions.RequestHostOverwrite,
|
||||||
Version: target.parent.parent.Option.HostVersion,
|
Version: target.parent.parent.Option.HostVersion,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
@ -2,7 +2,6 @@ package redirection
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
@ -111,6 +110,42 @@ func (t *RuleTable) AddRedirectRule(redirectURL string, destURL string, forwardP
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Edit an existing redirection rule, the oldRedirectURL is used to find the rule to be edited
|
||||||
|
func (t *RuleTable) EditRedirectRule(oldRedirectURL string, newRedirectURL string, destURL string, forwardPathname bool, statusCode int) error {
|
||||||
|
newRule := &RedirectRules{
|
||||||
|
RedirectURL: newRedirectURL,
|
||||||
|
TargetURL: destURL,
|
||||||
|
ForwardChildpath: forwardPathname,
|
||||||
|
StatusCode: statusCode,
|
||||||
|
}
|
||||||
|
|
||||||
|
//Remove the old rule
|
||||||
|
t.DeleteRedirectRule(oldRedirectURL)
|
||||||
|
|
||||||
|
// Convert the redirectURL to a valid filename by replacing "/" with "-" and "." with "_"
|
||||||
|
filename := utils.ReplaceSpecialCharacters(newRedirectURL) + ".json"
|
||||||
|
filepath := path.Join(t.configPath, filename)
|
||||||
|
|
||||||
|
// Create a new file for writing the JSON data
|
||||||
|
file, err := os.Create(filepath)
|
||||||
|
if err != nil {
|
||||||
|
t.log("Error creating file "+filepath, err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
err = json.NewEncoder(file).Encode(newRule)
|
||||||
|
if err != nil {
|
||||||
|
t.log("Error encoding JSON to file "+filepath, err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update the runtime map
|
||||||
|
t.rules.Store(newRedirectURL, newRule)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func (t *RuleTable) DeleteRedirectRule(redirectURL string) error {
|
func (t *RuleTable) DeleteRedirectRule(redirectURL string) error {
|
||||||
// Convert the redirectURL to a valid filename by replacing "/" with "-" and "." with "_"
|
// Convert the redirectURL to a valid filename by replacing "/" with "-" and "." with "_"
|
||||||
filename := utils.ReplaceSpecialCharacters(redirectURL) + ".json"
|
filename := utils.ReplaceSpecialCharacters(redirectURL) + ".json"
|
||||||
@ -118,7 +153,6 @@ func (t *RuleTable) DeleteRedirectRule(redirectURL string) error {
|
|||||||
// Create the full file path by joining the t.configPath with the filename
|
// Create the full file path by joining the t.configPath with the filename
|
||||||
filepath := path.Join(t.configPath, filename)
|
filepath := path.Join(t.configPath, filename)
|
||||||
|
|
||||||
fmt.Println(redirectURL, filename, filepath)
|
|
||||||
// Check if the file exists
|
// Check if the file exists
|
||||||
if _, err := os.Stat(filepath); os.IsNotExist(err) {
|
if _, err := os.Stat(filepath); os.IsNotExist(err) {
|
||||||
return nil // File doesn't exist, nothing to delete
|
return nil // File doesn't exist, nothing to delete
|
||||||
|
@ -1,5 +1,12 @@
|
|||||||
package dynamicproxy
|
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 (
|
import (
|
||||||
_ "embed"
|
_ "embed"
|
||||||
"net"
|
"net"
|
||||||
@ -166,6 +173,7 @@ type ProxyEndpoint struct {
|
|||||||
|
|
||||||
//Custom Headers
|
//Custom Headers
|
||||||
HeaderRewriteRules *HeaderRewriteRules
|
HeaderRewriteRules *HeaderRewriteRules
|
||||||
|
EnableWebsocketCustomHeaders bool //Enable custom headers for websocket connections as well (default only http reqiests)
|
||||||
|
|
||||||
//Authentication
|
//Authentication
|
||||||
AuthenticationProvider *AuthenticationProvider
|
AuthenticationProvider *AuthenticationProvider
|
||||||
@ -186,6 +194,7 @@ type ProxyEndpoint struct {
|
|||||||
|
|
||||||
//Internal Logic Elements
|
//Internal Logic Elements
|
||||||
parent *Router `json:"-"`
|
parent *Router `json:"-"`
|
||||||
|
Tags []string // Tags for the proxy endpoint
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -16,6 +16,15 @@ import (
|
|||||||
func GetRequesterIP(r *http.Request) string {
|
func GetRequesterIP(r *http.Request) string {
|
||||||
ip := r.Header.Get("X-Real-Ip")
|
ip := r.Header.Get("X-Real-Ip")
|
||||||
if ip == "" {
|
if ip == "" {
|
||||||
|
CF_Connecting_IP := r.Header.Get("CF-Connecting-IP")
|
||||||
|
Fastly_Client_IP := r.Header.Get("Fastly-Client-IP")
|
||||||
|
if CF_Connecting_IP != "" {
|
||||||
|
//Use CF Connecting IP
|
||||||
|
return CF_Connecting_IP
|
||||||
|
} else if Fastly_Client_IP != "" {
|
||||||
|
//Use Fastly Client IP
|
||||||
|
return Fastly_Client_IP
|
||||||
|
}
|
||||||
ip = r.Header.Get("X-Forwarded-For")
|
ip = r.Header.Get("X-Forwarded-For")
|
||||||
}
|
}
|
||||||
if ip == "" {
|
if ip == "" {
|
||||||
|
@ -157,3 +157,13 @@ func resolveIpFromDomain(targetIpOrDomain string) string {
|
|||||||
|
|
||||||
return targetIpAddrString
|
return targetIpAddrString
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check if the given port is already used by another process
|
||||||
|
func CheckIfPortOccupied(portNumber int) bool {
|
||||||
|
listener, err := net.Listen("tcp", ":"+strconv.Itoa(portNumber))
|
||||||
|
if err != nil {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
listener.Close()
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
@ -172,6 +172,11 @@ func (w *WebsocketProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|||||||
if req.Host != "" {
|
if req.Host != "" {
|
||||||
requestHeader.Set("Host", 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
|
// Pass X-Forwarded-For headers too, code below is a part of
|
||||||
// httputil.ReverseProxy. See http://en.wikipedia.org/wiki/X-Forwarded-For
|
// httputil.ReverseProxy. See http://en.wikipedia.org/wiki/X-Forwarded-For
|
||||||
@ -195,21 +200,31 @@ func (w *WebsocketProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|||||||
requestHeader.Set("X-Forwarded-Proto", "https")
|
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
|
// Replace header variables and copy user-defined headers
|
||||||
|
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)
|
rewrittenUserDefinedHeaders := rewrite.PopulateRequestHeaderVariables(req, w.Options.UserDefinedHeaders)
|
||||||
upstreamHeaders, _ := rewrite.SplitUpDownStreamHeaders(&rewrite.HeaderRewriteOptions{
|
upstreamHeaders, _ := rewrite.SplitUpDownStreamHeaders(&rewrite.HeaderRewriteOptions{
|
||||||
UserDefinedHeaders: rewrittenUserDefinedHeaders,
|
UserDefinedHeaders: rewrittenUserDefinedHeaders,
|
||||||
})
|
})
|
||||||
for _, headerValuePair := range upstreamHeaders {
|
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])
|
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
|
// Connect to the backend URL, also pass the headers we get from the requst
|
||||||
// together with the Forwarded headers we prepared above.
|
// together with the Forwarded headers we prepared above.
|
||||||
// TODO: support multiplexing on the same backend connection instead of
|
// TODO: support multiplexing on the same backend connection instead of
|
||||||
|
@ -78,6 +78,49 @@ func handleDeleteRedirectionRule(w http.ResponseWriter, r *http.Request) {
|
|||||||
utils.SendOK(w)
|
utils.SendOK(w)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func handleEditRedirectionRule(w http.ResponseWriter, r *http.Request) {
|
||||||
|
originalRedirectUrl, err := utils.PostPara(r, "originalRedirectUrl")
|
||||||
|
if err != nil {
|
||||||
|
utils.SendErrorResponse(w, "original redirect url cannot be empty")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
newRedirectUrl, err := utils.PostPara(r, "newRedirectUrl")
|
||||||
|
if err != nil {
|
||||||
|
utils.SendErrorResponse(w, "redirect url cannot be empty")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
destUrl, err := utils.PostPara(r, "destUrl")
|
||||||
|
if err != nil {
|
||||||
|
utils.SendErrorResponse(w, "destination url cannot be empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
forwardChildpath, err := utils.PostPara(r, "forwardChildpath")
|
||||||
|
if err != nil {
|
||||||
|
//Assume true
|
||||||
|
forwardChildpath = "true"
|
||||||
|
}
|
||||||
|
|
||||||
|
redirectTypeString, err := utils.PostPara(r, "redirectType")
|
||||||
|
if err != nil {
|
||||||
|
redirectTypeString = "307"
|
||||||
|
}
|
||||||
|
|
||||||
|
redirectionStatusCode, err := strconv.Atoi(redirectTypeString)
|
||||||
|
if err != nil {
|
||||||
|
utils.SendErrorResponse(w, "invalid status code number")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = redirectTable.EditRedirectRule(originalRedirectUrl, newRedirectUrl, destUrl, forwardChildpath == "true", redirectionStatusCode)
|
||||||
|
if err != nil {
|
||||||
|
utils.SendErrorResponse(w, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
utils.SendOK(w)
|
||||||
|
}
|
||||||
|
|
||||||
// Toggle redirection regex support. Note that this cost another O(n) time complexity to each page load
|
// Toggle redirection regex support. Note that this cost another O(n) time complexity to each page load
|
||||||
func handleToggleRedirectRegexpSupport(w http.ResponseWriter, r *http.Request) {
|
func handleToggleRedirectRegexpSupport(w http.ResponseWriter, r *http.Request) {
|
||||||
enabled, err := utils.PostPara(r, "enable")
|
enabled, err := utils.PostPara(r, "enable")
|
||||||
|
@ -14,6 +14,7 @@ import (
|
|||||||
"imuslab.com/zoraxy/mod/dynamicproxy/loadbalance"
|
"imuslab.com/zoraxy/mod/dynamicproxy/loadbalance"
|
||||||
"imuslab.com/zoraxy/mod/dynamicproxy/permissionpolicy"
|
"imuslab.com/zoraxy/mod/dynamicproxy/permissionpolicy"
|
||||||
"imuslab.com/zoraxy/mod/dynamicproxy/rewrite"
|
"imuslab.com/zoraxy/mod/dynamicproxy/rewrite"
|
||||||
|
"imuslab.com/zoraxy/mod/netutils"
|
||||||
"imuslab.com/zoraxy/mod/uptime"
|
"imuslab.com/zoraxy/mod/uptime"
|
||||||
"imuslab.com/zoraxy/mod/utils"
|
"imuslab.com/zoraxy/mod/utils"
|
||||||
)
|
)
|
||||||
@ -27,11 +28,23 @@ func ReverseProxtInit() {
|
|||||||
/*
|
/*
|
||||||
Load Reverse Proxy Global Settings
|
Load Reverse Proxy Global Settings
|
||||||
*/
|
*/
|
||||||
inboundPort := 443
|
inboundPort := *defaultInboundPort
|
||||||
|
autoStartReverseProxy := *defaultEnableInboundTraffic
|
||||||
if sysdb.KeyExists("settings", "inbound") {
|
if sysdb.KeyExists("settings", "inbound") {
|
||||||
|
//Read settings from database
|
||||||
sysdb.Read("settings", "inbound", &inboundPort)
|
sysdb.Read("settings", "inbound", &inboundPort)
|
||||||
SystemWideLogger.Println("Serving inbound port ", inboundPort)
|
if netutils.CheckIfPortOccupied(inboundPort) {
|
||||||
|
autoStartReverseProxy = false
|
||||||
|
SystemWideLogger.Println("Inbound port ", inboundPort, " is occupied. Change the listening port in the webmin panel and press \"Start Service\" to start reverse proxy service")
|
||||||
} else {
|
} else {
|
||||||
|
SystemWideLogger.Println("Serving inbound port ", inboundPort)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
//Default port
|
||||||
|
if netutils.CheckIfPortOccupied(inboundPort) {
|
||||||
|
autoStartReverseProxy = false
|
||||||
|
SystemWideLogger.Println("Port 443 is occupied. Change the listening port in the webmin panel and press \"Start Service\" to start reverse proxy service")
|
||||||
|
}
|
||||||
SystemWideLogger.Println("Inbound port not set. Using default (443)")
|
SystemWideLogger.Println("Inbound port not set. Using default (443)")
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -60,6 +73,9 @@ func ReverseProxtInit() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
listenOnPort80 := true
|
listenOnPort80 := true
|
||||||
|
if netutils.CheckIfPortOccupied(80) {
|
||||||
|
listenOnPort80 = false
|
||||||
|
}
|
||||||
sysdb.Read("settings", "listenP80", &listenOnPort80)
|
sysdb.Read("settings", "listenP80", &listenOnPort80)
|
||||||
if listenOnPort80 {
|
if listenOnPort80 {
|
||||||
SystemWideLogger.Println("Port 80 listener enabled")
|
SystemWideLogger.Println("Port 80 listener enabled")
|
||||||
@ -96,7 +112,7 @@ func ReverseProxtInit() {
|
|||||||
RedirectRuleTable: redirectTable,
|
RedirectRuleTable: redirectTable,
|
||||||
GeodbStore: geodbStore,
|
GeodbStore: geodbStore,
|
||||||
StatisticCollector: statisticCollector,
|
StatisticCollector: statisticCollector,
|
||||||
WebDirectory: *staticWebServerRoot,
|
WebDirectory: *path_webserver,
|
||||||
AccessController: accessController,
|
AccessController: accessController,
|
||||||
AutheliaRouter: autheliaRouter,
|
AutheliaRouter: autheliaRouter,
|
||||||
LoadBalancer: loadBalancer,
|
LoadBalancer: loadBalancer,
|
||||||
@ -136,9 +152,11 @@ func ReverseProxtInit() {
|
|||||||
//Start Service
|
//Start Service
|
||||||
//Not sure why but delay must be added if you have another
|
//Not sure why but delay must be added if you have another
|
||||||
//reverse proxy server in front of this service
|
//reverse proxy server in front of this service
|
||||||
|
if autoStartReverseProxy {
|
||||||
time.Sleep(300 * time.Millisecond)
|
time.Sleep(300 * time.Millisecond)
|
||||||
dynamicProxyRouter.StartProxyService()
|
dynamicProxyRouter.StartProxyService()
|
||||||
SystemWideLogger.Println("Dynamic Reverse Proxy service started")
|
SystemWideLogger.Println("Dynamic Reverse Proxy service started")
|
||||||
|
}
|
||||||
|
|
||||||
//Add all proxy services to uptime monitor
|
//Add all proxy services to uptime monitor
|
||||||
//Create a uptime monitor service
|
//Create a uptime monitor service
|
||||||
@ -287,6 +305,23 @@ func ReverseProxyHandleAddEndpoint(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
tagStr, _ := utils.PostPara(r, "tags")
|
||||||
|
tags := []string{}
|
||||||
|
if tagStr != "" {
|
||||||
|
tags = strings.Split(tagStr, ",")
|
||||||
|
for i := range tags {
|
||||||
|
tags[i] = strings.TrimSpace(tags[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Remove empty tags
|
||||||
|
filteredTags := []string{}
|
||||||
|
for _, tag := range tags {
|
||||||
|
if tag != "" {
|
||||||
|
filteredTags = append(filteredTags, tag)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tags = filteredTags
|
||||||
|
|
||||||
var proxyEndpointCreated *dynamicproxy.ProxyEndpoint
|
var proxyEndpointCreated *dynamicproxy.ProxyEndpoint
|
||||||
if eptype == "host" {
|
if eptype == "host" {
|
||||||
rootOrMatchingDomain, err := utils.PostPara(r, "rootname")
|
rootOrMatchingDomain, err := utils.PostPara(r, "rootname")
|
||||||
@ -320,10 +355,6 @@ func ReverseProxyHandleAddEndpoint(w http.ResponseWriter, r *http.Request) {
|
|||||||
BasicAuthExceptionRules: []*dynamicproxy.BasicAuthExceptionRule{},
|
BasicAuthExceptionRules: []*dynamicproxy.BasicAuthExceptionRule{},
|
||||||
}
|
}
|
||||||
|
|
||||||
thisCustomHeaderRules := dynamicproxy.HeaderRewriteRules{
|
|
||||||
UserDefinedHeaders: []*rewrite.UserDefinedHeader{},
|
|
||||||
}
|
|
||||||
|
|
||||||
//Generate a proxy endpoint object
|
//Generate a proxy endpoint object
|
||||||
thisProxyEndpoint := dynamicproxy.ProxyEndpoint{
|
thisProxyEndpoint := dynamicproxy.ProxyEndpoint{
|
||||||
//I/O
|
//I/O
|
||||||
@ -353,7 +384,7 @@ func ReverseProxyHandleAddEndpoint(w http.ResponseWriter, r *http.Request) {
|
|||||||
AuthenticationProvider: &thisAuthenticationProvider,
|
AuthenticationProvider: &thisAuthenticationProvider,
|
||||||
|
|
||||||
//Header Rewrite
|
//Header Rewrite
|
||||||
HeaderRewriteRules: &thisCustomHeaderRules,
|
HeaderRewriteRules: dynamicproxy.GetDefaultHeaderRewriteRules(),
|
||||||
|
|
||||||
//Default Site
|
//Default Site
|
||||||
DefaultSiteOption: 0,
|
DefaultSiteOption: 0,
|
||||||
@ -361,6 +392,8 @@ func ReverseProxyHandleAddEndpoint(w http.ResponseWriter, r *http.Request) {
|
|||||||
// Rate Limit
|
// Rate Limit
|
||||||
RequireRateLimit: requireRateLimit,
|
RequireRateLimit: requireRateLimit,
|
||||||
RateLimit: int64(proxyRateLimit),
|
RateLimit: int64(proxyRateLimit),
|
||||||
|
|
||||||
|
Tags: tags,
|
||||||
}
|
}
|
||||||
|
|
||||||
preparedEndpoint, err := dynamicProxyRouter.PrepareProxyRoute(&thisProxyEndpoint)
|
preparedEndpoint, err := dynamicProxyRouter.PrepareProxyRoute(&thisProxyEndpoint)
|
||||||
@ -471,6 +504,12 @@ func ReverseProxyHandleEditEndpoint(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
bypassGlobalTLS := (bpgtls == "true")
|
bypassGlobalTLS := (bpgtls == "true")
|
||||||
|
|
||||||
|
//Disable uptime monitor
|
||||||
|
disbleUtm, err := utils.PostBool(r, "dutm")
|
||||||
|
if err != nil {
|
||||||
|
disbleUtm = false
|
||||||
|
}
|
||||||
|
|
||||||
// Auth Provider
|
// Auth Provider
|
||||||
authProviderTypeStr, _ := utils.PostPara(r, "authprovider")
|
authProviderTypeStr, _ := utils.PostPara(r, "authprovider")
|
||||||
if authProviderTypeStr == "" {
|
if authProviderTypeStr == "" {
|
||||||
@ -513,6 +552,15 @@ func ReverseProxyHandleEditEndpoint(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
tagStr, _ := utils.PostPara(r, "tags")
|
||||||
|
tags := []string{}
|
||||||
|
if tagStr != "" {
|
||||||
|
tags = strings.Split(tagStr, ",")
|
||||||
|
for i := range tags {
|
||||||
|
tags[i] = strings.TrimSpace(tags[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
//Generate a new proxyEndpoint from the new config
|
//Generate a new proxyEndpoint from the new config
|
||||||
newProxyEndpoint := dynamicproxy.CopyEndpoint(targetProxyEntry)
|
newProxyEndpoint := dynamicproxy.CopyEndpoint(targetProxyEntry)
|
||||||
newProxyEndpoint.BypassGlobalTLS = bypassGlobalTLS
|
newProxyEndpoint.BypassGlobalTLS = bypassGlobalTLS
|
||||||
@ -536,6 +584,8 @@ func ReverseProxyHandleEditEndpoint(w http.ResponseWriter, r *http.Request) {
|
|||||||
newProxyEndpoint.RequireRateLimit = requireRateLimit
|
newProxyEndpoint.RequireRateLimit = requireRateLimit
|
||||||
newProxyEndpoint.RateLimit = proxyRateLimit
|
newProxyEndpoint.RateLimit = proxyRateLimit
|
||||||
newProxyEndpoint.UseStickySession = useStickySession
|
newProxyEndpoint.UseStickySession = useStickySession
|
||||||
|
newProxyEndpoint.DisableUptimeMonitor = disbleUtm
|
||||||
|
newProxyEndpoint.Tags = tags
|
||||||
|
|
||||||
//Prepare to replace the current routing rule
|
//Prepare to replace the current routing rule
|
||||||
readyRoutingRule, err := dynamicProxyRouter.PrepareProxyRoute(newProxyEndpoint)
|
readyRoutingRule, err := dynamicProxyRouter.PrepareProxyRoute(newProxyEndpoint)
|
||||||
@ -1557,3 +1607,39 @@ func HandlePermissionPolicy(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
http.Error(w, "405 - Method not allowed", http.StatusMethodNotAllowed)
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -54,14 +54,14 @@ var (
|
|||||||
|
|
||||||
func startupSequence() {
|
func startupSequence() {
|
||||||
//Start a system wide logger and log viewer
|
//Start a system wide logger and log viewer
|
||||||
l, err := logger.NewLogger(LOG_PREFIX, LOG_FOLDER)
|
l, err := logger.NewLogger(LOG_PREFIX, *path_logFile)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
SystemWideLogger = l
|
SystemWideLogger = l
|
||||||
} else {
|
} else {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
LogViewer = logviewer.NewLogViewer(&logviewer.ViewerOption{
|
LogViewer = logviewer.NewLogViewer(&logviewer.ViewerOption{
|
||||||
RootFolder: LOG_FOLDER,
|
RootFolder: *path_logFile,
|
||||||
Extension: LOG_EXTENSION,
|
Extension: LOG_EXTENSION,
|
||||||
})
|
})
|
||||||
|
|
||||||
@ -73,7 +73,7 @@ func startupSequence() {
|
|||||||
backendType = dbinc.BackendBoltDB
|
backendType = dbinc.BackendBoltDB
|
||||||
}
|
}
|
||||||
l.PrintAndLog("database", "Using "+backendType.String()+" as the database backend", nil)
|
l.PrintAndLog("database", "Using "+backendType.String()+" as the database backend", nil)
|
||||||
db, err := database.NewDatabase(DATABASE_PATH, backendType)
|
db, err := database.NewDatabase("./sys.db", backendType)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
@ -158,7 +158,7 @@ func startupSequence() {
|
|||||||
staticWebServer = webserv.NewWebServer(&webserv.WebServerOptions{
|
staticWebServer = webserv.NewWebServer(&webserv.WebServerOptions{
|
||||||
Sysdb: sysdb,
|
Sysdb: sysdb,
|
||||||
Port: strconv.Itoa(WEBSERV_DEFAULT_PORT), //Default Port
|
Port: strconv.Itoa(WEBSERV_DEFAULT_PORT), //Default Port
|
||||||
WebRoot: *staticWebServerRoot,
|
WebRoot: *path_webserver,
|
||||||
EnableDirectoryListing: true,
|
EnableDirectoryListing: true,
|
||||||
EnableWebDirManager: *allowWebFileManager,
|
EnableWebDirManager: *allowWebFileManager,
|
||||||
Logger: SystemWideLogger,
|
Logger: SystemWideLogger,
|
||||||
|
@ -1174,7 +1174,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function removeIpBlacklist(ipaddr){
|
function removeIpBlacklist(ipaddr){
|
||||||
if (confirm("Confirm remove blacklist for " + ipaddr + " ?")){
|
//if (confirm("Confirm remove blacklist for " + ipaddr + " ?")){
|
||||||
$.cjax({
|
$.cjax({
|
||||||
url: "/api/blacklist/ip/remove",
|
url: "/api/blacklist/ip/remove",
|
||||||
type: "POST",
|
type: "POST",
|
||||||
@ -1191,7 +1191,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
});
|
});
|
||||||
}
|
//}
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@ -1318,7 +1318,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function removeIpWhitelist(ipaddr){
|
function removeIpWhitelist(ipaddr){
|
||||||
if (confirm("Confirm remove whitelist for " + ipaddr + " ?")){
|
//if (confirm("Confirm remove whitelist for " + ipaddr + " ?")){
|
||||||
$.cjax({
|
$.cjax({
|
||||||
url: "/api/whitelist/ip/remove",
|
url: "/api/whitelist/ip/remove",
|
||||||
type: "POST",
|
type: "POST",
|
||||||
@ -1335,7 +1335,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
});
|
});
|
||||||
}
|
//}
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|
@ -11,7 +11,47 @@
|
|||||||
.subdEntry td:not(.ignoremw){
|
.subdEntry td:not(.ignoremw){
|
||||||
min-width: 200px;
|
min-width: 200px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.httpProxyListTools{
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tag-select{
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tag-select:hover{
|
||||||
|
text-decoration: underline;
|
||||||
|
opacity: 0.8;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
<div class="httpProxyListTools" style="margin-bottom: 1em;">
|
||||||
|
<div id="tagFilterDropdown" class="ui floating basic dropdown labeled icon button" style="min-width: 150px;">
|
||||||
|
<i class="filter icon"></i>
|
||||||
|
<span class="text">Filter by tags</span>
|
||||||
|
<div class="menu">
|
||||||
|
<div class="ui icon search input">
|
||||||
|
<i class="search icon"></i>
|
||||||
|
<input type="text" placeholder="Search tags...">
|
||||||
|
</div>
|
||||||
|
<div class="divider"></div>
|
||||||
|
<div class="scrolling menu tagList">
|
||||||
|
<!--
|
||||||
|
Example:
|
||||||
|
<div class="item">
|
||||||
|
<div class="ui red empty circular label"></div>
|
||||||
|
Important
|
||||||
|
</div>
|
||||||
|
-->
|
||||||
|
<!-- Add more tag options dynamically -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="ui small input" style="width: 300px; height: 38px;">
|
||||||
|
<input type="text" id="searchInput" placeholder="Quick Search" onkeydown="handleSearchInput(event);" onchange="handleSearchInput(event);" onblur="handleSearchInput(event);">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div style="width: 100%; overflow-x: auto; margin-bottom: 1em; min-height: 300px;">
|
<div style="width: 100%; overflow-x: auto; margin-bottom: 1em; min-height: 300px;">
|
||||||
<table class="ui celled sortable unstackable compact table">
|
<table class="ui celled sortable unstackable compact table">
|
||||||
<thead>
|
<thead>
|
||||||
@ -19,6 +59,7 @@
|
|||||||
<th>Host</th>
|
<th>Host</th>
|
||||||
<th>Destination</th>
|
<th>Destination</th>
|
||||||
<th>Virtual Directory</th>
|
<th>Virtual Directory</th>
|
||||||
|
<th>Tags</th>
|
||||||
<th style="max-width: 300px;">Advanced Settings</th>
|
<th style="max-width: 300px;">Advanced Settings</th>
|
||||||
<th class="no-sort" style="min-width:150px;">Actions</th>
|
<th class="no-sort" style="min-width:150px;">Actions</th>
|
||||||
</tr>
|
</tr>
|
||||||
@ -124,6 +165,11 @@
|
|||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td data-label="" editable="true" datatype="vdir">${vdList}</td>
|
<td data-label="" editable="true" datatype="vdir">${vdList}</td>
|
||||||
|
<td data-label="tags" payload="${encodeURIComponent(JSON.stringify(subd.Tags))}" datatype="tags">
|
||||||
|
<div class="tags-list">
|
||||||
|
${subd.Tags.length >0 ? subd.Tags.map(tag => `<span class="ui tiny label tag-select" style="background-color: ${getTagColorByName(tag)}; color: ${getTagTextColor(tag)}">${tag}</span>`).join(""):"<small style='opacity: 0.3; pointer-events: none; user-select: none;'>No Tags</small>"}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
<td data-label="" editable="true" datatype="advanced" style="width: 350px;">
|
<td data-label="" editable="true" datatype="advanced" style="width: 350px;">
|
||||||
${subd.AuthenticationProvider.AuthMethod == 0x1?`<i class="ui grey key icon"></i> Basic Auth`:``}
|
${subd.AuthenticationProvider.AuthMethod == 0x1?`<i class="ui grey key icon"></i> Basic Auth`:``}
|
||||||
${subd.AuthenticationProvider.AuthMethod == 0x2?`<i class="ui blue key icon"></i> Authelia`:``}
|
${subd.AuthenticationProvider.AuthMethod == 0x2?`<i class="ui blue key icon"></i> Authelia`:``}
|
||||||
@ -142,6 +188,7 @@
|
|||||||
</td>
|
</td>
|
||||||
</tr>`);
|
</tr>`);
|
||||||
});
|
});
|
||||||
|
populateTagFilterDropdown(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
resolveAccessRuleNameOnHostRPlist();
|
resolveAccessRuleNameOnHostRPlist();
|
||||||
@ -258,6 +305,13 @@
|
|||||||
if (payload.UseStickySession){
|
if (payload.UseStickySession){
|
||||||
useStickySessionChecked = "checked";
|
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>
|
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 divider"></div>
|
||||||
<div class="ui checkbox" style="margin-top: 0.4em;">
|
<div class="ui checkbox" style="margin-top: 0.4em;">
|
||||||
@ -265,7 +319,11 @@
|
|||||||
<label>Use Sticky Session<br>
|
<label>Use Sticky Session<br>
|
||||||
<small>Enable stick session on load balancing</small></label>
|
<small>Enable stick session on load balancing</small></label>
|
||||||
</div>
|
</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.append(input);
|
||||||
$(column).find(".upstreamList").addClass("editing");
|
$(column).find(".upstreamList").addClass("editing");
|
||||||
@ -274,7 +332,11 @@
|
|||||||
column.append(`<button class="ui basic tiny button" style="margin-left: 0.4em; margin-top: 0.4em;" onclick="quickEditVdir('${uuid}');">
|
column.append(`<button class="ui basic tiny button" style="margin-left: 0.4em; margin-top: 0.4em;" onclick="quickEditVdir('${uuid}');">
|
||||||
<i class="ui yellow folder icon"></i> Edit Virtual Directories
|
<i class="ui yellow folder icon"></i> Edit Virtual Directories
|
||||||
</button>`);
|
</button>`);
|
||||||
|
}else if (datatype == "tags"){
|
||||||
|
column.append(`
|
||||||
|
<div class="ui divider"></div>
|
||||||
|
<button class="ui basic compact fluid tiny button" style="margin-left: 0.4em; margin-top: 0.4em;" onclick="editTags('${uuid}');"><i class="ui purple tag icon"></i> Edit tags</button>
|
||||||
|
`);
|
||||||
}else if (datatype == "advanced"){
|
}else if (datatype == "advanced"){
|
||||||
let authProvider = payload.AuthenticationProvider.AuthMethod;
|
let authProvider = payload.AuthenticationProvider.AuthMethod;
|
||||||
|
|
||||||
@ -441,11 +503,17 @@
|
|||||||
|
|
||||||
var epttype = "host";
|
var epttype = "host";
|
||||||
let useStickySession = $(row).find(".UseStickySession")[0].checked;
|
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 authProviderType = $(row).find(".authProviderPicker input[type='radio']:checked").val();
|
||||||
let requireRateLimit = $(row).find(".RequireRateLimit")[0].checked;
|
let requireRateLimit = $(row).find(".RequireRateLimit")[0].checked;
|
||||||
let rateLimit = $(row).find(".RateLimit").val();
|
let rateLimit = $(row).find(".RateLimit").val();
|
||||||
let bypassGlobalTLS = $(row).find(".BypassGlobalTLS")[0].checked;
|
let bypassGlobalTLS = $(row).find(".BypassGlobalTLS")[0].checked;
|
||||||
|
let tags = getTagsArrayFromEndpoint(uuid);
|
||||||
|
if (tags.length > 0){
|
||||||
|
tags = tags.join(",");
|
||||||
|
}else{
|
||||||
|
tags = "";
|
||||||
|
}
|
||||||
$.cjax({
|
$.cjax({
|
||||||
url: "/api/proxy/edit",
|
url: "/api/proxy/edit",
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@ -453,10 +521,12 @@
|
|||||||
"type": epttype,
|
"type": epttype,
|
||||||
"rootname": uuid,
|
"rootname": uuid,
|
||||||
"ss":useStickySession,
|
"ss":useStickySession,
|
||||||
|
"dutm": DisableUptimeMonitor,
|
||||||
"bpgtls": bypassGlobalTLS,
|
"bpgtls": bypassGlobalTLS,
|
||||||
"authprovider" :authProviderType,
|
"authprovider" :authProviderType,
|
||||||
"rate" :requireRateLimit,
|
"rate" :requireRateLimit,
|
||||||
"ratenum" :rateLimit,
|
"ratenum" :rateLimit,
|
||||||
|
"tags": tags,
|
||||||
},
|
},
|
||||||
success: function(data){
|
success: function(data){
|
||||||
if (data.error !== undefined){
|
if (data.error !== undefined){
|
||||||
@ -596,4 +666,110 @@
|
|||||||
tabSwitchEventBind["httprp"] = function(){
|
tabSwitchEventBind["httprp"] = function(){
|
||||||
listProxyEndpoints();
|
listProxyEndpoints();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Tags & Search */
|
||||||
|
function handleSearchInput(event){
|
||||||
|
if (event.key == "Escape"){
|
||||||
|
$("#searchInput").val("");
|
||||||
|
}
|
||||||
|
filterProxyList();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Function to filter the proxy list
|
||||||
|
function filterProxyList() {
|
||||||
|
let searchInput = $("#searchInput").val().toLowerCase();
|
||||||
|
let selectedTag = $("#tagFilterDropdown").dropdown('get value');
|
||||||
|
$("#httpProxyList tr").each(function() {
|
||||||
|
let host = $(this).find("td[data-label='']").text().toLowerCase();
|
||||||
|
let tagElements = $(this).find("td[data-label='tags']");
|
||||||
|
let tags = tagElements.attr("payload");
|
||||||
|
tags = JSON.parse(decodeURIComponent(tags));
|
||||||
|
if ((host.includes(searchInput) || searchInput === "") && (tags.includes(selectedTag) || selectedTag === "")) {
|
||||||
|
$(this).show();
|
||||||
|
} else {
|
||||||
|
$(this).hide();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Function to generate a color based on a tag name
|
||||||
|
function getTagColorByName(tagName) {
|
||||||
|
function hashCode(str) {
|
||||||
|
return str.split('').reduce((prevHash, currVal) =>
|
||||||
|
((prevHash << 5) - prevHash) + currVal.charCodeAt(0), 0);
|
||||||
|
}
|
||||||
|
let hash = hashCode(tagName);
|
||||||
|
let color = '#' + ((hash >> 24) & 0xFF).toString(16).padStart(2, '0') +
|
||||||
|
((hash >> 16) & 0xFF).toString(16).padStart(2, '0') +
|
||||||
|
((hash >> 8) & 0xFF).toString(16).padStart(2, '0');
|
||||||
|
return color;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getTagTextColor(tagName){
|
||||||
|
let color = getTagColorByName(tagName);
|
||||||
|
let r = parseInt(color.substr(1, 2), 16);
|
||||||
|
let g = parseInt(color.substr(3, 2), 16);
|
||||||
|
let b = parseInt(color.substr(5, 2), 16);
|
||||||
|
let brightness = Math.round(((r * 299) + (g * 587) + (b * 114)) / 1000);
|
||||||
|
return brightness > 125 ? "#000000" : "#ffffff";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Populate the tag filter dropdown
|
||||||
|
function populateTagFilterDropdown(data) {
|
||||||
|
let tags = new Set();
|
||||||
|
data.forEach(subd => {
|
||||||
|
subd.Tags.forEach(tag => tags.add(tag));
|
||||||
|
});
|
||||||
|
tags = Array.from(tags).sort((a, b) => a.localeCompare(b));
|
||||||
|
let dropdownMenu = $("#tagFilterDropdown .tagList");
|
||||||
|
dropdownMenu.html(`<div class="item tag-select" data-value="">
|
||||||
|
<div class="ui grey empty circular label"></div>
|
||||||
|
Show all
|
||||||
|
</div>`);
|
||||||
|
tags.forEach(tag => {
|
||||||
|
let thisTagColor = getTagColorByName(tag);
|
||||||
|
dropdownMenu.append(`<div class="item tag-select" data-value="${tag}">
|
||||||
|
<div class="ui empty circular label" style="background-color: ${thisTagColor}; border-color: ${thisTagColor};" ></div>
|
||||||
|
${tag}
|
||||||
|
</div>`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Edit tags for a specific endpoint
|
||||||
|
function editTags(uuid){
|
||||||
|
let payload = encodeURIComponent(JSON.stringify({
|
||||||
|
ept: "host",
|
||||||
|
ep: uuid
|
||||||
|
}));
|
||||||
|
showSideWrapper("snippet/tagEditor.html?t=" + Date.now() + "#" + payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Render the tags preview from tag editing snippet
|
||||||
|
function renderTagsPreview(endpoint, tags){
|
||||||
|
let targetProxyRuleEle = $(".subdEntry[eptuuid='" + endpoint + "'] td[data-label='tags']");
|
||||||
|
//Update the tag DOM
|
||||||
|
let newTagDOM = tags.map(tag => `<span class="ui tiny label tag-select" style="background-color: ${getTagColorByName(tag)}; color: ${getTagTextColor(tag)}">${tag}</span>`).join("");
|
||||||
|
$(targetProxyRuleEle).find(".tags-list").html(newTagDOM);
|
||||||
|
|
||||||
|
//Update the tag payload
|
||||||
|
$(targetProxyRuleEle).attr("payload", encodeURIComponent(JSON.stringify(tags)));
|
||||||
|
}
|
||||||
|
|
||||||
|
function getTagsArrayFromEndpoint(endpoint){
|
||||||
|
let targetProxyRuleEle = $(".subdEntry[eptuuid='" + endpoint + "'] td[data-label='tags']");
|
||||||
|
let tags = $(targetProxyRuleEle).attr("payload");
|
||||||
|
return JSON.parse(decodeURIComponent(tags));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initialize the proxy list on page load
|
||||||
|
$(document).ready(function() {
|
||||||
|
listProxyEndpoints();
|
||||||
|
|
||||||
|
// Event listener for clicking on tags
|
||||||
|
$(document).on('click', '.tag-select', function() {
|
||||||
|
let tag = $(this).text().trim();
|
||||||
|
$('#tagFilterDropdown').dropdown('set selected', tag);
|
||||||
|
filterProxyList();
|
||||||
|
});
|
||||||
|
});
|
||||||
</script>
|
</script>
|
@ -13,7 +13,7 @@
|
|||||||
<th>Destination URL</th>
|
<th>Destination URL</th>
|
||||||
<th class="no-sort">Copy Pathname</th>
|
<th class="no-sort">Copy Pathname</th>
|
||||||
<th class="no-sort">Status Code</th>
|
<th class="no-sort">Status Code</th>
|
||||||
<th class="no-sort">Remove</th>
|
<th class="no-sort">Actions</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody id="redirectionRuleList">
|
<tbody id="redirectionRuleList">
|
||||||
@ -163,12 +163,20 @@
|
|||||||
$("#redirectionRuleList").html("");
|
$("#redirectionRuleList").html("");
|
||||||
$.get("/api/redirect/list", function(data){
|
$.get("/api/redirect/list", function(data){
|
||||||
data.forEach(function(entry){
|
data.forEach(function(entry){
|
||||||
|
let encodedEntry = encodeURIComponent(JSON.stringify(entry));
|
||||||
|
let hrefURL = entry.RedirectURL;
|
||||||
|
if (!hrefURL.startsWith("http")){
|
||||||
|
hrefURL = "https://" + hrefURL;
|
||||||
|
}
|
||||||
$("#redirectionRuleList").append(`<tr>
|
$("#redirectionRuleList").append(`<tr>
|
||||||
<td><a href="${entry.RedirectURL}" target="_blank">${entry.RedirectURL}</a></td>
|
<td><a href="${hrefURL}" target="_blank">${entry.RedirectURL}</a></td>
|
||||||
<td>${entry.TargetURL}</td>
|
<td>${entry.TargetURL}</td>
|
||||||
<td>${entry.ForwardChildpath?"<i class='ui green checkmark icon'></i>":"<i class='ui red remove icon'></i>"}</td>
|
<td>${entry.ForwardChildpath?"<i class='ui green checkmark icon'></i>":"<i class='ui red remove icon'></i>"}</td>
|
||||||
<td>${entry.StatusCode==307?"Temporary Redirect (307)":"Moved Permanently (301)"}</td>
|
<td>${entry.StatusCode==307?"Temporary Redirect (307)":"Moved Permanently (301)"}</td>
|
||||||
<td><button onclick="deleteRule(this);" rurl="${encodeURIComponent(JSON.stringify(entry.RedirectURL))}" title="Delete redirection rule" class="ui mini red icon basic button"><i class="trash icon"></i></button></td>
|
<td>
|
||||||
|
<button onclick="editRule(this);" payload="${encodedEntry}" title="Edit redirection rule" class="ui mini circular icon basic button redirectEditBtn"><i class="edit icon"></i></button>
|
||||||
|
<button onclick="deleteRule(this);" rurl="${encodeURIComponent(JSON.stringify(entry.RedirectURL))}" title="Delete redirection rule" class="ui mini red circular icon basic button"><i class="trash icon"></i></button>
|
||||||
|
</td>
|
||||||
</tr>`);
|
</tr>`);
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -180,6 +188,68 @@
|
|||||||
}
|
}
|
||||||
initRedirectionRuleList();
|
initRedirectionRuleList();
|
||||||
|
|
||||||
|
function editRule(obj){
|
||||||
|
$(".redirectEditBtn").addClass("disabled");
|
||||||
|
let payload = JSON.parse(decodeURIComponent($(obj).attr("payload")));
|
||||||
|
let row = $(obj).closest("tr");
|
||||||
|
let redirectUrl = payload.RedirectURL;
|
||||||
|
let destUrl = payload.TargetURL;
|
||||||
|
let forwardChildpath = payload.ForwardChildpath;
|
||||||
|
let statusCode = payload.StatusCode;
|
||||||
|
|
||||||
|
row.html(`
|
||||||
|
<td>
|
||||||
|
<div class="ui small input">
|
||||||
|
<input type="text" value="${redirectUrl}" id="editRedirectUrl">
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<div class="ui small input">
|
||||||
|
<input type="text" value="${destUrl}" id="editDestUrl">
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td><div class="ui toggle checkbox"><input type="checkbox" ${forwardChildpath ? "checked" : ""} id="editForwardChildpath"><label></label></div></td>
|
||||||
|
<td>
|
||||||
|
<div class="ui radio checkbox"><input type="radio" name="editStatusCode" value="307" ${statusCode == 307 ? "checked" : ""}><label>Temporary Redirect (307)</label></div><br>
|
||||||
|
<div class="ui radio checkbox"><input type="radio" name="editStatusCode" value="301" ${statusCode == 301 ? "checked" : ""}><label>Moved Permanently (301)</label></div>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<button onclick="saveEditRule(this);" payload="${encodeURIComponent(JSON.stringify(payload))}" class="ui small circular green icon basic button"><i class="save icon"></i></button>
|
||||||
|
<button onclick="initRedirectionRuleList();" class="ui small circular icon basic button"><i class="cancel icon"></i></button>
|
||||||
|
</td>
|
||||||
|
`);
|
||||||
|
|
||||||
|
$(".checkbox").checkbox();
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveEditRule(obj){
|
||||||
|
let payload = JSON.parse(decodeURIComponent($(obj).attr("payload")));
|
||||||
|
let redirectUrl = $("#editRedirectUrl").val();
|
||||||
|
let destUrl = $("#editDestUrl").val();
|
||||||
|
let forwardChildpath = $("#editForwardChildpath").is(":checked");
|
||||||
|
let statusCode = parseInt($("input[name='editStatusCode']:checked").val());
|
||||||
|
|
||||||
|
$.cjax({
|
||||||
|
url: "/api/redirect/edit",
|
||||||
|
method: "POST",
|
||||||
|
data: {
|
||||||
|
originalRedirectUrl: payload.RedirectURL,
|
||||||
|
newRedirectUrl: redirectUrl,
|
||||||
|
destUrl: destUrl,
|
||||||
|
forwardChildpath: forwardChildpath,
|
||||||
|
redirectType: statusCode,
|
||||||
|
},
|
||||||
|
success: function(data){
|
||||||
|
if (data.error != undefined){
|
||||||
|
msgbox(data.error, false);
|
||||||
|
}else{
|
||||||
|
msgbox("Redirection rule updated", true);
|
||||||
|
initRedirectionRuleList();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function initRegexpSupportToggle(){
|
function initRegexpSupportToggle(){
|
||||||
$.get("/api/redirect/regex", function(data){
|
$.get("/api/redirect/regex", function(data){
|
||||||
//Set the checkbox initial state
|
//Set the checkbox initial state
|
||||||
|
@ -41,7 +41,7 @@
|
|||||||
<div class="ui radio defaultsite checkbox">
|
<div class="ui radio defaultsite checkbox">
|
||||||
<input type="radio" name="defaultsiteOption" value="closeresp">
|
<input type="radio" name="defaultsiteOption" value="closeresp">
|
||||||
<label>Close Connection<br>
|
<label>Close Connection<br>
|
||||||
<small>Close the connection without any response or in TLS mode, send an empty response</small>
|
<small>Close the connection without any response</small>
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
@ -63,6 +63,11 @@
|
|||||||
<label>Sticky Session<br><small>Enable stick session on upstream load balancing</small></label>
|
<label>Sticky Session<br><small>Enable stick session on upstream load balancing</small></label>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label>Tags</label>
|
||||||
|
<input type="text" id="proxyTags" placeholder="e.g. mediaserver, management">
|
||||||
|
<small>Comma-separated list of tags for this proxy host.</small>
|
||||||
|
</div>
|
||||||
<div class="ui horizontal divider">
|
<div class="ui horizontal divider">
|
||||||
<i class="ui green lock icon"></i>
|
<i class="ui green lock icon"></i>
|
||||||
Security
|
Security
|
||||||
@ -198,6 +203,7 @@
|
|||||||
let skipWebSocketOriginCheck = $("#skipWebsocketOriginCheck")[0].checked;
|
let skipWebSocketOriginCheck = $("#skipWebsocketOriginCheck")[0].checked;
|
||||||
let accessRuleToUse = $("#newProxyRuleAccessFilter").val();
|
let accessRuleToUse = $("#newProxyRuleAccessFilter").val();
|
||||||
let useStickySessionLB = $("#useStickySessionLB")[0].checked;
|
let useStickySessionLB = $("#useStickySessionLB")[0].checked;
|
||||||
|
let tags = $("#proxyTags").val().trim();
|
||||||
|
|
||||||
if (rootname.trim() == ""){
|
if (rootname.trim() == ""){
|
||||||
$("#rootname").parent().addClass("error");
|
$("#rootname").parent().addClass("error");
|
||||||
@ -231,6 +237,7 @@
|
|||||||
cred: JSON.stringify(credentials),
|
cred: JSON.stringify(credentials),
|
||||||
access: accessRuleToUse,
|
access: accessRuleToUse,
|
||||||
stickysess: useStickySessionLB,
|
stickysess: useStickySessionLB,
|
||||||
|
tags: tags,
|
||||||
},
|
},
|
||||||
success: function(data){
|
success: function(data){
|
||||||
if (data.error != undefined){
|
if (data.error != undefined){
|
||||||
@ -239,6 +246,7 @@
|
|||||||
//Clear old data
|
//Clear old data
|
||||||
$("#rootname").val("");
|
$("#rootname").val("");
|
||||||
$("#proxyDomain").val("");
|
$("#proxyDomain").val("");
|
||||||
|
$("#proxyTags").val("");
|
||||||
credentials = [];
|
credentials = [];
|
||||||
updateTable();
|
updateTable();
|
||||||
reloadUptimeList();
|
reloadUptimeList();
|
||||||
|
@ -108,6 +108,36 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function showStatusDotInfo(targetDot){
|
||||||
|
$(".statusbar .selectedDotInfo").hide();
|
||||||
|
let payload = $(targetDot).attr("payload");
|
||||||
|
let statusData = JSON.parse(decodeURIComponent(payload));
|
||||||
|
let statusDotInfoEle = $(targetDot).parent().parent().find(".selectedDotInfo");
|
||||||
|
let statusInfoEle = $(statusDotInfoEle).find(".status_dot_status_info");
|
||||||
|
//Fill in the data to the info box
|
||||||
|
$(statusDotInfoEle).find(".status_dot_timestamp").text(format_time(statusData.Timestamp));
|
||||||
|
$(statusDotInfoEle).find(".status_dot_latency").text(statusData.Latency + "ms");
|
||||||
|
$(statusDotInfoEle).find(".status_dot_status_code").text(statusData.StatusCode);
|
||||||
|
|
||||||
|
|
||||||
|
//Set the class of the info box if status code is 5xx
|
||||||
|
$(statusDotInfoEle).removeClass("yellow");
|
||||||
|
$(statusDotInfoEle).removeClass("red");
|
||||||
|
$(statusDotInfoEle).removeClass("green");
|
||||||
|
if (statusData.StatusCode >= 500 && statusData.StatusCode < 600){
|
||||||
|
$(statusDotInfoEle).addClass("yellow");
|
||||||
|
$(statusInfoEle).text(httpErrorStatusCodeToText(statusData.StatusCode));
|
||||||
|
}else if (statusData.StatusCode == 0 && !statusData.Online){
|
||||||
|
$(statusDotInfoEle).addClass("red");
|
||||||
|
$(statusInfoEle).text("Upstream is offline");
|
||||||
|
}else{
|
||||||
|
$(statusDotInfoEle).addClass("green");
|
||||||
|
$(statusInfoEle).text("Upstream Online");
|
||||||
|
}
|
||||||
|
|
||||||
|
$(statusDotInfoEle).show();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
function renderUptimeData(key, value){
|
function renderUptimeData(key, value){
|
||||||
if (value.length == 0){
|
if (value.length == 0){
|
||||||
@ -132,6 +162,7 @@
|
|||||||
let thisStatus = value[i];
|
let thisStatus = value[i];
|
||||||
let dotType = "";
|
let dotType = "";
|
||||||
let statusCode = thisStatus.StatusCode;
|
let statusCode = thisStatus.StatusCode;
|
||||||
|
let statusDotPayload = encodeURIComponent(JSON.stringify(thisStatus));
|
||||||
|
|
||||||
if (!thisStatus.Online && statusCode == 0){
|
if (!thisStatus.Online && statusCode == 0){
|
||||||
dotType = "offline";
|
dotType = "offline";
|
||||||
@ -159,7 +190,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
let datetime = format_time(thisStatus.Timestamp);
|
let datetime = format_time(thisStatus.Timestamp);
|
||||||
statusDotList += `<div title="${datetime}" class="${dotType} statusDot"></div>`
|
statusDotList += `<div title="${datetime}" class="${dotType} statusDot" payload="${statusDotPayload}" onclick="showStatusDotInfo(this);"></div>`
|
||||||
}
|
}
|
||||||
|
|
||||||
ontimeRate = ontimeRate / value.length * 100;
|
ontimeRate = ontimeRate / value.length * 100;
|
||||||
@ -233,8 +264,71 @@
|
|||||||
${statusDotList}
|
${statusDotList}
|
||||||
</div>
|
</div>
|
||||||
${reminderEle}
|
${reminderEle}
|
||||||
|
<div class="ui basic segment selectedDotInfo" style="display:none; border: 0.4em;">
|
||||||
|
<div class="ui list">
|
||||||
|
<div class="item"><b>Timestamp</b>: <span class="status_dot_timestamp"></span></div>
|
||||||
|
<div class="item"><b>Latency</b>: <span class="status_dot_latency"></span></div>
|
||||||
|
<div class="item"><b>Status Code</b>: <span class="status_dot_status_code"></span></div>
|
||||||
|
<div class="item"><b>Status Info</b>: <span class="status_dot_status_info"></span></div>
|
||||||
|
</div>
|
||||||
|
<button onclick="$(this).parent().hide();" style="position: absolute; right: 0.4em; top: 0.6em;" class="ui basic tiny circular icon button"><i class="ui times icon"></i></button>
|
||||||
|
</div>
|
||||||
<div class="ui divider"></div>
|
<div class="ui divider"></div>
|
||||||
</div>`);
|
</div>`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function httpErrorStatusCodeToText(statusCode){
|
||||||
|
switch(statusCode){
|
||||||
|
case 400:
|
||||||
|
return "Bad Request";
|
||||||
|
case 401:
|
||||||
|
return "Unauthorized";
|
||||||
|
case 403:
|
||||||
|
return "Forbidden";
|
||||||
|
case 404:
|
||||||
|
return "Not Found";
|
||||||
|
case 405:
|
||||||
|
return "Method Not Allowed";
|
||||||
|
case 500:
|
||||||
|
return "Internal Server Error";
|
||||||
|
case 501:
|
||||||
|
return "Not Implemented";
|
||||||
|
case 502:
|
||||||
|
return "Bad Gateway";
|
||||||
|
case 503:
|
||||||
|
return "Service Unavailable";
|
||||||
|
case 504:
|
||||||
|
return "Gateway Timeout";
|
||||||
|
case 505:
|
||||||
|
return "HTTP Version Not Supported";
|
||||||
|
case 506:
|
||||||
|
return "Variant Also Negotiates";
|
||||||
|
case 507:
|
||||||
|
return "Insufficient Storage";
|
||||||
|
case 508:
|
||||||
|
return "Loop Detected";
|
||||||
|
case 510:
|
||||||
|
return "Not Extended";
|
||||||
|
case 511:
|
||||||
|
return "Network Authentication Required";
|
||||||
|
case 520:
|
||||||
|
return "Web Server Returned an Unknown Error (Cloudflare)";
|
||||||
|
case 521:
|
||||||
|
return "Web Server is Down (Cloudflare)";
|
||||||
|
case 522:
|
||||||
|
return "Connection Timed Out (Cloudflare)";
|
||||||
|
case 523:
|
||||||
|
return "Origin is Unreachable (Cloudflare)";
|
||||||
|
case 524:
|
||||||
|
return "A Timeout Occurred (Cloudflare)";
|
||||||
|
case 525:
|
||||||
|
return "SSL Handshake Failed (Cloudflare)";
|
||||||
|
case 526:
|
||||||
|
return "Invalid SSL Certificate (Cloudflare)";
|
||||||
|
case 527:
|
||||||
|
return "Railgun Error (Cloudflare)";
|
||||||
|
default:
|
||||||
|
return "Unknown Error";
|
||||||
|
}
|
||||||
|
}
|
||||||
</script>
|
</script>
|
@ -23,6 +23,10 @@ body:not(.darkTheme){
|
|||||||
--text_color_inverted: #fcfcfc;
|
--text_color_inverted: #fcfcfc;
|
||||||
--button_text_color: #878787;
|
--button_text_color: #878787;
|
||||||
--button_border_color: #dedede;
|
--button_border_color: #dedede;
|
||||||
|
--buttom_toggle_active: #01dc64;
|
||||||
|
--buttom_toggle_disabled: #f2f2f2;
|
||||||
|
--table_bg_default: transparent;
|
||||||
|
--status_dot_bg: #e8e8e8;
|
||||||
|
|
||||||
--theme_background: linear-gradient(60deg, rgb(84, 58, 183) 0%, rgb(0, 172, 193) 100%);
|
--theme_background: linear-gradient(60deg, rgb(84, 58, 183) 0%, rgb(0, 172, 193) 100%);
|
||||||
--theme_background_inverted: linear-gradient(215deg, rgba(38,60,71,1) 13%, rgba(2,3,42,1) 84%);
|
--theme_background_inverted: linear-gradient(215deg, rgba(38,60,71,1) 13%, rgba(2,3,42,1) 84%);
|
||||||
@ -31,10 +35,10 @@ body:not(.darkTheme){
|
|||||||
}
|
}
|
||||||
|
|
||||||
body.darkTheme{
|
body.darkTheme{
|
||||||
--theme_bg: #0a090e;
|
--theme_bg: #1e1e1e;
|
||||||
--theme_bg_primary: #060912;
|
--theme_bg_primary: #151517;
|
||||||
--theme_bg_secondary:#172a41;
|
--theme_bg_secondary:#1b3572;
|
||||||
--theme_highlight: #4380b0;
|
--theme_highlight: #6a7792;
|
||||||
--theme_bg_active: #020101;
|
--theme_bg_active: #020101;
|
||||||
--theme_bg_inverted: #f8f8f9;
|
--theme_bg_inverted: #f8f8f9;
|
||||||
--theme_advance: #000000;
|
--theme_advance: #000000;
|
||||||
@ -47,8 +51,12 @@ body.darkTheme{
|
|||||||
--text_color_inverted: #414141;
|
--text_color_inverted: #414141;
|
||||||
--button_text_color: #e9e9e9;
|
--button_text_color: #e9e9e9;
|
||||||
--button_border_color: #646464;
|
--button_border_color: #646464;
|
||||||
|
--buttom_toggle_active: #01dc64;
|
||||||
|
--buttom_toggle_disabled: #2b2b2b;
|
||||||
|
--table_bg_default: #121214;
|
||||||
|
--status_dot_bg: #232323;
|
||||||
|
|
||||||
--theme_background: linear-gradient(214deg, rgba(3,1,70,1) 17%, rgb(1, 55, 80) 78%);
|
--theme_background: linear-gradient(23deg, rgba(2,74,106,1) 17%, rgba(46,12,136,1) 86%);
|
||||||
--theme_background_inverted: linear-gradient(215deg, rgba(38,60,71,1) 13%, rgba(2,3,42,1) 84%);
|
--theme_background_inverted: linear-gradient(215deg, rgba(38,60,71,1) 13%, rgba(2,3,42,1) 84%);
|
||||||
--theme_green: linear-gradient(214deg, rgba(25,128,94,1) 17%, rgba(62,76,111,1) 78%);
|
--theme_green: linear-gradient(214deg, rgba(25,128,94,1) 17%, rgba(62,76,111,1) 78%);
|
||||||
--theme_red: linear-gradient(203deg, rgba(250,172,38,1) 17%, rgba(202,0,37,1) 78%);
|
--theme_red: linear-gradient(203deg, rgba(250,172,38,1) 17%, rgba(202,0,37,1) 78%);
|
||||||
@ -113,6 +121,9 @@ body.darkTheme .ui.basic.button:not(.red) {
|
|||||||
body.darkTheme .ui.basic.button:not(.red):hover {
|
body.darkTheme .ui.basic.button:not(.red):hover {
|
||||||
border: 1px solid var(--button_border_color) !important;
|
border: 1px solid var(--button_border_color) !important;
|
||||||
background-color: var(--theme_bg) !important;
|
background-color: var(--theme_bg) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
body.darkTheme .ui.basic.button:not(.red):not(.dropdown):hover {
|
||||||
opacity: 0.8;
|
opacity: 0.8;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -195,10 +206,14 @@ body.darkTheme textarea:focus {
|
|||||||
}
|
}
|
||||||
|
|
||||||
body.darkTheme .ui.toggle.checkbox input ~ label::before{
|
body.darkTheme .ui.toggle.checkbox input ~ label::before{
|
||||||
background-color: var(--theme_bg_secondary) !important;
|
background-color: var(--buttom_toggle_disabled) !important;
|
||||||
}
|
}
|
||||||
body.darkTheme .ui.toggle.checkbox input:checked ~ label::before{
|
body.darkTheme .ui.toggle.checkbox input:checked ~ label::before{
|
||||||
background-color: var(--theme_highlight) !important;
|
background-color: var(--buttom_toggle_active) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
body.darkTheme .ui.checkbox:not(.toggle) input[type="checkbox"]{
|
||||||
|
opacity: 100% !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
#sidemenuBtn{
|
#sidemenuBtn{
|
||||||
@ -444,7 +459,7 @@ body.darkTheme .ui.table{
|
|||||||
body.darkTheme .ui.celled.sortable.unstackable.compact.table thead th,
|
body.darkTheme .ui.celled.sortable.unstackable.compact.table thead th,
|
||||||
body.darkTheme .ui.celled.sortable.unstackable.compact.table tbody td,
|
body.darkTheme .ui.celled.sortable.unstackable.compact.table tbody td,
|
||||||
body.darkTheme .ui.celled.sortable.unstackable.compact.table tfoot td {
|
body.darkTheme .ui.celled.sortable.unstackable.compact.table tfoot td {
|
||||||
background-color: var(--theme_bg) !important;
|
background-color: var(--table_bg_default) !important;
|
||||||
color: var(--text_color) !important;
|
color: var(--text_color) !important;
|
||||||
border-color: var(--divider_color) !important;
|
border-color: var(--divider_color) !important;
|
||||||
}
|
}
|
||||||
@ -476,11 +491,11 @@ body.darkTheme .ui.celled.sortable.unstackable.compact.table tbody td .ui.toggle
|
|||||||
}
|
}
|
||||||
|
|
||||||
body.darkTheme .ui.celled.sortable.unstackable.compact.table tbody td .ui.toggle.checkbox input ~ label::before {
|
body.darkTheme .ui.celled.sortable.unstackable.compact.table tbody td .ui.toggle.checkbox input ~ label::before {
|
||||||
background-color: var(--theme_bg_secondary) !important;
|
background-color: var(--buttom_toggle_disabled) !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
body.darkTheme .ui.celled.sortable.unstackable.compact.table tbody td .ui.toggle.checkbox input:checked ~ label::before {
|
body.darkTheme .ui.celled.sortable.unstackable.compact.table tbody td .ui.toggle.checkbox input:checked ~ label::before {
|
||||||
background-color: var(--theme_highlight) !important;
|
background-color: var(--buttom_toggle_active) !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
body.darkTheme .ui.celled.sortable.unstackable.compact.table tbody td .ui.circular.mini.basic.icon.button {
|
body.darkTheme .ui.celled.sortable.unstackable.compact.table tbody td .ui.circular.mini.basic.icon.button {
|
||||||
@ -537,6 +552,18 @@ body.darkTheme .RateLimit input {
|
|||||||
border-color: var(--theme_highlight) !important;
|
border-color: var(--theme_highlight) !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
body.darkTheme .menu.transition{
|
||||||
|
background-color: var(--theme_bg) !important;
|
||||||
|
color: var(--text_color) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
body.darkTheme .ui.dropdown .menu{
|
||||||
|
background: var(--theme_bg_primary) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
body.darkTheme .ui.dropdown .menu .item{
|
||||||
|
color: var(--text_color) !important;
|
||||||
|
}
|
||||||
/*
|
/*
|
||||||
Virtual Directorie Table
|
Virtual Directorie Table
|
||||||
*/
|
*/
|
||||||
@ -714,7 +741,7 @@ body.darkTheme #redirectset .ui.sortable.unstackable.celled.table thead th {
|
|||||||
}
|
}
|
||||||
|
|
||||||
body.darkTheme #redirectset .ui.sortable.unstackable.celled.table tbody tr td {
|
body.darkTheme #redirectset .ui.sortable.unstackable.celled.table tbody tr td {
|
||||||
background-color: var(--theme_bg) !important;
|
background-color: var(--table_bg_default) !important;
|
||||||
color: var(--text_color) !important;
|
color: var(--text_color) !important;
|
||||||
border-color: var(--divider_color) !important;
|
border-color: var(--divider_color) !important;
|
||||||
}
|
}
|
||||||
@ -833,7 +860,7 @@ body.darkTheme #access .ui.unstackable.basic.celled.table thead th {
|
|||||||
}
|
}
|
||||||
|
|
||||||
body.darkTheme #access .ui.unstackable.basic.celled.table tbody tr td {
|
body.darkTheme #access .ui.unstackable.basic.celled.table tbody tr td {
|
||||||
background-color: var(--theme_bg) !important;
|
background-color: var(--table_bg_default) !important;
|
||||||
color: var(--text_color) !important;
|
color: var(--text_color) !important;
|
||||||
border-color: var(--divider_color) !important;
|
border-color: var(--divider_color) !important;
|
||||||
}
|
}
|
||||||
@ -985,8 +1012,8 @@ body.darkTheme #utm .standardContainer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
body.darkTheme #utm .standardContainer .padding.statusDot {
|
body.darkTheme #utm .standardContainer .padding.statusDot {
|
||||||
background-color: var(--theme_bg) !important;
|
background-color: var(--status_dot_bg) !important;
|
||||||
border: 0.2px solid var(--text_color_inverted) !important;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
body.darkTheme .ui.utmloading.segment {
|
body.darkTheme .ui.utmloading.segment {
|
||||||
@ -1116,7 +1143,7 @@ body.darkTheme .statistic .label {
|
|||||||
/* Other Tables */
|
/* Other Tables */
|
||||||
|
|
||||||
body.darkTheme .ui.celled.compact.table {
|
body.darkTheme .ui.celled.compact.table {
|
||||||
background-color: var(--theme_bg) !important;
|
background-color: var(--table_bg_default) !important;
|
||||||
color: var(--text_color) !important;
|
color: var(--text_color) !important;
|
||||||
border-color: var(--divider_color) !important;
|
border-color: var(--divider_color) !important;
|
||||||
}
|
}
|
||||||
|
@ -117,6 +117,16 @@
|
|||||||
<label>Remove Hop-by-hop Header<br>
|
<label>Remove Hop-by-hop Header<br>
|
||||||
<small>This should be ON by default</small></label>
|
<small>This should be ON by default</small></label>
|
||||||
</div>
|
</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">
|
<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>
|
<p><i class="exclamation triangle icon"></i>Settings in this section are for advanced users. Invalid settings might cause werid, unexpected behavior.</p>
|
||||||
</div>
|
</div>
|
||||||
@ -597,6 +607,7 @@
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Manual Hostname overwrite */
|
||||||
function initManualHostOverwriteValue(){
|
function initManualHostOverwriteValue(){
|
||||||
$.get("/api/proxy/header/handleHostOverwrite?domain=" + editingEndpoint.ep, function(data){
|
$.get("/api/proxy/header/handleHostOverwrite?domain=" + editingEndpoint.ep, function(data){
|
||||||
if (data.error != undefined){
|
if (data.error != undefined){
|
||||||
@ -643,6 +654,42 @@
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
initHopByHopRemoverState();
|
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>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
260
src/web/snippet/tagEditor.html
Normal file
260
src/web/snippet/tagEditor.html
Normal file
@ -0,0 +1,260 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="zoraxy.csrf.Token" content="{{.csrfToken}}">
|
||||||
|
<link rel="stylesheet" href="../script/semantic/semantic.min.css">
|
||||||
|
<script src="../script/jquery-3.6.0.min.js"></script>
|
||||||
|
<script src="../script/semantic/semantic.min.js"></script>
|
||||||
|
<script src="../script/utils.js"></script>
|
||||||
|
<style>
|
||||||
|
.ui.circular.label.tag-color{
|
||||||
|
min-width: 5px !important;
|
||||||
|
min-height: 5px !important;
|
||||||
|
margin-right: .4em;
|
||||||
|
margin-bottom: -0.2em;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<link rel="stylesheet" href="../darktheme.css">
|
||||||
|
<script src="../script/darktheme.js"></script>
|
||||||
|
<br>
|
||||||
|
<div class="ui container">
|
||||||
|
<div class="ui header">
|
||||||
|
<div class="content">
|
||||||
|
Edit Tags
|
||||||
|
<div class="sub header" id="epname"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="ui divider"></div>
|
||||||
|
<p>Tags currently applied to this host name / proxy rule</p>
|
||||||
|
<div style="max-height: 300px; overflow-y: scroll;">
|
||||||
|
<table class="ui compact basic unstackable celled table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Tag Name</th>
|
||||||
|
<th>Action</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody id="tagsTableBody">
|
||||||
|
<!-- Rows will be dynamically added here -->
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div class="ui divider"></div>
|
||||||
|
<h4>Add New Tags</h4>
|
||||||
|
<p>Create new tag or add this proxy rule to an existing tag</p>
|
||||||
|
<div class="ui form">
|
||||||
|
<div class="field">
|
||||||
|
<label>New Tags</label>
|
||||||
|
<input type="text" id="tagsInput" placeholder="e.g. mediaserver, management">
|
||||||
|
</div>
|
||||||
|
<button class="ui basic button" onclick="addSelectedTags();"><i class="ui blue plus icon"></i> Add tag</button>
|
||||||
|
<div class="ui horizontal divider">
|
||||||
|
Or
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label>Join Existing Tag Groups</label>
|
||||||
|
<div class="ui fluid multiple search selection dropdown" id="existingTagsDropdown">
|
||||||
|
<input type="hidden" id="existingTagsInput">
|
||||||
|
<i class="dropdown icon"></i>
|
||||||
|
<div class="default text">Select Tags</div>
|
||||||
|
<div class="menu" id="existingTagsMenu">
|
||||||
|
<!-- Options will be dynamically added here -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<small id="notagwarning" style="display:none;"><i class="ui green circle check icon"></i> All tags has already been included in this host</small>
|
||||||
|
</div>
|
||||||
|
<button class="ui basic button" onclick="joinSelectedTagGroups();"><i class="ui blue plus icon"></i> Join tag group(s)</button>
|
||||||
|
</div>
|
||||||
|
<div class="ui divider"></div>
|
||||||
|
<!-- <button class="ui basic button" onclick="saveTags();"><i class="ui green save icon"></i> Save Changes</button> -->
|
||||||
|
<button class="ui basic button" style="float: right;" onclick="parent.hideSideWrapper();"><i class="remove icon"></i> Close</button>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
let editingEndpoint = {};
|
||||||
|
if (window.location.hash.length > 1){
|
||||||
|
let payloadHash = window.location.hash.substr(1);
|
||||||
|
try{
|
||||||
|
payloadHash = JSON.parse(decodeURIComponent(payloadHash));
|
||||||
|
$("#epname").text(payloadHash.ep);
|
||||||
|
editingEndpoint = payloadHash;
|
||||||
|
loadTags();
|
||||||
|
}catch(ex){
|
||||||
|
console.log("Unable to load endpoint data from hash")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadTags(){
|
||||||
|
$.get("/api/proxy/detail", { type: "host", epname: editingEndpoint.ep }, function(data){
|
||||||
|
if (data.error == undefined){
|
||||||
|
//Render the tags to the table
|
||||||
|
$("#tagsTableBody").empty();
|
||||||
|
data.Tags.forEach(tag => {
|
||||||
|
addTagRow(tag);
|
||||||
|
});
|
||||||
|
|
||||||
|
if (data.Tags.length == 0){
|
||||||
|
appendNoTagNotice();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
parent.msgbox(data.error, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
//Populate the dropdown with all tags created in the system
|
||||||
|
populateTagsDropdown();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
//Append or remove a notice to the table when no tags are applied
|
||||||
|
function appendNoTagNotice(){
|
||||||
|
$("#tagsTableBody").append(`<tr class="notagNotice" style="opacity: 0.5; pointer-events: none; user-select: none;"><td colspan="2"><i class="ui green circle check icon"></i> No tags applied to this host</td></tr>`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeNoTagNotice(){
|
||||||
|
$("#tagsTableBody .notagNotice").remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
//Load all tags created in this system
|
||||||
|
function loadAllCreatedTags(callback){
|
||||||
|
$.get("/api/proxy/list?type=host", function(data){
|
||||||
|
if (data.error !== undefined){
|
||||||
|
//No existsing rule created yet. Fresh install?
|
||||||
|
callback([]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let tags = {};
|
||||||
|
data.forEach(host => {
|
||||||
|
host.Tags.forEach(tag => {
|
||||||
|
tags[tag] = true;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
let uniqueTags = Object.keys(tags);
|
||||||
|
callback(uniqueTags);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
//Populate the dropdown with all tags created in the system
|
||||||
|
function populateTagsDropdown(){
|
||||||
|
loadAllCreatedTags(function(tags) {
|
||||||
|
let existingTags = new Set();
|
||||||
|
$('#tagsTableBody tr').each(function() {
|
||||||
|
existingTags.add($(this).attr('value'));
|
||||||
|
});
|
||||||
|
tags = tags.filter(tag => !existingTags.has(tag));
|
||||||
|
$('#existingTagsMenu').empty();
|
||||||
|
tags.forEach(tag => {
|
||||||
|
$('#existingTagsMenu').append(`<div class="item" data-value="${tag}">${tag}</div>`);
|
||||||
|
});
|
||||||
|
$('#existingTagsDropdown').dropdown();
|
||||||
|
|
||||||
|
if (tags.length == 0){
|
||||||
|
$('#notagwarning').show();
|
||||||
|
}else{
|
||||||
|
$('#notagwarning').hide();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function tagAlreadyExistsInTable(tag) {
|
||||||
|
return $(`#tagsTableBody .tagEntry[value="${tag}"]`).length > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function addSelectedTags() {
|
||||||
|
let tags = $('#tagsInput').val().split(',').map(tag => tag.trim());
|
||||||
|
tags.forEach(tag => {
|
||||||
|
if (tag && !tagAlreadyExistsInTable(tag)) {
|
||||||
|
addTagRow(tag);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
console.log(tags);
|
||||||
|
populateTagsDropdown();
|
||||||
|
$('#tagsInput').val('');
|
||||||
|
saveTags();
|
||||||
|
}
|
||||||
|
|
||||||
|
function joinSelectedTagGroups() {
|
||||||
|
if ($('#existingTagsInput').val() == ""){
|
||||||
|
parent.msgbox("Please select at least one tag group to join", false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let selectedTags = $('#existingTagsInput').val().split(',');
|
||||||
|
selectedTags.forEach(tag => {
|
||||||
|
if (tag && !tagAlreadyExistsInTable(tag)) {
|
||||||
|
addTagRow(tag);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
populateTagsDropdown();
|
||||||
|
$('#existingTagsDropdown').dropdown('clear');
|
||||||
|
saveTags();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Function to generate a color based on a tag name
|
||||||
|
function getTagColorByName(tagName) {
|
||||||
|
function hashCode(str) {
|
||||||
|
return str.split('').reduce((prevHash, currVal) =>
|
||||||
|
((prevHash << 5) - prevHash) + currVal.charCodeAt(0), 0);
|
||||||
|
}
|
||||||
|
let hash = hashCode(tagName);
|
||||||
|
let color = '#' + ((hash >> 24) & 0xFF).toString(16).padStart(2, '0') +
|
||||||
|
((hash >> 16) & 0xFF).toString(16).padStart(2, '0') +
|
||||||
|
((hash >> 8) & 0xFF).toString(16).padStart(2, '0');
|
||||||
|
return color;
|
||||||
|
}
|
||||||
|
|
||||||
|
//Add a tag row to the table
|
||||||
|
function addTagRow(tag) {
|
||||||
|
const row = `<tr class="tagEntry" value="${tag}">
|
||||||
|
<td><div class="ui circular label tag-color" style="background-color: ${getTagColorByName(tag)};"></div> ${tag}</td>
|
||||||
|
<td>
|
||||||
|
<button title="Delete Tag" class="ui circular mini red basic icon button" onclick="removeTag('${tag}')">
|
||||||
|
<i class="trash icon"></i>
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>`;
|
||||||
|
$("#tagsTableBody").append(row);
|
||||||
|
removeNoTagNotice();
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeTag(tag) {
|
||||||
|
$(`#tagsTableBody .tagEntry[value="${tag}"]`).remove();
|
||||||
|
populateTagsDropdown();
|
||||||
|
saveTags();
|
||||||
|
|
||||||
|
if ($('#tagsTableBody tr').length == 0){
|
||||||
|
appendNoTagNotice();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveTags(){
|
||||||
|
let tags = [];
|
||||||
|
$('#tagsTableBody tr').each(function() {
|
||||||
|
tags.push($(this).attr('value'));
|
||||||
|
});
|
||||||
|
console.log(tags);
|
||||||
|
$.cjax({
|
||||||
|
url: "/api/proxy/edit",
|
||||||
|
method: "POST",
|
||||||
|
data: {
|
||||||
|
type: "host",
|
||||||
|
rootname: editingEndpoint.ep,
|
||||||
|
tags: tags.join(",")
|
||||||
|
},
|
||||||
|
success: function(data){
|
||||||
|
if (data.error != undefined){
|
||||||
|
parent.msgbox(data.error, false);
|
||||||
|
} else {
|
||||||
|
parent.msgbox("Tags updated");
|
||||||
|
//Update the preview on parent page
|
||||||
|
parent.renderTagsPreview(editingEndpoint.ep, tags);
|
||||||
|
//parent.hideSideWrapper();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
@ -36,6 +36,10 @@
|
|||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
body.darkTheme #upstreamTable{
|
||||||
|
border: 1px solid var(--button_border_color);
|
||||||
|
}
|
||||||
|
|
||||||
.upstreamEntry.inactive{
|
.upstreamEntry.inactive{
|
||||||
background-color: #f3f3f3 !important;
|
background-color: #f3f3f3 !important;
|
||||||
}
|
}
|
||||||
|
3
tools/benchmark/go.mod
Normal file
3
tools/benchmark/go.mod
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
module imuslab.com/zoraxy/benchmark
|
||||||
|
|
||||||
|
go 1.23.2
|
51
tools/benchmark/main.go
Normal file
51
tools/benchmark/main.go
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
//Global variables
|
||||||
|
stopchan chan bool
|
||||||
|
|
||||||
|
//Runtime flags
|
||||||
|
benchmarkWebserverListeningPort int
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
flag.IntVar(&benchmarkWebserverListeningPort, "port", 8123, "Port to listen on")
|
||||||
|
flag.Parse()
|
||||||
|
}
|
||||||
|
|
||||||
|
/* SIGTERM handler, do shutdown sequences before closing */
|
||||||
|
func SetupCloseHandler() {
|
||||||
|
c := make(chan os.Signal, 2)
|
||||||
|
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
|
||||||
|
go func() {
|
||||||
|
<-c
|
||||||
|
//Stop all request loops
|
||||||
|
fmt.Println("Stopping request generators")
|
||||||
|
if stopchan != nil {
|
||||||
|
stopchan <- true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for all goroutines to finish
|
||||||
|
time.Sleep(1 * time.Second)
|
||||||
|
os.Exit(0)
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
//Setup the SIGTERM handler
|
||||||
|
SetupCloseHandler()
|
||||||
|
//Start the web server
|
||||||
|
fmt.Println("Starting web server on port", benchmarkWebserverListeningPort)
|
||||||
|
fmt.Println("In Zoraxy, point your test proxy rule to this server at the given port")
|
||||||
|
startWebServer()
|
||||||
|
select {}
|
||||||
|
}
|
42
tools/benchmark/server.go
Normal file
42
tools/benchmark/server.go
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Start the web server for reciving test request
|
||||||
|
// in Zoraxy, point test.localhost to this server at the given port in the start variables
|
||||||
|
func startWebServer() {
|
||||||
|
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// Print the request details to console
|
||||||
|
fmt.Printf("Timestamp: %s\n", time.Now().Format(time.RFC1123))
|
||||||
|
fmt.Printf("Request type: %s\n", r.Method)
|
||||||
|
fmt.Printf("Payload size: %d bytes\n", r.ContentLength)
|
||||||
|
fmt.Printf("Request URI: %s\n", r.RequestURI)
|
||||||
|
fmt.Printf("User Agent: %s\n", r.UserAgent())
|
||||||
|
fmt.Printf("Remote Address: %s\n", r.RemoteAddr)
|
||||||
|
fmt.Println("----------------------------------------")
|
||||||
|
|
||||||
|
//Set header to text
|
||||||
|
w.Header().Set("Content-Type", "text/plain")
|
||||||
|
// Send response, print the request details to web page
|
||||||
|
w.Write([]byte("----------------------------------------\n"))
|
||||||
|
w.Write([]byte("Request type: " + r.Method + "\n"))
|
||||||
|
w.Write([]byte(fmt.Sprintf("Payload size: %d bytes\n", r.ContentLength)))
|
||||||
|
w.Write([]byte("Request URI: " + r.RequestURI + "\n"))
|
||||||
|
w.Write([]byte("User Agent: " + r.UserAgent() + "\n"))
|
||||||
|
w.Write([]byte("Remote Address: " + r.RemoteAddr + "\n"))
|
||||||
|
w.Write([]byte("----------------------------------------\n"))
|
||||||
|
})
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
err := http.ListenAndServe(fmt.Sprintf(":%d", benchmarkWebserverListeningPort), nil)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("Failed to start server: %v\n", err)
|
||||||
|
stopchan <- true
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
}
|
5
tools/websocket_echo/go.mod
Normal file
5
tools/websocket_echo/go.mod
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
module aroz.org/zoraxy/websocket-echo
|
||||||
|
|
||||||
|
go 1.23.2
|
||||||
|
|
||||||
|
require github.com/gorilla/websocket v1.5.3
|
2
tools/websocket_echo/go.sum
Normal file
2
tools/websocket_echo/go.sum
Normal file
@ -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
tools/websocket_echo/main.go
Normal file
44
tools/websocket_echo/main.go
Normal file
@ -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
tools/websocket_echo/test.html
Normal file
67
tools/websocket_echo/test.html
Normal file
@ -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>
|
Reference in New Issue
Block a user