forked from v2ray/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
228 lines (187 loc) · 6.17 KB
/
server.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
// R.I.P Shadowsocks
package shadowsocks
import (
"sync"
"errors"
"v2ray.com/core/app"
"v2ray.com/core/app/dispatcher"
"v2ray.com/core/common"
"v2ray.com/core/common/alloc"
v2io "v2ray.com/core/common/io"
"v2ray.com/core/common/log"
v2net "v2ray.com/core/common/net"
"v2ray.com/core/common/protocol"
"v2ray.com/core/proxy"
"v2ray.com/core/transport/internet"
"v2ray.com/core/transport/internet/udp"
)
type Server struct {
packetDispatcher dispatcher.PacketDispatcher
config *ServerConfig
user *protocol.User
account *ShadowsocksAccount
meta *proxy.InboundHandlerMeta
accepting bool
tcpHub *internet.TCPHub
udpHub *udp.UDPHub
udpServer *udp.UDPServer
}
func NewServer(config *ServerConfig, space app.Space, meta *proxy.InboundHandlerMeta) (*Server, error) {
if config.GetUser() == nil {
return nil, protocol.ErrUserMissing
}
rawAccount, err := config.User.GetTypedAccount()
if err != nil {
return nil, errors.New("Shadowsocks|Server: Failed to get user account: " + err.Error())
}
account := rawAccount.(*ShadowsocksAccount)
s := &Server{
config: config,
meta: meta,
user: config.GetUser(),
account: account,
}
space.InitializeApplication(func() error {
if !space.HasApp(dispatcher.APP_ID) {
return errors.New("Shadowsocks|Server: Dispatcher is not found in space.")
}
s.packetDispatcher = space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher)
return nil
})
return s, nil
}
func (v *Server) Port() v2net.Port {
return v.meta.Port
}
func (v *Server) Close() {
v.accepting = false
// TODO: synchronization
if v.tcpHub != nil {
v.tcpHub.Close()
v.tcpHub = nil
}
if v.udpHub != nil {
v.udpHub.Close()
v.udpHub = nil
}
}
func (v *Server) Start() error {
if v.accepting {
return nil
}
tcpHub, err := internet.ListenTCP(v.meta.Address, v.meta.Port, v.handleConnection, v.meta.StreamSettings)
if err != nil {
log.Error("Shadowsocks: Failed to listen TCP on ", v.meta.Address, ":", v.meta.Port, ": ", err)
return err
}
v.tcpHub = tcpHub
if v.config.UdpEnabled {
v.udpServer = udp.NewUDPServer(v.packetDispatcher)
udpHub, err := udp.ListenUDP(v.meta.Address, v.meta.Port, udp.ListenOption{Callback: v.handlerUDPPayload})
if err != nil {
log.Error("Shadowsocks: Failed to listen UDP on ", v.meta.Address, ":", v.meta.Port, ": ", err)
return err
}
v.udpHub = udpHub
}
v.accepting = true
return nil
}
func (v *Server) handlerUDPPayload(payload *alloc.Buffer, session *proxy.SessionInfo) {
source := session.Source
request, data, err := DecodeUDPPacket(v.user, payload)
if err != nil {
log.Info("Shadowsocks|Server: Skipping invalid UDP packet from: ", source, ": ", err)
log.Access(source, "", log.AccessRejected, err)
payload.Release()
return
}
if request.Option.Has(RequestOptionOneTimeAuth) && v.account.OneTimeAuth == Account_Disabled {
log.Info("Shadowsocks|Server: Client payload enables OTA but server doesn't allow it.")
payload.Release()
return
}
if !request.Option.Has(RequestOptionOneTimeAuth) && v.account.OneTimeAuth == Account_Enabled {
log.Info("Shadowsocks|Server: Client payload disables OTA but server forces it.")
payload.Release()
return
}
dest := request.Destination()
log.Access(source, dest, log.AccessAccepted, "")
log.Info("Shadowsocks|Server: Tunnelling request to ", dest)
v.udpServer.Dispatch(&proxy.SessionInfo{Source: source, Destination: dest, User: request.User, Inbound: v.meta}, data, func(destination v2net.Destination, payload *alloc.Buffer) {
defer payload.Release()
data, err := EncodeUDPPacket(request, payload)
if err != nil {
log.Warning("Shadowsocks|Server: Failed to encode UDP packet: ", err)
return
}
defer data.Release()
v.udpHub.WriteTo(data.Value, source)
})
}
func (v *Server) handleConnection(conn internet.Connection) {
defer conn.Close()
conn.SetReusable(false)
timedReader := v2net.NewTimeOutReader(16, conn)
defer timedReader.Release()
bufferedReader := v2io.NewBufferedReader(timedReader)
defer bufferedReader.Release()
request, bodyReader, err := ReadTCPSession(v.user, bufferedReader)
if err != nil {
log.Access(conn.RemoteAddr(), "", log.AccessRejected, err)
log.Info("Shadowsocks|Server: Failed to create request from: ", conn.RemoteAddr(), ": ", err)
return
}
defer bodyReader.Release()
bufferedReader.SetCached(false)
userSettings := v.user.GetSettings()
timedReader.SetTimeOut(userSettings.PayloadReadTimeout)
dest := request.Destination()
log.Access(conn.RemoteAddr(), dest, log.AccessAccepted, "")
log.Info("Shadowsocks|Server: Tunnelling request to ", dest)
ray := v.packetDispatcher.DispatchToOutbound(&proxy.SessionInfo{
Source: v2net.DestinationFromAddr(conn.RemoteAddr()),
Destination: dest,
User: request.User,
Inbound: v.meta,
})
defer ray.InboundOutput().Release()
var writeFinish sync.Mutex
writeFinish.Lock()
go func() {
defer writeFinish.Unlock()
bufferedWriter := v2io.NewBufferedWriter(conn)
defer bufferedWriter.Release()
responseWriter, err := WriteTCPResponse(request, bufferedWriter)
if err != nil {
log.Warning("Shadowsocks|Server: Failed to write response: ", err)
return
}
defer responseWriter.Release()
if payload, err := ray.InboundOutput().Read(); err == nil {
responseWriter.Write(payload)
bufferedWriter.SetCached(false)
if err := v2io.PipeUntilEOF(ray.InboundOutput(), responseWriter); err != nil {
log.Info("Shadowsocks|Server: Failed to transport all TCP response: ", err)
}
}
}()
if err := v2io.PipeUntilEOF(bodyReader, ray.InboundInput()); err != nil {
log.Info("Shadowsocks|Server: Failed to transport all TCP request: ", err)
}
ray.InboundInput().Close()
writeFinish.Lock()
}
type ServerFactory struct{}
func (v *ServerFactory) StreamCapability() v2net.NetworkList {
return v2net.NetworkList{
Network: []v2net.Network{v2net.Network_TCP, v2net.Network_RawTCP},
}
}
func (v *ServerFactory) Create(space app.Space, rawConfig interface{}, meta *proxy.InboundHandlerMeta) (proxy.InboundHandler, error) {
if !space.HasApp(dispatcher.APP_ID) {
return nil, common.ErrBadConfiguration
}
return NewServer(rawConfig.(*ServerConfig), space, meta)
}