working commit

This commit is contained in:
2026-05-29 13:34:07 +02:00
parent bcdd2766e6
commit 4e2c548e97
15 changed files with 188 additions and 91 deletions
+1 -39
View File
@@ -19,18 +19,8 @@ type Service struct {
Port uint32 `json:"port" yaml:"port"`
}
type Database struct {
Basepath string `json:"basepath" yaml:"basepath"`
}
type Storage struct {
Basepath string `json:"basepath" yaml:"basepath"`
}
type Config struct {
Service Service `json:"service" yaml:"service"`
Database Database `json:"database" yaml:"database"`
Storage Storage `json:"storage" yaml:"storage"`
AsDaemon bool `json:"asDaemon" yaml:"asDaemon"`
Logpath string `json:"logpath" yaml:"logpath"`
Runpath string `json:"runpath" yaml:"runpath"`
@@ -53,23 +43,11 @@ func NewConfig() *Config {
runfile := fmt.Sprintf("%s.pid", srvname)
runpath := filepath.Join(rundir, runfile)
//certpath := fmt.Sprintf("%s.crt", srvname)
//certpath = filepath.Join(confdir, certpath)
//keypath := fmt.Sprintf("%s.crt", srvname)
//keypath = filepath.Join(confdir, keypath)
return &Config{
Service: Service{
Address: "0.0.0.0",
Address: "[::]",
Port: 1025,
},
Database: Database{
Basepath: datadir,
},
Storage: Storage{
Basepath: datadir,
},
AsDaemon: false,
Logpath: logpath,
Runpath: runpath,
@@ -124,20 +102,6 @@ func (conf *Config) ReadX509Cert() error {
conf.X509Key = string(keyBytes)
return err
}
/*
if conf.X509Cert != "" && conf.X509Key != "" {
x509Cert, err := base64.StdEncoding.DecodeString(conf.X509Cert)
if err != nil {
return err
}
conf.X509Cert = string(x509Cert)
x509Key, err := base64.StdEncoding.DecodeString(conf.X509Key)
if err != nil {
return err
}
conf.X509Key = string(x509Key)
}
*/
if conf.X509Cert == "" || conf.X509Key == "" {
if conf.Hostname == "" {
conf.Hostname, err = os.Hostname()
@@ -152,8 +116,6 @@ func (conf *Config) ReadX509Cert() error {
conf.X509Cert = string(certBytes)
conf.X509Key = string(keyBytes)
return err
}
return err
}
+49 -7
View File
@@ -5,23 +5,65 @@ package handler
import (
"net/http"
"sync"
"io"
"net"
"mproxy/app/proxoper"
"mproxy/app/router"
)
func (hand *Handler) ConnectTo(rctx *router.Context) {
hostaddr, _ := rctx.GetSubpath("hostaddr")
params := &proxoper.ConnectToParams{
Hostaddr: hostaddr,
}
ctx := rctx.GetContext()
_, err := hand.prop.ConnectTo(ctx, params)
hostaddr := rctx.GetHost()
hand.logg.Debugf("Hostaddr: [%s]", hostaddr)
destConn, err := net.Dial("tcp", hostaddr)
if err != nil {
hand.logg.Errorf("ConnectTo error: %v", err)
rctx.SetStatus(http.StatusInternalServerError)
return
}
if err != nil {
hand.logg.Errorf("ConnectTo error: %v", err)
rctx.SetStatus(http.StatusInternalServerError)
return
}
defer destConn.Close()
hijacker, hijackerOk := rctx.Writer.(http.Hijacker)
if !hijackerOk {
hand.logg.Errorf("Hijacking not OK")
rctx.SetStatus(http.StatusInternalServerError)
return
}
rctx.SetStatus(http.StatusOK)
clientConn, _, err := hijacker.Hijack()
if err != nil {
hand.logg.Errorf("Hijacking error: %v", err)
rctx.SetStatus(http.StatusInternalServerError)
return
}
var wg sync.WaitGroup
copyTo := func() {
defer wg.Done()
_, err = io.Copy(clientConn, destConn)
if err != nil {
hand.logg.Errorf("CopyTo error: %v", err)
return
}
}
copyFrom := func() {
defer wg.Done()
_, err = io.Copy(destConn, clientConn)
if err != nil {
hand.logg.Errorf("CopyFrom error: %v", err)
return
}
}
wg.Add(1)
go copyTo()
wg.Add(1)
go copyFrom()
wg.Wait()
return
}
+42
View File
@@ -0,0 +1,42 @@
/*
* Copyright 2026 Oleg Borodin <onborodin@gmail.com>
*/
package handler
import (
"context"
"errors"
"io"
)
func CopyWithContext(ctx context.Context, writer io.Writer, reader io.Reader) (int64, error) {
var err error
var size int64
var halt bool
buffer := make([]byte, 1024*4)
for {
select {
case <-ctx.Done():
err = errors.New("Break copy by context")
break
default:
}
rsize, err := reader.Read(buffer)
if err == io.EOF {
err = nil
halt = true
}
if err != nil {
return size, err
}
wsize, err := writer.Write(buffer[0:rsize])
size += int64(wsize)
if err != nil {
return size, err
}
if halt {
break
}
}
return size, err
}
+59
View File
@@ -0,0 +1,59 @@
/*
* Copyright 2026 Oleg Borodin <onborodin@gmail.com>
*/
package handler
import (
"net/http"
"io"
"context"
"time"
"mproxy/app/router"
)
func (hand *Handler) PlainCall(rctx *router.Context) {
hostaddr := rctx.GetHost()
hand.logg.Debugf("Hostaddr: [%s]", hostaddr)
ctx := rctx.GetContext()
ctx, _ = context.WithTimeout(ctx, 5*time.Second)
reqMethod := rctx.Request.Method
reqUrl := rctx.URL().String()
reqBody := rctx.Request.Body
req, err := http.NewRequestWithContext(ctx, reqMethod, reqUrl, reqBody)
if err != nil {
hand.logg.Errorf("Create request error: %v", err)
rctx.SetStatus(http.StatusInternalServerError)
return
}
for key := range rctx.Request.Header {
val := rctx.Request.Header.Get(key)
req.Header.Add(key, val)
}
httpClient := &http.Client{}
resp, err := httpClient.Do(req)
if err != nil {
hand.logg.Errorf("Call request error: %v", err)
rctx.SetStatus(http.StatusInternalServerError)
return
}
// Copy headers from remote side
for key := range resp.Header {
val := resp.Header.Get(key)
rctx.Writer.Header().Set(key, val)
}
// Copy status code
rctx.SetStatus(resp.StatusCode)
// Copy body
_, err = io.Copy(rctx.Writer, resp.Body)
if err != nil {
hand.logg.Errorf("Copy resp body error: %v", err)
return
}
return
}
-23
View File
@@ -1,23 +0,0 @@
/*
* Copyright 2026 Oleg Borodin <onborodin@gmail.com>
*/
package proxoper
import (
"context"
"io"
)
type ConnectToParams struct {
Hostaddr string
}
type ConnectToResult struct {
Stream io.Writer
}
func (oper *Operator) ConnectTo(ctx context.Context, param *ConnectToParams) (*ConnectToResult, error) {
var err error
res := &ConnectToResult{}
return res, err
}
+4
View File
@@ -68,6 +68,10 @@ func (rctx *Context) GetQuery(key string) string {
return rctx.Request.URL.Query().Get(key)
}
func (rctx *Context) GetHost() string {
return rctx.Request.Host
}
func (rctx *Context) GetHeader(key string) string {
return rctx.Request.Header.Get(key)
}
+1 -1
View File
@@ -15,7 +15,7 @@ const (
startRegex byte = '{'
stopRegex byte = '}'
defaultRegexp = `[a-zA-Z0-9_\.]+`
defaultRegexp = `[a-zA-Z0-9_\.:]+`
)
func pathCompiler(path string) (string, error) {
+3
View File
@@ -158,6 +158,9 @@ func (route Route) Match(req *http.Request) bool {
if req.Method != route.Method {
return false
}
if req.Method == http.MethodConnect {
return true
}
match := route.Regexp.MatchString(req.URL.Path)
if match {
return true
-2
View File
@@ -70,8 +70,6 @@ func (srv *Server) SetRundir(dir string) {
}
func (srv *Server) SetDatadir(dir string) {
srv.conf.Database.Basepath = dir
srv.conf.Storage.Basepath = dir
srv.conf.Datadir = dir
}
+12 -8
View File
@@ -30,9 +30,9 @@ type Service struct {
logg *logger.Logger
hsrv *http.Server
listen net.Listener
address string
portnum uint32
listen net.Listener
x509cert string
x509key string
protocol string
@@ -46,7 +46,7 @@ func NewService(params *ServiceParams) (*Service, error) {
portnum: params.Portnum,
x509cert: params.X509cert,
x509key: params.X509key,
protocol: "TCP",
protocol: "tcp",
}
svc.logg = logger.NewLoggerWithSubject("service")
return svc, err
@@ -54,7 +54,7 @@ func NewService(params *ServiceParams) (*Service, error) {
func (svc *Service) Build() error {
var err error
svc.logg.Infof("Service build ")
svc.logg.Infof("Service build")
svc.rout = router.NewRouter()
@@ -64,7 +64,14 @@ func (svc *Service) Build() error {
svc.rout.Use(svc.hand.AuthMiddleware)
svc.rout.Get(`/v3/api/service/hello`, svc.hand.SendHello)
svc.rout.Connect(`{hostaddr}`, svc.hand.ConnectTo)
svc.rout.Connect(``, svc.hand.ConnectTo)
svc.rout.Delete(`{uri:.*}`, svc.hand.PlainCall)
svc.rout.Get(`{uri:.*}`, svc.hand.PlainCall)
svc.rout.Head(`{uri:.*}`, svc.hand.PlainCall)
svc.rout.Patch(`{uri:.*}`, svc.hand.PlainCall)
svc.rout.Post(`{uri:.*}`, svc.hand.PlainCall)
svc.rout.NotFound(svc.hand.NotFound)
@@ -73,26 +80,23 @@ func (svc *Service) Build() error {
svc.logg.Infof("%s\t%s", item.Method, item.RawPath)
}
const useTLS = true
const useTLS = false
if useTLS {
tlsCert, err := tls.X509KeyPair([]byte(svc.x509cert), []byte(svc.x509key))
if err != nil {
return err
}
tlsConfig := tls.Config{
Certificates: []tls.Certificate{tlsCert},
ClientAuth: tls.NoClientCert,
InsecureSkipVerify: true,
}
listenAddress := fmt.Sprintf("%s:%d", svc.address, svc.portnum)
svc.listen, err = tls.Listen(svc.protocol, listenAddress, &tlsConfig)
if err != nil {
return err
}
} else {
listenAddress := fmt.Sprintf("%s:%d", svc.address, svc.portnum)
svc.listen, err = net.Listen(svc.protocol, listenAddress)