func handleConnection(conn *ss.Conn) { var ( host string remote net.Conn ) connCnt++ // this maybe not accurate, but should be enough if connCnt-nextLogConnCnt >= 0 { // XXX There's no xadd in the atomic package, so it's difficult to log // the message only once with low cost. Also note nextLogConnCnt maybe // added twice for current peak connection number level. log.Printf("Number of client connections reaches %d\n", nextLogConnCnt) nextLogConnCnt += logCntDelta } // function arguments are always evaluated, so surround debug statement // with if statement if debug { debug.Printf("new client %s->%s\n", conn.RemoteAddr().String(), conn.LocalAddr()) } closed := false defer func() { if debug { debug.Printf("closed pipe %s<->%s\n", conn.RemoteAddr(), host) } connCnt-- if !closed { conn.Close() } }() host, extra, err := getRequest(conn) if err != nil { log.Println("error getting request", conn.RemoteAddr(), conn.LocalAddr(), err) return } debug.Println("connecting", host) if (config.TcpFastOpen & 1) != 0 { // dial with data remote, err = ss.TfoDial("tcp", host, extra) extra = nil } else { remote, err = net.Dial("tcp", host) } if err != nil { if ne, ok := err.(*net.OpError); ok && (ne.Err == syscall.EMFILE || ne.Err == syscall.ENFILE) { // log too many open file error // EMFILE is process reaches open file limits, ENFILE is system limit log.Println("dial error:", err) } else { log.Println("error connecting to:", host, err) } return } defer func() { if !closed { remote.Close() } }() // write extra bytes read from if extra != nil { debug.Println("getRequest read extra data, writing to remote, len", len(extra)) if _, err = remote.Write(extra); err != nil { debug.Println("write request extra error:", err) return } } if debug { debug.Printf("piping %s<->%s", conn.RemoteAddr(), host) } go ss.PipeThenClose(conn, remote) ss.PipeThenClose(remote, conn) closed = true return }