local.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. package client
  2. import (
  3. "net"
  4. "net/http"
  5. "sync"
  6. "time"
  7. "github.com/astaxie/beego/logs"
  8. "github.com/cnlh/nps/lib/common"
  9. "github.com/cnlh/nps/lib/config"
  10. "github.com/cnlh/nps/lib/conn"
  11. "github.com/cnlh/nps/lib/crypt"
  12. "github.com/cnlh/nps/lib/file"
  13. "github.com/cnlh/nps/lib/mux"
  14. "github.com/cnlh/nps/server/proxy"
  15. "github.com/xtaci/kcp-go"
  16. )
  17. var (
  18. LocalServer []*net.TCPListener
  19. udpConn net.Conn
  20. muxSession *mux.Mux
  21. fileServer []*http.Server
  22. p2pNetBridge *p2pBridge
  23. lock sync.RWMutex
  24. udpConnStatus bool
  25. )
  26. type p2pBridge struct {
  27. }
  28. func (p2pBridge *p2pBridge) SendLinkInfo(clientId int, link *conn.Link, t *file.Tunnel) (target net.Conn, err error) {
  29. nowConn, err := muxSession.NewConn()
  30. if err != nil {
  31. udpConn = nil
  32. return nil, err
  33. }
  34. if _, err := conn.NewConn(nowConn).SendInfo(link, ""); err != nil {
  35. udpConnStatus = false
  36. return nil, err
  37. }
  38. return nowConn, nil
  39. }
  40. func CloseLocalServer() {
  41. for _, v := range LocalServer {
  42. v.Close()
  43. }
  44. for _, v := range fileServer {
  45. v.Close()
  46. }
  47. }
  48. func startLocalFileServer(config *config.CommonConfig, t *file.Tunnel, vkey string) {
  49. remoteConn, err := NewConn(config.Tp, vkey, config.Server, common.WORK_FILE, config.ProxyUrl)
  50. if err != nil {
  51. logs.Error("Local connection server failed ", err.Error())
  52. return
  53. }
  54. srv := &http.Server{
  55. Handler: http.StripPrefix(t.StripPre, http.FileServer(http.Dir(t.LocalPath))),
  56. }
  57. logs.Info("start local file system, local path %s, strip prefix %s ,remote port %s ", t.LocalPath, t.StripPre, t.Ports)
  58. fileServer = append(fileServer, srv)
  59. listener := mux.NewMux(remoteConn.Conn, common.CONN_TCP)
  60. logs.Error(srv.Serve(listener))
  61. }
  62. func StartLocalServer(l *config.LocalServer, config *config.CommonConfig) error {
  63. if l.Type != "secret" {
  64. go handleUdpMonitor(config, l)
  65. }
  66. task := &file.Tunnel{
  67. Port: l.Port,
  68. ServerIp: "0.0.0.0",
  69. Status: true,
  70. Client: &file.Client{
  71. Cnf: &file.Config{
  72. U: "",
  73. P: "",
  74. Compress: config.Client.Cnf.Compress,
  75. },
  76. Status: true,
  77. RateLimit: 0,
  78. Flow: &file.Flow{},
  79. },
  80. Flow: &file.Flow{},
  81. Target: &file.Target{},
  82. }
  83. switch l.Type {
  84. case "p2ps":
  85. logs.Info("successful start-up of local socks5 monitoring, port", l.Port)
  86. return proxy.NewSock5ModeServer(p2pNetBridge, task).Start()
  87. case "p2pt":
  88. logs.Info("successful start-up of local tcp trans monitoring, port", l.Port)
  89. return proxy.NewTunnelModeServer(proxy.HandleTrans, p2pNetBridge, task).Start()
  90. case "p2p", "secret":
  91. listener, err := net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), l.Port, ""})
  92. if err != nil {
  93. logs.Error("local listener startup failed port %d, error %s", l.Port, err.Error())
  94. return err
  95. }
  96. LocalServer = append(LocalServer, listener)
  97. logs.Info("successful start-up of local tcp monitoring, port", l.Port)
  98. conn.Accept(listener, func(c net.Conn) {
  99. logs.Trace("new %s connection", l.Type)
  100. if l.Type == "secret" {
  101. handleSecret(c, config, l)
  102. } else if l.Type == "p2p" {
  103. handleP2PVisitor(c, config, l)
  104. }
  105. })
  106. }
  107. return nil
  108. }
  109. func handleUdpMonitor(config *config.CommonConfig, l *config.LocalServer) {
  110. ticker := time.NewTicker(time.Second * 1)
  111. defer ticker.Stop()
  112. for {
  113. select {
  114. case <-ticker.C:
  115. if !udpConnStatus {
  116. udpConn = nil
  117. tmpConn, err := common.GetLocalUdpAddr()
  118. if err != nil {
  119. logs.Error(err)
  120. return
  121. }
  122. for i := 0; i < 10; i++ {
  123. logs.Notice("try to connect to the server", i+1)
  124. newUdpConn(tmpConn.LocalAddr().String(), config, l)
  125. if udpConn != nil {
  126. udpConnStatus = true
  127. break
  128. }
  129. }
  130. }
  131. }
  132. }
  133. }
  134. func handleSecret(localTcpConn net.Conn, config *config.CommonConfig, l *config.LocalServer) {
  135. remoteConn, err := NewConn(config.Tp, config.VKey, config.Server, common.WORK_SECRET, config.ProxyUrl)
  136. if err != nil {
  137. logs.Error("Local connection server failed ", err.Error())
  138. return
  139. }
  140. if _, err := remoteConn.Write([]byte(crypt.Md5(l.Password))); err != nil {
  141. logs.Error("Local connection server failed ", err.Error())
  142. return
  143. }
  144. conn.CopyWaitGroup(remoteConn.Conn, localTcpConn, false, false, nil, nil, false, nil)
  145. }
  146. func handleP2PVisitor(localTcpConn net.Conn, config *config.CommonConfig, l *config.LocalServer) {
  147. if udpConn == nil {
  148. logs.Notice("new conn, P2P can not penetrate successfully, traffic will be transferred through the server")
  149. handleSecret(localTcpConn, config, l)
  150. }
  151. logs.Trace("start trying to connect with the server")
  152. //TODO just support compress now because there is not tls file in client packages
  153. link := conn.NewLink(common.CONN_TCP, l.Target, false, config.Client.Cnf.Compress, localTcpConn.LocalAddr().String(), false)
  154. if target, err := p2pNetBridge.SendLinkInfo(0, link, nil); err != nil {
  155. logs.Error(err)
  156. udpConnStatus = false
  157. return
  158. } else {
  159. conn.CopyWaitGroup(target, localTcpConn, false, config.Client.Cnf.Compress, nil, nil, false, nil)
  160. }
  161. }
  162. func newUdpConn(localAddr string, config *config.CommonConfig, l *config.LocalServer) {
  163. lock.Lock()
  164. defer lock.Unlock()
  165. remoteConn, err := NewConn(config.Tp, config.VKey, config.Server, common.WORK_P2P, config.ProxyUrl)
  166. if err != nil {
  167. logs.Error("Local connection server failed ", err.Error())
  168. return
  169. }
  170. if _, err := remoteConn.Write([]byte(crypt.Md5(l.Password))); err != nil {
  171. logs.Error("Local connection server failed ", err.Error())
  172. return
  173. }
  174. var rAddr []byte
  175. //读取服务端地址、密钥 继续做处理
  176. if rAddr, err = remoteConn.GetShortLenContent(); err != nil {
  177. logs.Error(err)
  178. return
  179. }
  180. var localConn net.PacketConn
  181. var remoteAddress string
  182. if remoteAddress, localConn, err = handleP2PUdp(localAddr, string(rAddr), crypt.Md5(l.Password), common.WORK_P2P_VISITOR); err != nil {
  183. logs.Error(err)
  184. return
  185. }
  186. udpTunnel, err := kcp.NewConn(remoteAddress, nil, 150, 3, localConn)
  187. if err != nil || udpTunnel == nil {
  188. logs.Warn(err)
  189. return
  190. }
  191. logs.Trace("successful create a connection with server", remoteAddress)
  192. conn.SetUdpSession(udpTunnel)
  193. udpConn = udpTunnel
  194. muxSession = mux.NewMux(udpConn, "kcp")
  195. p2pNetBridge = &p2pBridge{}
  196. }