/
smux.go
104 lines (95 loc) · 2.5 KB
/
smux.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
package tcp
import (
"fmt"
"log"
"net"
"sync"
"time"
"github.com/xtaci/smux"
)
var (
allcon = make(map[string]*smux.Session)
GlobalSessions = make(chan *smux.Session, 512)
GlobalAverageRunning = false
locker = sync.RWMutex{}
)
type scavengeSession struct {
session *smux.Session
ts time.Time
}
func Average(ch chan *smux.Session, ttl int) net.Conn {
tick := time.NewTicker(1 * time.Second)
defer tick.Stop()
var sessionList []scavengeSession
for {
select {
case sess := <-ch:
sessionList = append(sessionList, scavengeSession{sess, time.Now()})
log.Println("session marked as expired", sess.RemoteAddr())
case <-tick.C:
var newList []scavengeSession
for k := range sessionList {
s := sessionList[k]
if s.session.NumStreams() == 0 || s.session.IsClosed() {
log.Println("session normally closed", s.session.RemoteAddr())
s.session.Close()
} else if ttl >= 0 && time.Since(s.ts) >= time.Duration(ttl)*time.Second {
log.Println("session reached scavenge ttl", s.session.RemoteAddr())
s.session.Close()
} else {
newList = append(newList, sessionList[k])
}
}
sessionList = newList
}
}
}
func UpdateSession(proxy string, con *smux.Session) {
locker.Lock()
defer locker.Unlock()
allcon[proxy] = con
}
func createSession(protocol, proxy string) (*smux.Session, error) {
for {
con, _, err := ExpressDial(proxy, protocol, false)
if err != nil {
log.Println(fmt.Sprintf(protocol+" connect error \"%s\" , wait 1s to reconnect!!!", proxy))
time.Sleep(1 * time.Second)
continue
}
for i := 0; i < 3; i++ {
session, err := smux.Client(con, nil)
if err != nil {
log.Println(fmt.Sprintf("smux session connect error \"%s\" , wait 1s to reconnect!!!", proxy))
time.Sleep(1 * time.Second)
} else {
return session, nil
}
}
con.Close()
}
}
func WithASession(protocol, proxy string) (*smux.Session, error) {
if !GlobalAverageRunning {
go Average(GlobalSessions, 600)
GlobalAverageRunning = true
}
if sess, ok := allcon[proxy]; ok {
if !sess.IsClosed() {
return sess, nil
} else {
sess, err := createSession(protocol, proxy)
GlobalSessions <- sess
if err != nil {
return nil, err
}
UpdateSession(proxy, sess)
return sess, nil
}
} else {
sess, _ := createSession(protocol, proxy)
GlobalSessions <- sess
UpdateSession(proxy, sess)
return sess, nil
}
}