bridge.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. package bridge
  2. import (
  3. "errors"
  4. "github.com/cnlh/nps/lib/conn"
  5. "github.com/cnlh/nps/lib/file"
  6. "github.com/cnlh/nps/lib/kcp"
  7. "github.com/cnlh/nps/lib/lg"
  8. "github.com/cnlh/nps/lib/pool"
  9. "github.com/cnlh/nps/lib/common"
  10. "net"
  11. "strconv"
  12. "sync"
  13. "time"
  14. )
  15. type Client struct {
  16. tunnel *conn.Conn
  17. signal *conn.Conn
  18. linkMap map[int]*conn.Link
  19. linkStatusMap map[int]bool
  20. stop chan bool
  21. sync.RWMutex
  22. }
  23. func NewClient(t *conn.Conn, s *conn.Conn) *Client {
  24. return &Client{
  25. linkMap: make(map[int]*conn.Link),
  26. stop: make(chan bool),
  27. linkStatusMap: make(map[int]bool),
  28. signal: s,
  29. tunnel: t,
  30. }
  31. }
  32. type Bridge struct {
  33. TunnelPort int //通信隧道端口
  34. tcpListener *net.TCPListener //server端监听
  35. kcpListener *kcp.Listener //server端监听
  36. Client map[int]*Client
  37. RunList map[int]interface{} //运行中的任务
  38. tunnelType string //bridge type kcp or tcp
  39. lock sync.Mutex
  40. tunnelLock sync.Mutex
  41. clientLock sync.RWMutex
  42. }
  43. func NewTunnel(tunnelPort int, runList map[int]interface{}, tunnelType string) *Bridge {
  44. t := new(Bridge)
  45. t.TunnelPort = tunnelPort
  46. t.Client = make(map[int]*Client)
  47. t.RunList = runList
  48. t.tunnelType = tunnelType
  49. return t
  50. }
  51. func (s *Bridge) StartTunnel() error {
  52. var err error
  53. if s.tunnelType == "kcp" {
  54. s.kcpListener, err = kcp.ListenWithOptions(":"+strconv.Itoa(s.TunnelPort), nil, 150, 3)
  55. if err != nil {
  56. return err
  57. }
  58. go func() {
  59. for {
  60. c, err := s.kcpListener.AcceptKCP()
  61. conn.SetUdpSession(c)
  62. if err != nil {
  63. lg.Println(err)
  64. continue
  65. }
  66. go s.cliProcess(conn.NewConn(c))
  67. }
  68. }()
  69. } else {
  70. s.tcpListener, err = net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), s.TunnelPort, ""})
  71. if err != nil {
  72. return err
  73. }
  74. go func() {
  75. for {
  76. c, err := s.tcpListener.Accept()
  77. if err != nil {
  78. lg.Println(err)
  79. continue
  80. }
  81. go s.cliProcess(conn.NewConn(c))
  82. }
  83. }()
  84. }
  85. return nil
  86. }
  87. //验证失败,返回错误验证flag,并且关闭连接
  88. func (s *Bridge) verifyError(c *conn.Conn) {
  89. c.Write([]byte(common.VERIFY_EER))
  90. c.Conn.Close()
  91. }
  92. func (s *Bridge) cliProcess(c *conn.Conn) {
  93. c.SetReadDeadline(5, s.tunnelType)
  94. var buf []byte
  95. var err error
  96. if buf, err = c.ReadLen(32); err != nil {
  97. c.Close()
  98. return
  99. }
  100. //验证
  101. id, err := file.GetCsvDb().GetIdByVerifyKey(string(buf), c.Conn.RemoteAddr().String())
  102. if err != nil {
  103. lg.Println("当前客户端连接校验错误,关闭此客户端:", c.Conn.RemoteAddr())
  104. s.verifyError(c)
  105. return
  106. }
  107. //做一个判断 添加到对应的channel里面以供使用
  108. if flag, err := c.ReadFlag(); err == nil {
  109. s.typeDeal(flag, c, id)
  110. }
  111. return
  112. }
  113. func (s *Bridge) closeClient(id int) {
  114. s.clientLock.Lock()
  115. defer s.clientLock.Unlock()
  116. if v, ok := s.Client[id]; ok {
  117. v.signal.WriteClose()
  118. delete(s.Client, id)
  119. }
  120. }
  121. //tcp连接类型区分
  122. func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int) {
  123. switch typeVal {
  124. case common.WORK_MAIN:
  125. //客户端已经存在,下线
  126. s.clientLock.Lock()
  127. if v, ok := s.Client[id]; ok {
  128. s.clientLock.Unlock()
  129. if v.signal != nil {
  130. v.signal.WriteClose()
  131. }
  132. v.Lock()
  133. v.signal = c
  134. v.Unlock()
  135. } else {
  136. s.Client[id] = NewClient(nil, c)
  137. s.clientLock.Unlock()
  138. }
  139. lg.Printf("客户端%d连接成功,地址为:%s", id, c.Conn.RemoteAddr())
  140. go s.GetStatus(id)
  141. case common.WORK_CHAN:
  142. s.clientLock.Lock()
  143. if v, ok := s.Client[id]; ok {
  144. s.clientLock.Unlock()
  145. v.Lock()
  146. v.tunnel = c
  147. v.Unlock()
  148. } else {
  149. s.Client[id] = NewClient(c, nil)
  150. s.clientLock.Unlock()
  151. }
  152. go s.clientCopy(id)
  153. }
  154. c.SetAlive(s.tunnelType)
  155. return
  156. }
  157. //等待
  158. func (s *Bridge) waitStatus(clientId, id int) (bool) {
  159. ticker := time.NewTicker(time.Millisecond * 100)
  160. stop := time.After(time.Second * 10)
  161. for {
  162. select {
  163. case <-ticker.C:
  164. s.clientLock.Lock()
  165. if v, ok := s.Client[clientId]; ok {
  166. s.clientLock.Unlock()
  167. v.Lock()
  168. if vv, ok := v.linkStatusMap[id]; ok {
  169. ticker.Stop()
  170. v.Unlock()
  171. return vv
  172. }
  173. v.Unlock()
  174. } else {
  175. s.clientLock.Unlock()
  176. }
  177. case <-stop:
  178. return false
  179. }
  180. }
  181. return false
  182. }
  183. func (s *Bridge) SendLinkInfo(clientId int, link *conn.Link) (tunnel *conn.Conn, err error) {
  184. s.clientLock.Lock()
  185. if v, ok := s.Client[clientId]; ok {
  186. s.clientLock.Unlock()
  187. v.signal.SendLinkInfo(link)
  188. if err != nil {
  189. lg.Println("send error:", err, link.Id)
  190. s.DelClient(clientId)
  191. return
  192. }
  193. if v.tunnel == nil {
  194. err = errors.New("tunnel获取错误")
  195. return
  196. } else {
  197. tunnel = v.tunnel
  198. }
  199. v.Lock()
  200. v.linkMap[link.Id] = link
  201. v.Unlock()
  202. if !s.waitStatus(clientId, link.Id) {
  203. err = errors.New("连接失败")
  204. return
  205. }
  206. } else {
  207. s.clientLock.Unlock()
  208. err = errors.New("客户端未连接")
  209. }
  210. return
  211. }
  212. //得到一个tcp隧道
  213. func (s *Bridge) GetTunnel(id int, en, de int, crypt, mux bool) (conn *conn.Conn, err error) {
  214. s.clientLock.Lock()
  215. defer s.clientLock.Unlock()
  216. if v, ok := s.Client[id]; !ok {
  217. err = errors.New("客户端未连接")
  218. } else {
  219. conn = v.tunnel
  220. }
  221. return
  222. }
  223. //得到一个通信通道
  224. func (s *Bridge) GetSignal(id int) (conn *conn.Conn, err error) {
  225. s.clientLock.Lock()
  226. defer s.clientLock.Unlock()
  227. if v, ok := s.Client[id]; !ok {
  228. err = errors.New("客户端未连接")
  229. } else {
  230. conn = v.signal
  231. }
  232. return
  233. }
  234. //删除通信通道
  235. func (s *Bridge) DelClient(id int) {
  236. s.closeClient(id)
  237. }
  238. func (s *Bridge) verify(id int) bool {
  239. for k := range s.RunList {
  240. if k == id {
  241. return true
  242. }
  243. }
  244. return false
  245. }
  246. func (s *Bridge) GetStatus(clientId int) {
  247. s.clientLock.Lock()
  248. client := s.Client[clientId]
  249. s.clientLock.Unlock()
  250. if client == nil {
  251. return
  252. }
  253. for {
  254. if id, status, err := client.signal.GetConnStatus(); err != nil {
  255. s.closeClient(clientId)
  256. return
  257. } else {
  258. client.Lock()
  259. client.linkStatusMap[id] = status
  260. client.Unlock()
  261. }
  262. }
  263. }
  264. func (s *Bridge) clientCopy(clientId int) {
  265. s.clientLock.Lock()
  266. client := s.Client[clientId]
  267. s.clientLock.Unlock()
  268. for {
  269. if id, err := client.tunnel.GetLen(); err != nil {
  270. s.closeClient(clientId)
  271. lg.Println("读取msg id 错误", err, id)
  272. break
  273. } else {
  274. client.Lock()
  275. if link, ok := client.linkMap[id]; ok {
  276. client.Unlock()
  277. if content, err := client.tunnel.GetMsgContent(link); err != nil {
  278. pool.PutBufPoolCopy(content)
  279. s.closeClient(clientId)
  280. lg.Println("read msg content error", err, "close client")
  281. break
  282. } else {
  283. if len(content) == len(common.IO_EOF) && string(content) == common.IO_EOF {
  284. if link.Conn != nil {
  285. link.Conn.Close()
  286. }
  287. } else {
  288. if link.UdpListener != nil && link.UdpRemoteAddr != nil {
  289. link.UdpListener.WriteToUDP(content, link.UdpRemoteAddr)
  290. } else {
  291. link.Conn.Write(content)
  292. }
  293. link.Flow.Add(0, len(content))
  294. }
  295. pool.PutBufPoolCopy(content)
  296. }
  297. } else {
  298. client.Unlock()
  299. continue
  300. }
  301. }
  302. }
  303. }