github.com/geph-official/geph2@v0.22.6-0.20210211030601-f527cb59b0df/libs/niaucchi4/listener.go (about) 1 package niaucchi4 2 3 import ( 4 "log" 5 "net" 6 7 "github.com/geph-official/geph2/libs/fastudp" 8 "github.com/geph-official/geph2/libs/kcp-go" 9 ) 10 11 // DialKCP dials KCP over obfs in one function. 12 func DialKCP(addr string, cookie []byte) (conn net.Conn, err error) { 13 socket := Wrap(func() net.PacketConn { 14 udpsock, err := net.ListenPacket("udp", "") 15 if err != nil { 16 panic(err) 17 } 18 if doLogging { 19 log.Println("N4: recreating source socket", udpsock.LocalAddr()) 20 } 21 // udpsock.(*net.UDPConn).SetReadBuffer(10 * 1024 * 1024) 22 // udpsock.(*net.UDPConn).SetWriteBuffer(10 * 1024 * 1024) 23 return fastudp.NewConn(udpsock.(*net.UDPConn)) 24 }) 25 kcpConn, err := kcp.NewConn(addr, nil, 16, 16, ObfsListen(cookie, socket, false)) 26 if err != nil { 27 socket.Close() 28 return 29 } 30 kcpConn.SetWindowSize(10000, 10000) 31 kcpConn.SetNoDelay(0, 100, 32, 0) 32 kcpConn.SetStreamMode(true) 33 kcpConn.SetMtu(1300) 34 conn = kcpConn 35 return 36 } 37 38 // KCPListener operates KCP over obfs. Standard caveats about KCP not having proper open and close signaling apply. 39 type KCPListener struct { 40 k *kcp.Listener 41 conn net.PacketConn 42 } 43 44 // ListenKCP creates a new listener. 45 func ListenKCP(sock net.PacketConn) *KCPListener { 46 listener, err := kcp.ServeConn(nil, 16, 16, sock) 47 if err != nil { 48 panic(err) 49 } 50 return &KCPListener{ 51 k: listener, 52 conn: sock, 53 } 54 } 55 56 // Accept accepts a new connection. 57 func (l *KCPListener) Accept() (c *kcp.UDPSession, err error) { 58 kc, err := l.k.AcceptKCP() 59 if err != nil { 60 return 61 } 62 kc.SetWindowSize(10000, 10000) 63 kc.SetNoDelay(0, 100, 32, 0) 64 kc.SetMtu(1300) 65 c = kc 66 return 67 } 68 69 // Close closes the thing. 70 func (l *KCPListener) Close() error { 71 l.conn.Close() 72 return l.k.Close() 73 }