Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support mieru protocol (issue #1563) #1574

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
237 changes: 237 additions & 0 deletions adapter/outbound/mieru.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,237 @@
package outbound

import (
"context"
"fmt"
"net"
"runtime"
"strconv"

mieruclient "github.com/enfein/mieru/v3/apis/client"
mierumodel "github.com/enfein/mieru/v3/apis/model"
mierupb "github.com/enfein/mieru/v3/pkg/appctl/appctlpb"
N "github.com/metacubex/mihomo/common/net"
"github.com/metacubex/mihomo/component/dialer"
C "github.com/metacubex/mihomo/constant"
"google.golang.org/protobuf/proto"
)

const (
// Default MTU used in mieru UDP transport.
mieruDefaultMTU = 1400
)

type Mieru struct {
*Base
option *MieruOption
client mieruclient.Client
}

type MieruOption struct {
BasicOption
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port,omitempty"`
PortRange string `proxy:"port-range,omitempty"`
Transport string `proxy:"transport"`
UserName string `proxy:"username"`
Password string `proxy:"password"`
MTU int `proxy:"mtu,omitempty"`
}

// DialContext implements C.ProxyAdapter
func (m *Mieru) DialContext(ctx context.Context, metadata *C.Metadata, _ ...dialer.Option) (_ C.Conn, err error) {
c, err := m.client.DialContext(ctx)
if err != nil {
return nil, err
}

addrSpec := mierumodel.AddrSpec{
Port: int(metadata.DstPort),
}
if metadata.Host != "" {
addrSpec.FQDN = metadata.Host
} else {
addrSpec.IP = metadata.DstIP.AsSlice()
}
if err := m.client.HandshakeWithConnect(ctx, c, addrSpec); err != nil {
return nil, err
}
return NewConn(N.NewRefConn(c, m), m), nil
}

func NewMieru(option MieruOption) (*Mieru, error) {
config, err := buildMieruClientConfig(option)
if err != nil {
return nil, fmt.Errorf("failed to build mieru client config: %w", err)
}
c := mieruclient.NewClient()
if err := c.Store(config); err != nil {
return nil, fmt.Errorf("failed to store mieru client config: %w", err)
}
if err := c.Start(); err != nil {
return nil, fmt.Errorf("failed to start mieru client: %w", err)
}

var addr string
if option.Port != 0 {
addr = net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
} else {
beginPort, _, _ := beginAndEndPortFromPortRange(option.PortRange)
addr = net.JoinHostPort(option.Server, strconv.Itoa(beginPort))
}
outbound := &Mieru{
Base: &Base{
name: option.Name,
addr: addr,
iface: option.Interface,
tp: C.Mieru,
udp: false,
xudp: false,
rmark: option.RoutingMark,
prefer: C.NewDNSPrefer(option.IPVersion),
},
option: &option,
client: c,
}
runtime.SetFinalizer(outbound, closeMieru)
return outbound, nil
}

func closeMieru(m *Mieru) {
if m.client != nil {
m.client.Stop()
}
}

func buildMieruClientConfig(option MieruOption) (*mieruclient.ClientConfig, error) {
if err := validateMieruOption(option); err != nil {
return nil, fmt.Errorf("failed to validate mieru option: %w", err)
}

var transportProtocol *mierupb.TransportProtocol
if option.Transport == "TCP" {
transportProtocol = mierupb.TransportProtocol_TCP.Enum()
} else if option.Transport == "UDP" {
transportProtocol = mierupb.TransportProtocol_UDP.Enum()
}
var server *mierupb.ServerEndpoint
if net.ParseIP(option.Server) != nil {
// server is an IP address
if option.PortRange != "" {
server = &mierupb.ServerEndpoint{
IpAddress: proto.String(option.Server),
PortBindings: []*mierupb.PortBinding{
{
PortRange: proto.String(option.PortRange),
Protocol: transportProtocol,
},
},
}
} else {
server = &mierupb.ServerEndpoint{
IpAddress: proto.String(option.Server),
PortBindings: []*mierupb.PortBinding{
{
Port: proto.Int32(int32(option.Port)),
Protocol: transportProtocol,
},
},
}
}
} else {
// server is a domain name
if option.PortRange != "" {
server = &mierupb.ServerEndpoint{
DomainName: proto.String(option.Server),
PortBindings: []*mierupb.PortBinding{
{
PortRange: proto.String(option.PortRange),
Protocol: transportProtocol,
},
},
}
} else {
server = &mierupb.ServerEndpoint{
DomainName: proto.String(option.Server),
PortBindings: []*mierupb.PortBinding{
{
Port: proto.Int32(int32(option.Port)),
Protocol: transportProtocol,
},
},
}
}
}
if option.MTU == 0 {
option.MTU = mieruDefaultMTU
}
return &mieruclient.ClientConfig{
Profile: &mierupb.ClientProfile{
ProfileName: proto.String(option.Name),
User: &mierupb.User{
Name: proto.String(option.UserName),
Password: proto.String(option.Password),
},
Servers: []*mierupb.ServerEndpoint{server},
Mtu: proto.Int32(int32(option.MTU)),
Multiplexing: &mierupb.MultiplexingConfig{
// Multiplexing doesn't work well with connection tracking.
Level: mierupb.MultiplexingLevel_MULTIPLEXING_OFF.Enum(),
},
},
}, nil
}

func validateMieruOption(option MieruOption) error {
if option.DialerProxy != "" {
return fmt.Errorf("dialer proxy is not supported")
}
if option.Name == "" {
return fmt.Errorf("name is empty")
}
if option.Server == "" {
return fmt.Errorf("server is empty")
}
if option.Port == 0 && option.PortRange == "" {
return fmt.Errorf("either port or port-range must be set")
}
if option.Port != 0 && option.PortRange != "" {
return fmt.Errorf("port and port-range cannot be set at the same time")
}
if option.Port != 0 && (option.Port < 1 || option.Port > 65535) {
return fmt.Errorf("port must be between 1 and 65535")
}
if option.PortRange != "" {
begin, end, err := beginAndEndPortFromPortRange(option.PortRange)
if err != nil {
return fmt.Errorf("invalid port-range format")
}
if begin < 1 || begin > 65535 {
return fmt.Errorf("begin port must be between 1 and 65535")
}
if end < 1 || end > 65535 {
return fmt.Errorf("end port must be between 1 and 65535")
}
if begin > end {
return fmt.Errorf("begin port must be less than or equal to end port")
}
}

if option.Transport != "TCP" && option.Transport != "UDP" {
return fmt.Errorf("transport must be TCP or UDP")
}
if option.UserName == "" {
return fmt.Errorf("username is empty")
}
if option.Password == "" {
return fmt.Errorf("password is empty")
}
return nil
}

func beginAndEndPortFromPortRange(portRange string) (int, int, error) {
var begin, end int
_, err := fmt.Sscanf(portRange, "%d-%d", &begin, &end)
return begin, end, err
}
81 changes: 81 additions & 0 deletions adapter/outbound/mieru_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package outbound

import "testing"

func TestNewMieru(t *testing.T) {
testCases := []struct {
option MieruOption
wantBaseAddr string
}{
{
option: MieruOption{
Name: "test",
Server: "1.2.3.4",
Port: 10000,
Transport: "TCP",
UserName: "test",
Password: "test",
},
wantBaseAddr: "1.2.3.4:10000",
},
{
option: MieruOption{
Name: "test",
Server: "example.com",
PortRange: "10001-10002",
Transport: "UDP",
UserName: "test",
Password: "test",
},
wantBaseAddr: "example.com:10001",
},
}

for _, testCase := range testCases {
mieru, err := NewMieru(testCase.option)
if err != nil {
t.Error(err)
}
if mieru.addr != testCase.wantBaseAddr {
t.Errorf("got addr %q, want %q", mieru.addr, testCase.wantBaseAddr)
}
}
}

func TestBeginAndEndPortFromPortRange(t *testing.T) {
testCases := []struct {
input string
begin int
end int
hasErr bool
}{
{"1-10", 1, 10, false},
{"1000-2000", 1000, 2000, false},
{"65535-65535", 65535, 65535, false},
{"1", 0, 0, true},
{"1-", 0, 0, true},
{"-10", 0, 0, true},
{"a-b", 0, 0, true},
{"1-b", 0, 0, true},
{"a-10", 0, 0, true},
}

for _, testCase := range testCases {
begin, end, err := beginAndEndPortFromPortRange(testCase.input)
if testCase.hasErr {
if err == nil {
t.Errorf("beginAndEndPortFromPortRange(%s) should return an error", testCase.input)
}
} else {
if err != nil {
t.Errorf("beginAndEndPortFromPortRange(%s) should not return an error, but got %v", testCase.input, err)
}
if begin != testCase.begin {
t.Errorf("beginAndEndPortFromPortRange(%s) begin port mismatch, got %d, want %d", testCase.input, begin, testCase.begin)
}
if end != testCase.end {
t.Errorf("beginAndEndPortFromPortRange(%s) end port mismatch, got %d, want %d", testCase.input, end, testCase.end)
}
}
}
}
7 changes: 7 additions & 0 deletions adapter/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,13 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
break
}
proxy, err = outbound.NewSsh(*sshOption)
case "mieru":
mieruOption := &outbound.MieruOption{}
err = decoder.Decode(mapping, mieruOption)
if err != nil {
break
}
proxy, err = outbound.NewMieru(*mieruOption)
default:
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
}
Expand Down
3 changes: 3 additions & 0 deletions constant/adapters.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ const (
WireGuard
Tuic
Ssh
Mieru
)

const (
Expand Down Expand Up @@ -213,6 +214,8 @@ func (at AdapterType) String() string {
return "WireGuard"
case Tuic:
return "Tuic"
case Mieru:
return "Mieru"

case Relay:
return "Relay"
Expand Down
13 changes: 12 additions & 1 deletion docs/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -846,6 +846,17 @@ proxies: # socks5
password: password
privateKey: path

# mieru
- name: mieru
type: mieru
server: 1.2.3.4
port: 2999
# port-range: 2090-2099 #(不可同时填写 port 和 port-range)
transport: TCP # Available: "TCP", "UDP".
username: user
password: password
# mtu: 1450 # Available: 1280 - 1500. Default: 1400.

# dns 出站会将请求劫持到内部 dns 模块,所有请求均在内部处理
- name: "dns-out"
type: dns
Expand Down Expand Up @@ -1200,4 +1211,4 @@ listeners:
# authentication-timeout: 1000
# alpn:
# - h3
# max-udp-relay-packet-size: 1500
# max-udp-relay-packet-size: 1500
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ require (
github.com/bahlo/generic-list-go v0.2.0
github.com/coreos/go-iptables v0.8.0
github.com/dlclark/regexp2 v1.11.4
github.com/enfein/mieru/v3 v3.6.0
github.com/go-chi/chi/v5 v5.1.0
github.com/go-chi/render v1.0.3
github.com/gobwas/ws v1.4.0
Expand Down Expand Up @@ -114,6 +115,8 @@ require (
golang.org/x/text v0.19.0 // indirect
golang.org/x/time v0.5.0 // indirect
golang.org/x/tools v0.24.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240610135401-a8a62080eff3 // indirect
google.golang.org/grpc v1.64.1 // indirect
)

replace github.com/sagernet/sing => github.com/metacubex/sing v0.0.0-20240724044459-6f3cf5896297
Loading