forked from rchunping/TcpRoute2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
128 lines (106 loc) · 2.57 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
package main
import (
"time"
"net"
"io"
"log"
"github.com/gamexg/TcpRoute2/nettool"
)
//
const (
// 尝试创建处理器时的conn.read 的timeout
// 实际是一次性读取数据,所以这个超时指的是客户端必须10秒内发出第一和数据
handlerNewTimeout = 10 * time.Second
// 默认一个连接的总处理时间,一般都会被实际的处理器修改掉。
handlerBaseTimeout = 10 * time.Minute
)
type SetLingerer interface {
SetLinger(sec int) error
}
type Server struct {
Addr string // TCP 监听地址
hNewer HandlerNewer // 请求处理器
upStream UpStreamDial // 上层代理
ln net.Listener
errConn *ErrConnService //错误连接统计
}
func NewServer(addr string, upStream UpStreamDial) *Server {
srv := Server{}
srv.Addr = addr
// 错误连接记录
srv.errConn = NewErrConnService()
if upStream == nil {
// 基本上层代理
localUpStream, err := NewBaseUpStream(&srv)
if err != nil {
panic(err)
}
upStream = localUpStream
}
srv.upStream = upStream
// 处理器
h := NewSwitchHandlerNewer()
hs := NewSocksHandlerNewer(srv.upStream)
h.AppendHandlerNewer(hs)
srv.hNewer = h
return &srv
}
func (srv *Server) ListAndServe() error {
if srv.Addr == "" {
srv.Addr = ":7070"
}
ln, err := net.Listen("tcp", srv.Addr)
if err != nil {
return err
}
srv.ln = ln
return srv.Server()
}
func (srv *Server) Server() error {
ln := srv.ln
defer ln.Close()
var tempDelay time.Duration
for {
rw, e := ln.Accept()
if e != nil {
if ne, ok := e.(net.Error); ok && ne.Temporary() {
if tempDelay == 0 {
tempDelay = 5 * time.Millisecond
} else {
tempDelay *= 2
}
if max := 1 * time.Second; tempDelay > max {
tempDelay = max
}
log.Printf("Accept error: %v; retrying in %v", e, tempDelay)
time.Sleep(tempDelay)
continue
}
return e
}
tempDelay = 0
go srv.handlerConn(rw)
}
}
func (srv *Server) handlerConn(conn net.Conn) {
defer func() {
if err := recover(); err != nil {
log.Printf("work failed:%v", err)
}
}()
// 是这里调用关闭还是 Handler() 负责?
defer conn.Close()
nettool.SetLinger(conn,5)
conn.SetDeadline(time.Now().Add(handlerNewTimeout))
h, _, err := srv.hNewer.New(conn)
if h == nil {
log.Printf("无法识别请求的协议类型,远端地址:%v,近端地址:%v,详细错误:%v", conn.RemoteAddr(), conn.LocalAddr(), err)
return
}
conn.SetDeadline(time.Now().Add(handlerBaseTimeout))
if err := h.Handle(); err != nil {
if err != io.EOF {
log.Printf("协议处理错误:%v", err)
}
}
}