forked from ShangjinTang/clash-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
listener.go
90 lines (77 loc) · 1.88 KB
/
listener.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package constant
import (
"fmt"
"net"
"net/url"
"strconv"
)
type Listener interface {
RawAddress() string
Address() string
Close() error
}
type InboundType string
const (
InboundTypeSocks InboundType = "socks"
InboundTypeRedir InboundType = "redir"
InboundTypeTproxy InboundType = "tproxy"
InboundTypeHTTP InboundType = "http"
InboundTypeMixed InboundType = "mixed"
)
var supportInboundTypes = map[InboundType]bool{
InboundTypeSocks: true,
InboundTypeRedir: true,
InboundTypeTproxy: true,
InboundTypeHTTP: true,
InboundTypeMixed: true,
}
type inbound struct {
Type InboundType `json:"type" yaml:"type"`
BindAddress string `json:"bind-address" yaml:"bind-address"`
IsFromPortCfg bool `json:"-" yaml:"-"`
}
// Inbound
type Inbound inbound
// UnmarshalYAML implements yaml.Unmarshaler
func (i *Inbound) UnmarshalYAML(unmarshal func(any) error) error {
var tp string
if err := unmarshal(&tp); err != nil {
var inner inbound
if err := unmarshal(&inner); err != nil {
return err
}
*i = Inbound(inner)
} else {
inner, err := parseInbound(tp)
if err != nil {
return err
}
*i = Inbound(*inner)
}
if !supportInboundTypes[i.Type] {
return fmt.Errorf("not support inbound type: %s", i.Type)
}
_, portStr, err := net.SplitHostPort(i.BindAddress)
if err != nil {
return fmt.Errorf("bind address parse error. addr: %s, err: %w", i.BindAddress, err)
}
port, err := strconv.ParseUint(portStr, 10, 16)
if err != nil || port == 0 {
return fmt.Errorf("invalid bind port. addr: %s", i.BindAddress)
}
return nil
}
func parseInbound(alias string) (*inbound, error) {
u, err := url.Parse(alias)
if err != nil {
return nil, err
}
listenerType := InboundType(u.Scheme)
return &inbound{
Type: listenerType,
BindAddress: u.Host,
}, nil
}
func (i *Inbound) ToAlias() string {
return string(i.Type) + "://" + i.BindAddress
}