diff --git a/README.md b/README.md index 9706b06..6132cb6 100644 --- a/README.md +++ b/README.md @@ -22,11 +22,21 @@ ## 更新日志 +- 2024-05-28 v0.26.19 + - golang 版本升级到 1.22. + - 增加自动https,自动将http 重定向(301)到 https. + - 客户端命令行方式启动支持多个隧道ID,使用逗号拼接,示例:`npc -server=xxx:8024 -vkey=ytkpyr0er676m0r7,iwnbjfbvygvzyzzt` . + - 移除 nps.conf 参数 `https_just_proxy` , 调整 https 处理逻辑,如果上传了 https 证书,则由nps负责SSL (此方式可以获取真实IP), + 否则走端口转发模式(使用本地证书,nps 获取不到真实IP), 如下图所示。 + ![image](image/new/https.png) + + + - 2024-02-27 v0.26.18 ***新增***:nps.conf 新增 `tls_bridge_port=8025` 参数,当 `tls_enable=true` 时,nps 会监听8025端口,作为 tls 的连接端口。 客户端可以选择连接 tls 端口或者非 tls 端口: `npc.exe -server=xxx:8024 -vkey=xxx` 或 `npc.exe -server=xxx:8025 -vkey=xxx -tls_enable=true` - + - 2024-01-31 v0.26.17 ***说明***:考虑到 npc 历史版本客户端众多,版本号不同旧版本客户端无法连接,为了兼容,仓库版本号将继续沿用 0.26.xx diff --git a/conf/clients.json b/conf/clients.json index 8e1be7b..ff1090d 100644 --- a/conf/clients.json +++ b/conf/clients.json @@ -1,2 +1,2 @@ -{"Cnf":{"U":"","P":"","Compress":false,"Crypt":false},"Id":2,"VerifyKey":"a82kjhdyllqnlruk","Addr":"127.0.0.1","Remark":"","Status":true,"IsConnect":false,"RateLimit":0,"Flow":{"ExportFlow":551,"InletFlow":551,"FlowLimit":0},"Rate":{"NowRate":0},"NoStore":false,"NoDisplay":false,"MaxConn":0,"NowConn":0,"WebUserName":"","WebPassword":"","ConfigConnAllow":true,"MaxTunnelNum":0,"Version":"0.26.12","BlackIpList":[""]} +{"Cnf":{"U":"","P":"","Compress":false,"Crypt":false},"Id":2,"VerifyKey":"a82kjhdyllqnlruk","Addr":"127.0.0.1","Remark":"","Status":true,"IsConnect":false,"RateLimit":0,"Flow":{"ExportFlow":551,"InletFlow":551,"FlowLimit":0},"Rate":{"NowRate":0},"NoStore":false,"NoDisplay":false,"MaxConn":0,"NowConn":0,"WebUserName":"","WebPassword":"","ConfigConnAllow":true,"MaxTunnelNum":0,"Version":"0.26.19","BlackIpList":[""],"LastOnlineTime":"2024-05-28 15:08:39"} *#* \ No newline at end of file diff --git a/conf/hosts.json b/conf/hosts.json index 4028236..5c17559 100644 --- a/conf/hosts.json +++ b/conf/hosts.json @@ -1,2 +1,2 @@ -{"Id":1,"Host":"testlocal.com","HeaderChange":"","HostChange":"","Location":"/","Remark":"","Scheme":"all","CertFilePath":"","KeyFilePath":"","NoStore":false,"IsClose":false,"Flow":{"ExportFlow":0,"InletFlow":0,"FlowLimit":0},"Client":{"Cnf":{"U":"","P":"","Compress":false,"Crypt":false},"Id":2,"VerifyKey":"a82kjhdyllqnlruk","Addr":"127.0.0.1","Remark":"","Status":true,"IsConnect":false,"RateLimit":0,"Flow":{"ExportFlow":551,"InletFlow":551,"FlowLimit":0},"Rate":{"NowRate":0},"NoStore":false,"NoDisplay":false,"MaxConn":0,"NowConn":0,"WebUserName":"","WebPassword":"","ConfigConnAllow":true,"MaxTunnelNum":0,"Version":"0.26.12","BlackIpList":[""]},"Target":{"TargetStr":"127.0.0.1:8080","TargetArr":["127.0.0.1:8080"],"LocalProxy":false}} +{"Id":1,"Host":"test.test.pp2pdf.com","HeaderChange":"","HostChange":"","Location":"/","Remark":"","Scheme":"all","CertFilePath":"-----BEGIN CERTIFICATE-----\r\nMIIGADCCBOigAwIBAgIQC0shW9rSx8iw/8ZZiE2w3TANBgkqhkiG9w0BAQsFADBu\r\nMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\r\nd3cuZGlnaWNlcnQuY29tMS0wKwYDVQQDEyRFbmNyeXB0aW9uIEV2ZXJ5d2hlcmUg\r\nRFYgVExTIENBIC0gRzIwHhcNMjQwNTI4MDAwMDAwW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U0eL3+sTq2fgEzfNLIRqy4m93Tru9RLUOcrLp2+AlUXpQU6tqBdkOg==\r\n-----END RSA PRIVATE KEY-----\r\n","NoStore":false,"IsClose":false,"AutoHttps":false,"Flow":{"ExportFlow":0,"InletFlow":0,"FlowLimit":0},"Client":{"Cnf":{"U":"","P":"","Compress":false,"Crypt":false},"Id":2,"VerifyKey":"a82kjhdyllqnlruk","Addr":"127.0.0.1","Remark":"","Status":true,"IsConnect":false,"RateLimit":0,"Flow":{"ExportFlow":551,"InletFlow":551,"FlowLimit":0},"Rate":{"NowRate":0},"NoStore":false,"NoDisplay":false,"MaxConn":0,"NowConn":0,"WebUserName":"","WebPassword":"","ConfigConnAllow":true,"MaxTunnelNum":0,"Version":"0.26.19","BlackIpList":[""],"LastOnlineTime":"2024-05-28 15:08:39"},"Target":{"TargetStr":"127.0.0.1:9090","TargetArr":null,"LocalProxy":false}} *#* \ No newline at end of file diff --git a/conf/nps.conf b/conf/nps.conf index 281d952..2a392a6 100755 --- a/conf/nps.conf +++ b/conf/nps.conf @@ -84,7 +84,7 @@ http_cache=false http_cache_length=100 #get origin ip -http_add_origin_header=false +#http_add_origin_header=false #pprof debug options #pprof_ip=0.0.0.0 diff --git a/image/new/https.png b/image/new/https.png new file mode 100644 index 0000000..50f8822 Binary files /dev/null and b/image/new/https.png differ diff --git a/lib/common/util.go b/lib/common/util.go index f9e5e2d..8fbf473 100755 --- a/lib/common/util.go +++ b/lib/common/util.go @@ -7,6 +7,7 @@ import ( "encoding/binary" "errors" "fmt" + "github.com/astaxie/beego" "github.com/astaxie/beego/logs" "html/template" "io" @@ -23,7 +24,7 @@ import ( "ehang.io/nps/lib/crypt" ) -//Get the corresponding IP address through domain name +// Get the corresponding IP address through domain name func GetHostByName(hostname string) string { if !DomainCheck(hostname) { return hostname @@ -39,7 +40,7 @@ func GetHostByName(hostname string) string { return "" } -//Check the legality of domain +// Check the legality of domain func DomainCheck(domain string) bool { var match bool IsLine := "^((http://)|(https://))?([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}(/)" @@ -51,7 +52,7 @@ func DomainCheck(domain string) bool { return match } -//Check if the Request request is validated +// Check if the Request request is validated func CheckAuth(r *http.Request, user, passwd string) bool { s := strings.SplitN(r.Header.Get("Authorization"), " ", 2) if len(s) != 2 { @@ -73,7 +74,7 @@ func CheckAuth(r *http.Request, user, passwd string) bool { return pair[0] == user && pair[1] == passwd } -//get bool by str +// get bool by str func GetBoolByStr(s string) bool { switch s { case "1", "true": @@ -82,7 +83,7 @@ func GetBoolByStr(s string) bool { return false } -//get str by bool +// get str by bool func GetStrByBool(b bool) string { if b { return "1" @@ -90,19 +91,19 @@ func GetStrByBool(b bool) string { return "0" } -//int +// int func GetIntNoErrByStr(str string) int { i, _ := strconv.Atoi(strings.TrimSpace(str)) return i } -//Get verify value +// Get verify value func Getverifyval(vkey string) string { return crypt.Md5(vkey) } -//Change headers and host of request -func ChangeHostAndHeader(r *http.Request, host string, header string, addr string, addOrigin bool) { +// Change headers and host of request +func ChangeHostAndHeader(r *http.Request, host string, header string, addr string) { if host != "" { r.Host = host } @@ -119,13 +120,17 @@ func ChangeHostAndHeader(r *http.Request, host string, header string, addr strin if prior, ok := r.Header["X-Forwarded-For"]; ok { addr = strings.Join(prior, ", ") + ", " + addr } + + addOrigin, _ := beego.AppConfig.Bool("http_add_origin_header") + if addOrigin { + logs.Debug("set X-Forwarded-For X-Real-IP = " + addr) r.Header.Set("X-Forwarded-For", addr) r.Header.Set("X-Real-IP", addr) } } -//Read file content by file path +// Read file content by file path func ReadAllFromFile(filePath string) ([]byte, error) { f, err := os.Open(filePath) if err != nil { @@ -145,7 +150,7 @@ func FileExists(name string) bool { return true } -//Judge whether the TCP port can open normally +// Judge whether the TCP port can open normally func TestTcpPort(port int) bool { l, err := net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), port, ""}) defer func() { @@ -159,7 +164,7 @@ func TestTcpPort(port int) bool { return true } -//Judge whether the UDP port can open normally +// Judge whether the UDP port can open normally func TestUdpPort(port int) bool { l, err := net.ListenUDP("udp", &net.UDPAddr{net.ParseIP("0.0.0.0"), port, ""}) defer func() { @@ -173,9 +178,9 @@ func TestUdpPort(port int) bool { return true } -//Write length and individual byte data -//Length prevents sticking -//# Characters are used to separate data +// Write length and individual byte data +// Length prevents sticking +// # Characters are used to separate data func BinaryWrite(raw *bytes.Buffer, v ...string) { b := GetWriteStr(v...) binary.Write(raw, binary.LittleEndian, int32(len(b))) @@ -194,7 +199,7 @@ func GetWriteStr(v ...string) []byte { return buffer.Bytes() } -//inArray str interface +// inArray str interface func InStrArr(arr []string, val string) bool { for _, v := range arr { if v == val { @@ -204,7 +209,7 @@ func InStrArr(arr []string, val string) bool { return false } -//inArray int interface +// inArray int interface func InIntArr(arr []int, val int) bool { for _, v := range arr { if v == val { @@ -214,7 +219,7 @@ func InIntArr(arr []int, val int) bool { return false } -//format ports str to a int array +// format ports str to a int array func GetPorts(p string) []int { var ps []int arr := strings.Split(p, ",") @@ -238,7 +243,7 @@ func GetPorts(p string) []int { return ps } -//is the string a port +// is the string a port func IsPort(p string) bool { pi, err := strconv.Atoi(p) if err != nil { @@ -250,7 +255,7 @@ func IsPort(p string) bool { return true } -//if the s is just a port,return 127.0.0.1:s +// if the s is just a port,return 127.0.0.1:s func FormatAddress(s string) string { if strings.Contains(s, ":") { return s @@ -258,13 +263,13 @@ func FormatAddress(s string) string { return "127.0.0.1:" + s } -//get address from the complete address +// get address from the complete address func GetIpByAddr(addr string) string { arr := strings.Split(addr, ":") return arr[0] } -//get port from the complete address +// get port from the complete address func GetPortByAddr(addr string) int { arr := strings.Split(addr, ":") if len(arr) < 2 { @@ -327,7 +332,7 @@ func CopyBuffer(dst io.Writer, src io.Reader, label ...string) (written int64, e return written, err } -//send this ip forget to get a local udp port +// send this ip forget to get a local udp port func GetLocalUdpAddr() (net.Conn, error) { tmpConn, err := net.Dial("udp", "114.114.114.114:53") if err != nil { @@ -336,7 +341,7 @@ func GetLocalUdpAddr() (net.Conn, error) { return tmpConn, tmpConn.Close() } -//parse template +// parse template func ParseStr(str string) (string, error) { tmp := template.New("npc") var err error @@ -350,7 +355,7 @@ func ParseStr(str string) (string, error) { return w.String(), nil } -//get env +// get env func GetEnvMap() map[string]string { m := make(map[string]string) environ := os.Environ() @@ -363,7 +368,7 @@ func GetEnvMap() map[string]string { return m } -//throw the empty element of the string array +// throw the empty element of the string array func TrimArr(arr []string) []string { newArr := make([]string, 0) for _, v := range arr { @@ -374,7 +379,6 @@ func TrimArr(arr []string) []string { return newArr } -// func IsArrContains(arr []string, val string) bool { if arr == nil { return false @@ -387,7 +391,7 @@ func IsArrContains(arr []string, val string) bool { return false } -//remove value from string array +// remove value from string array func RemoveArrVal(arr []string, val string) []string { for k, v := range arr { if v == val { @@ -398,7 +402,7 @@ func RemoveArrVal(arr []string, val string) []string { return arr } -//convert bytes to num +// convert bytes to num func BytesToNum(b []byte) int { var str string for i := 0; i < len(b); i++ { @@ -408,7 +412,7 @@ func BytesToNum(b []byte) int { return int(x) } -//get the length of the sync map +// get the length of the sync map func GeSynctMapLen(m sync.Map) int { var c int m.Range(func(key, value interface{}) bool { diff --git a/lib/file/obj.go b/lib/file/obj.go index 1a11c8a..a582e1d 100644 --- a/lib/file/obj.go +++ b/lib/file/obj.go @@ -174,6 +174,7 @@ type Host struct { KeyFilePath string NoStore bool IsClose bool + AutoHttps bool // 自动https Flow *Flow Client *Client Target *Target //目标 diff --git a/server/proxy/http.go b/server/proxy/http.go index 7ab47d8..0140dfa 100644 --- a/server/proxy/http.go +++ b/server/proxy/http.go @@ -102,6 +102,20 @@ func (s *httpServer) Close() error { func (s *httpServer) handleTunneling(w http.ResponseWriter, r *http.Request) { + var host *file.Host + var err error + host, err = file.GetDb().GetInfoByHost(r.Host, r) + if err != nil { + logs.Debug("the url %s %s %s can't be parsed!", r.URL.Scheme, r.Host, r.RequestURI) + return + } + + // 自动 http 301 https + if host.AutoHttps && r.TLS == nil { + http.Redirect(w, r, "https://"+r.Host+r.RequestURI, http.StatusMovedPermanently) + return + } + if r.Header.Get("Upgrade") != "" { rProxy := NewHttpReverseProxy(s) rProxy.ServeHTTP(w, r) @@ -246,7 +260,7 @@ reset: } //change the host and header and set proxy setting - common.ChangeHostAndHeader(r, host.HostChange, host.HeaderChange, c.Conn.RemoteAddr().String(), s.addOrigin) + common.ChangeHostAndHeader(r, host.HostChange, host.HeaderChange, c.Conn.RemoteAddr().String()) logs.Info("%s request, method %s, host %s, url %s, remote address %s, target %s", r.URL.Scheme, r.Method, r.Host, r.URL.Path, remoteAddr, lk.Host) @@ -303,3 +317,35 @@ func (s *httpServer) NewServer(port int, scheme string) *http.Server { TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)), } } + +func (s *httpServer) NewServerWithTls(port int, scheme string, l net.Listener, certFile string, keyFile string) error { + + if certFile == "" || keyFile == "" { + logs.Error("证书文件为空") + return nil + } + var certFileByte = []byte(certFile) + var keyFileByte = []byte(keyFile) + + config := &tls.Config{} + config.Certificates = make([]tls.Certificate, 1) + + var err error + config.Certificates[0], err = tls.X509KeyPair(certFileByte, keyFileByte) + if err != nil { + return err + } + + s2 := &http.Server{ + Addr: ":" + strconv.Itoa(port), + Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + r.URL.Scheme = scheme + s.handleTunneling(w, r) + }), + // Disable HTTP/2. + TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)), + TLSConfig: config, + } + + return s2.ServeTLS(l, "", "") +} diff --git a/server/proxy/https.go b/server/proxy/https.go index 8716617..4e4d4f2 100644 --- a/server/proxy/https.go +++ b/server/proxy/https.go @@ -4,7 +4,6 @@ import ( "net" "net/http" "net/url" - "path/filepath" "sync" "ehang.io/nps/lib/cache" @@ -12,7 +11,6 @@ import ( "ehang.io/nps/lib/conn" "ehang.io/nps/lib/crypt" "ehang.io/nps/lib/file" - "github.com/astaxie/beego" "github.com/astaxie/beego/logs" "github.com/pkg/errors" ) @@ -21,6 +19,7 @@ type HttpsServer struct { httpServer listener net.Listener httpsListenerMap sync.Map + hostIdCertMap sync.Map } func NewHttpsServer(l net.Listener, bridge NetBridge, useCache bool, cacheLen int) *HttpsServer { @@ -33,63 +32,170 @@ func NewHttpsServer(l net.Listener, bridge NetBridge, useCache bool, cacheLen in return https } -//start https server +// start https server func (https *HttpsServer) Start() error { - var err error - if https.errorContent, err = common.ReadAllFromFile(filepath.Join(common.GetRunPath(), "web", "static", "page", "error.html")); err != nil { - https.errorContent = []byte("nps 404") - } - if b, err := beego.AppConfig.Bool("https_just_proxy"); err == nil && b { - conn.Accept(https.listener, func(c net.Conn) { - https.handleHttps(c) - }) - } else { - //start the default listener - certFile := beego.AppConfig.String("https_default_cert_file") - keyFile := beego.AppConfig.String("https_default_key_file") - if common.FileExists(certFile) && common.FileExists(keyFile) { - l := NewHttpsListener(https.listener) - https.NewHttps(l, certFile, keyFile) - https.httpsListenerMap.Store("default", l) - } - conn.Accept(https.listener, func(c net.Conn) { - serverName, rb := GetServerNameFromClientHello(c) - //if the clientHello does not contains sni ,use the default ssl certificate - if serverName == "" { - serverName = "default" - } - var l *HttpsListener - if v, ok := https.httpsListenerMap.Load(serverName); ok { - l = v.(*HttpsListener) + + conn.Accept(https.listener, func(c net.Conn) { + serverName, rb := GetServerNameFromClientHello(c) + r := buildHttpsRequest(serverName) + if host, err := file.GetDb().GetInfoByHost(serverName, r); err != nil { + c.Close() + logs.Debug("the url %s can't be parsed!,remote addr %s", serverName, c.RemoteAddr().String()) + return + } else { + if host.CertFilePath == "" || host.KeyFilePath == "" { + logs.Debug("加载客户端本地证书") + https.handleHttps2(c, serverName, rb, r) } else { - r := buildHttpsRequest(serverName) - if host, err := file.GetDb().GetInfoByHost(serverName, r); err != nil { - c.Close() - logs.Notice("the url %s can't be parsed!,remote addr %s", serverName, c.RemoteAddr().String()) - return - } else { - if !common.FileExists(host.CertFilePath) || !common.FileExists(host.KeyFilePath) { - //if the host cert file or key file is not set ,use the default file - if v, ok := https.httpsListenerMap.Load("default"); ok { - l = v.(*HttpsListener) - } else { - c.Close() - logs.Error("the key %s cert %s file is not exist", host.KeyFilePath, host.CertFilePath) - return - } - } else { - l = NewHttpsListener(https.listener) - https.NewHttps(l, host.CertFilePath, host.KeyFilePath) - https.httpsListenerMap.Store(serverName, l) + logs.Debug("使用上传证书") + https.cert(host, c, rb, host.CertFilePath, host.KeyFilePath) + } + } + }) + + //var err error + //if https.errorContent, err = common.ReadAllFromFile(filepath.Join(common.GetRunPath(), "web", "static", "page", "error.html")); err != nil { + // https.errorContent = []byte("nps 404") + //} + //if b, err := beego.AppConfig.Bool("https_just_proxy"); err == nil && b { + // conn.Accept(https.listener, func(c net.Conn) { + // https.handleHttps(c) + // }) + //} else { + // //start the default listener + // certFile := beego.AppConfig.String("https_default_cert_file") + // keyFile := beego.AppConfig.String("https_default_key_file") + // if common.FileExists(certFile) && common.FileExists(keyFile) { + // l := NewHttpsListener(https.listener) + // https.NewHttps(l, certFile, keyFile) + // https.httpsListenerMap.Store("default", l) + // } + // conn.Accept(https.listener, func(c net.Conn) { + // serverName, rb := GetServerNameFromClientHello(c) + // //if the clientHello does not contains sni ,use the default ssl certificate + // if serverName == "" { + // serverName = "default" + // } + // var l *HttpsListener + // if v, ok := https.httpsListenerMap.Load(serverName); ok { + // l = v.(*HttpsListener) + // } else { + // r := buildHttpsRequest(serverName) + // if host, err := file.GetDb().GetInfoByHost(serverName, r); err != nil { + // c.Close() + // logs.Notice("the url %s can't be parsed!,remote addr %s", serverName, c.RemoteAddr().String()) + // return + // } else { + // if !common.FileExists(host.CertFilePath) || !common.FileExists(host.KeyFilePath) { + // //if the host cert file or key file is not set ,use the default file + // if v, ok := https.httpsListenerMap.Load("default"); ok { + // l = v.(*HttpsListener) + // } else { + // c.Close() + // logs.Error("the key %s cert %s file is not exist", host.KeyFilePath, host.CertFilePath) + // return + // } + // } else { + // l = NewHttpsListener(https.listener) + // https.NewHttps(l, host.CertFilePath, host.KeyFilePath) + // https.httpsListenerMap.Store(serverName, l) + // } + // } + // } + // acceptConn := conn.NewConn(c) + // acceptConn.Rb = rb + // l.acceptConn <- acceptConn + // }) + //} + return nil +} + +func (https *HttpsServer) cert(host *file.Host, c net.Conn, rb []byte, certFileUrl string, keyFileUrl string) { + var l *HttpsListener + i := 0 + https.hostIdCertMap.Range(func(key, value interface{}) bool { + i++ + // 如果host Id 不存在,则删除map + if id, ok := key.(int); ok { + var err error + _, err = file.GetDb().GetHostById(id) + if err != nil { + // 说明这个host已经不存了,需要释放Listener + logs.Error(err) + if oldL, ok := https.httpsListenerMap.Load(value); ok { + err := oldL.(*HttpsListener).Close() + if err != nil { + logs.Error(err) } + https.httpsListenerMap.Delete(value) + https.hostIdCertMap.Delete(key) + logs.Info("Listener 已释放") } } - acceptConn := conn.NewConn(c) - acceptConn.Rb = rb - l.acceptConn <- acceptConn - }) + } + return true + }) + + logs.Info("当前 Listener 连接数量", i) + + if cert, ok := https.hostIdCertMap.Load(host.Id); ok { + if cert == certFileUrl { + // 证书已经存在,直接加载 + if v, ok := https.httpsListenerMap.Load(certFileUrl); ok { + l = v.(*HttpsListener) + } + } else { + // 证书修改过,重新加载证书 + l = NewHttpsListener(https.listener) + https.NewHttps(l, certFileUrl, keyFileUrl) + if oldL, ok := https.httpsListenerMap.Load(cert); ok { + err := oldL.(*HttpsListener).Close() + if err != nil { + logs.Error(err) + } + https.httpsListenerMap.Delete(cert) + } + https.httpsListenerMap.Store(certFileUrl, l) + https.hostIdCertMap.Store(host.Id, certFileUrl) + } + } else { + // 第一次加载证书 + l = NewHttpsListener(https.listener) + https.NewHttps(l, certFileUrl, keyFileUrl) + https.httpsListenerMap.Store(certFileUrl, l) + https.hostIdCertMap.Store(host.Id, certFileUrl) } - return nil + + acceptConn := conn.NewConn(c) + acceptConn.Rb = rb + l.acceptConn <- acceptConn +} + +// handle the https which is just proxy to other client +func (https *HttpsServer) handleHttps2(c net.Conn, hostName string, rb []byte, r *http.Request) { + var targetAddr string + var host *file.Host + var err error + if host, err = file.GetDb().GetInfoByHost(hostName, r); err != nil { + c.Close() + logs.Debug("the url %s can't be parsed!", hostName) + return + } + if err := https.CheckFlowAndConnNum(host.Client); err != nil { + logs.Debug("client id %d, host id %d, error %s, when https connection", host.Client.Id, host.Id, err.Error()) + c.Close() + return + } + defer host.Client.AddConn() + if err = https.auth(r, conn.NewConn(c), host.Client.Cnf.U, host.Client.Cnf.P); err != nil { + logs.Warn("auth error", err, r.RemoteAddr) + return + } + if targetAddr, err = host.Target.GetRandomTarget(); err != nil { + logs.Warn(err.Error()) + } + logs.Info("new https connection,clientId %d,host %s,remote address %s", host.Client.Id, r.Host, c.RemoteAddr().String()) + https.DealClient(conn.NewConn(c), host.Client, targetAddr, rb, common.CONN_TCP, nil, host.Client.Flow, host.Target.LocalProxy, nil) } // close @@ -100,11 +206,13 @@ func (https *HttpsServer) Close() error { // new https server by cert and key file func (https *HttpsServer) NewHttps(l net.Listener, certFile string, keyFile string) { go func() { - logs.Error(https.NewServer(0, "https").ServeTLS(l, certFile, keyFile)) + //logs.Error(https.NewServer(0, "https").ServeTLS(l, certFile, keyFile)) + logs.Error(https.NewServerWithTls(0, "https", l, certFile, keyFile)) + }() } -//handle the https which is just proxy to other client +// handle the https which is just proxy to other client func (https *HttpsServer) handleHttps(c net.Conn) { hostName, rb := GetServerNameFromClientHello(c) var targetAddr string diff --git a/server/proxy/websocket.go b/server/proxy/websocket.go index 4692d5e..73df72c 100644 --- a/server/proxy/websocket.go +++ b/server/proxy/websocket.go @@ -100,7 +100,7 @@ func NewHttpReverseProxy(s *httpServer) *HttpReverseProxy { proxy := NewReverseProxy(&httputil.ReverseProxy{ Director: func(r *http.Request) { host := r.Context().Value("host").(*file.Host) - common.ChangeHostAndHeader(r, host.HostChange, host.HeaderChange, "", false) + common.ChangeHostAndHeader(r, host.HostChange, host.HeaderChange, "") }, Transport: &http.Transport{ ResponseHeaderTimeout: rp.responseHeaderTimeout, diff --git a/web/controllers/index.go b/web/controllers/index.go index 57c7d2c..cd26c35 100755 --- a/web/controllers/index.go +++ b/web/controllers/index.go @@ -272,6 +272,7 @@ func (s *IndexController) AddHost() { Scheme: s.getEscapeString("scheme"), KeyFilePath: s.getEscapeString("key_file_path"), CertFilePath: s.getEscapeString("cert_file_path"), + AutoHttps: s.GetBoolNoErr("AutoHttps"), } var err error if h.Client, err = file.GetDb().GetClient(s.GetIntNoErr("client_id")); err != nil { @@ -324,6 +325,7 @@ func (s *IndexController) EditHost() { h.KeyFilePath = s.getEscapeString("key_file_path") h.CertFilePath = s.getEscapeString("cert_file_path") h.Target.LocalProxy = s.GetBoolNoErr("local_proxy") + h.AutoHttps = s.GetBoolNoErr("AutoHttps") file.GetDb().JsonDb.StoreHostToJsonFile() } s.AjaxOk("modified success") diff --git a/web/static/js/language.js b/web/static/js/language.js index c7bd88e..7118553 100644 --- a/web/static/js/language.js +++ b/web/static/js/language.js @@ -59,7 +59,7 @@ $.fn.cloudLang = function () { $.ajax({ type: 'GET', - url: window.nps.web_base_url + '/static/page/languages.xml?v=20240227', + url: window.nps.web_base_url + '/static/page/languages.xml?v=20240528', dataType: 'xml', success: function (xml) { languages['content'] = xml2json($(xml).children())['content']; diff --git a/web/static/page/languages.xml b/web/static/page/languages.xml index 6c5d759..9b9441c 100644 --- a/web/static/page/languages.xml +++ b/web/static/page/languages.xml @@ -279,13 +279,13 @@ HTTP port - HTTPS 证书 + HTTPS 证书(pem格式) HTTPS cert HTTPS - HTTPS 密钥 + HTTPS 密钥(key格式) HTTPS key diff --git a/web/views/index/hadd.html b/web/views/index/hadd.html index 6c3087b..6b0edeb 100644 --- a/web/views/index/hadd.html +++ b/web/views/index/hadd.html @@ -32,20 +32,29 @@ - {{if eq false .https_just_proxy}} + +
+ +
+ +
+
+
- +
- +
- {{end}}
@@ -100,13 +109,53 @@
- + diff --git a/web/views/login/register.html b/web/views/login/register.html index 8e7f0e3..30c7d48 100644 --- a/web/views/login/register.html +++ b/web/views/login/register.html @@ -19,7 +19,7 @@ - + diff --git a/web/views/public/layout.html b/web/views/public/layout.html index 4047d6f..2696f91 100644 --- a/web/views/public/layout.html +++ b/web/views/public/layout.html @@ -26,7 +26,7 @@ - +