Example #1
0
func handleConnection(user user.User, conn *ss.Conn, auth bool) {
	var host string

	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.Debug("Number of client connections reaches %d\n", nextLogConnCnt)
		nextLogConnCnt += logCntDelta
	}

	// function arguments are always evaluated, so surround debug statement
	// with if statement
	Log.Debug(fmt.Sprintf("new client %s->%s\n", conn.RemoteAddr().String(), conn.LocalAddr()))
	closed := false
	defer func() {
		if ssdebug {
			Log.Debug(fmt.Sprintf("closed pipe %s<->%s\n", conn.RemoteAddr(), host))
		}
		connCnt--
		if !closed {
			conn.Close()
		}
	}()

	host, res_size, ota, err := getRequest(conn, auth)
	if err != nil {
		Log.Error("error getting request", conn.RemoteAddr(), conn.LocalAddr(), err)
		return
	}
	Log.Info(fmt.Sprintf("[port-%d]connecting %s ", user.GetPort(), host))
	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.Error("dial error:", err)
		} else {
			Log.Error("error connecting to:", host, err)
		}
		return
	}
	defer func() {
		if !closed {
			remote.Close()
		}
	}()

	// debug conn info
	Log.Debug(fmt.Sprintf("%d conn debug:  local addr: %s | remote addr: %s network: %s ", user.GetPort(),
		conn.LocalAddr().String(), conn.RemoteAddr().String(), conn.RemoteAddr().Network()))
	err = storage.IncrSize(user, res_size)
	if err != nil {
		Log.Error(err)
		return
	}
	err = storage.MarkUserOnline(user)
	if err != nil {
		Log.Error(err)
		return
	}
	Log.Debug(fmt.Sprintf("[port-%d] store size: %d", user.GetPort(), res_size))

	Log.Info(fmt.Sprintf("piping %s<->%s ota=%v connOta=%v", conn.RemoteAddr(), host, ota, conn.IsOta()))

	if ota {
		go PipeThenCloseOta(conn, remote, false, host, user)
	} else {
		go PipeThenClose(conn, remote, false, host, user)
	}

	PipeThenClose(remote, conn, true, host, user)
	closed = true
	return
}