Example #1
0
func handleConnection(conn *ss.Conn) {
	var host string

	atomic.AddInt32(&connCnt, 1)
	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())
	}
	defer func() {
		if debug {
			debug.Printf("closing pipe %s<->%s\n", conn.RemoteAddr(), host)
		}
		atomic.AddInt32(&connCnt, -1)
		conn.Close()
	}()

	host, extra, err := getRequest(conn)
	if err != nil {
		log.Println("error getting request:", err)
		return
	}
	debug.Println("connecting", 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.Println("dial error:", err)
		} else {
			debug.Println("error connecting to:", host, err)
		}
		return
	}
	defer 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)
	}
	c := make(chan byte, 2)
	go ss.Pipe(conn, remote, c)
	go ss.Pipe(remote, conn, c)
	<-c // close the other connection whenever one connection is closed
	return
}
Example #2
0
File: ss.go Project: guest6379/gost
// copyOta copies data from src to dst with ota verification.
//
// This function is copied from shadowsocks library with some modification.
func (s *ShadowServer) copyOta(dst net.Conn, src *ss.Conn) (int64, error) {
	// sometimes it have to fill large block
	buf := make([]byte, LargeBufferSize)
	for {
		src.SetReadDeadline(time.Now().Add(ReadTimeout))
		if n, err := io.ReadFull(src, buf[:dataLenLen+hmacSha1Len]); err != nil {
			return int64(n), err
		}
		src.SetReadDeadline(time.Time{})

		dataLen := binary.BigEndian.Uint16(buf[:dataLenLen])
		expectedHmacSha1 := buf[dataLenLen:idxData0]

		var dataBuf []byte
		if len(buf) < int(idxData0+dataLen) {
			dataBuf = make([]byte, dataLen)
		} else {
			dataBuf = buf[idxData0 : idxData0+dataLen]
		}
		if n, err := io.ReadFull(src, dataBuf); err != nil {
			return int64(n), err
		}
		chunkIdBytes := make([]byte, 4)
		chunkId := src.GetAndIncrChunkId()
		binary.BigEndian.PutUint32(chunkIdBytes, chunkId)
		actualHmacSha1 := ss.HmacSha1(append(src.GetIv(), chunkIdBytes...), dataBuf)
		if !bytes.Equal(expectedHmacSha1, actualHmacSha1) {
			return 0, errors.New("ota error: mismatch")
		}

		if n, err := dst.Write(dataBuf); err != nil {
			return int64(n), err
		}
	}
}
Example #3
0
func handleConnection(conn *ss.Conn) {
	if debug {
		// function arguments are always evaluated, so surround debug
		// statement with if statement
		debug.Printf("socks connect from %s\n", conn.RemoteAddr().String())
	}
	defer conn.Close()

	host, extra, err := getRequest(conn)
	if err != nil {
		log.Println("error getting request:", err)
		return
	}
	debug.Println("connecting", 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.Println("dial error:", err)
		} else {
			debug.Println("error connecting to:", host, err)
		}
		return
	}
	defer 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
		}
	}
	debug.Println("piping", host)
	c := make(chan byte, 2)
	go ss.Pipe(conn, remote, c)
	go ss.Pipe(remote, conn, c)
	<-c // close the other connection whenever one connection is closed
	debug.Println("closing", host)
	return
}
Example #4
0
func handleConnection(user User, conn *ss.Conn) {
	var host string
	var size = 0
	var raw_req_header, raw_res_header []byte
	var is_http = false
	var res_size = 0
	var req_chan = make(chan []byte)

	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)
	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 is_http {
			tmp_req_header := <-req_chan
			buffer := bytes.NewBuffer(raw_req_header)
			buffer.Write(tmp_req_header)
			raw_req_header = buffer.Bytes()
		}
		showConn(raw_req_header, raw_res_header, host, user, size, is_http)
		close(req_chan)
		if !closed {
			remote.Close()
		}
	}()
	// write extra bytes read from

	is_http, extra, _ = checkHttp(extra, conn)
	if strings.HasSuffix(host, ":80") {
		is_http = true
	}
	raw_req_header = extra
	res_size, err = remote.Write(extra)
	storage.IncrSize("flow:"+user.Name, res_size)
	storage.ZincrbySize("flow:"+user.Name, host, res_size)
	size += res_size
	if err != nil {
		debug.Println("write request extra error:", err)
		return
	}

	if debug {
		debug.Printf("piping %s<->%s", conn.RemoteAddr(), host)
	}

	go func() {
		_, raw_header := PipeThenClose(conn, remote, is_http, false, host, user)
		if is_http {
			req_chan <- raw_header
		}
	}()

	res_size, raw_res_header = PipeThenClose(remote, conn, is_http, true, host, user)
	size += res_size
	closed = true
	return
}
Example #5
0
func getRequest(conn *ss.Conn, auth bool) (host string, ota bool, err error) {
	ss.SetReadTimeout(conn)

	// buf size should at least have the same size with the largest possible
	// request size (when addrType is 3, domain name has at most 256 bytes)
	// 1(addrType) + 1(lenByte) + 256(max length address) + 2(port) + 10(hmac-sha1)
	buf := make([]byte, 270)
	// read till we get possible domain length field
	if _, err = io.ReadFull(conn, buf[:idType+1]); err != nil {
		return
	}

	var reqStart, reqEnd int
	addrType := buf[idType]
	switch addrType & ss.AddrMask {
	case typeIPv4:
		reqStart, reqEnd = idIP0, idIP0+lenIPv4
	case typeIPv6:
		reqStart, reqEnd = idIP0, idIP0+lenIPv6
	case typeDm:
		if _, err = io.ReadFull(conn, buf[idType+1:idDmLen+1]); err != nil {
			return
		}
		reqStart, reqEnd = idDm0, int(idDm0+buf[idDmLen]+lenDmBase)
	default:
		err = fmt.Errorf("addr type %d not supported", addrType&ss.AddrMask)
		return
	}

	if _, err = io.ReadFull(conn, buf[reqStart:reqEnd]); err != nil {
		return
	}

	// Return string for typeIP is not most efficient, but browsers (Chrome,
	// Safari, Firefox) all seems using typeDm exclusively. So this is not a
	// big problem.
	switch addrType & ss.AddrMask {
	case typeIPv4:
		host = net.IP(buf[idIP0 : idIP0+net.IPv4len]).String()
	case typeIPv6:
		host = net.IP(buf[idIP0 : idIP0+net.IPv6len]).String()
	case typeDm:
		host = string(buf[idDm0 : idDm0+buf[idDmLen]])
	}
	// parse port
	port := binary.BigEndian.Uint16(buf[reqEnd-2 : reqEnd])
	host = net.JoinHostPort(host, strconv.Itoa(int(port)))
	// if specified one time auth enabled, we should verify this
	if auth || addrType&ss.OneTimeAuthMask > 0 {
		ota = true
		if _, err = io.ReadFull(conn, buf[reqEnd:reqEnd+lenHmacSha1]); err != nil {
			return
		}
		iv := conn.GetIv()
		key := conn.GetKey()
		actualHmacSha1Buf := ss.HmacSha1(append(iv, key...), buf[:reqEnd])
		if !bytes.Equal(buf[reqEnd:reqEnd+lenHmacSha1], actualHmacSha1Buf) {
			err = fmt.Errorf("verify one time auth failed, iv=%v key=%v data=%v", iv, key, buf[:reqEnd])
			return
		}
	}
	return
}
Example #6
0
func handleConnection(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.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, ota, err := getRequest(conn, auth)
	if err != nil {
		log.Println("error getting request", conn.RemoteAddr(), conn.LocalAddr(), err)
		return
	}
	debug.Println("connecting", 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.Println("dial error:", err)
		} else {
			log.Println("error connecting to:", host, err)
		}
		return
	}
	defer func() {
		if !closed {
			remote.Close()
		}
	}()
	if debug {
		debug.Printf("piping %s<->%s ota=%v connOta=%v", conn.RemoteAddr(), host, ota, conn.IsOta())
	}
	if ota {
		go ss.PipeThenCloseOta(conn, remote)
	} else {
		go ss.PipeThenClose(conn, remote)
	}
	ss.PipeThenClose(remote, conn)
	closed = true
	return
}
Example #7
0
func PipeThenCloseOta(src *ss.Conn, dst net.Conn, is_res bool, host string, user user.User) {
	const (
		dataLenLen  = 2
		hmacSha1Len = 10
		idxData0    = dataLenLen + hmacSha1Len
	)

	defer func() {
		dst.Close()
	}()
	var pipeBuf = leakybuf.NewLeakyBuf(nBuf, bufSize)
	buf := pipeBuf.Get()
	// sometimes it have to fill large block
	for i := 1; ; i += 1 {
		SetReadTimeout(src)
		n, err := io.ReadFull(src, buf[:dataLenLen+hmacSha1Len])
		if err != nil {
			if err == io.EOF {
				break
			}
			Log.Debug(fmt.Sprintf("conn=%p #%v read header error n=%v: %v", src, i, n, err))
			break
		}
		dataLen := binary.BigEndian.Uint16(buf[:dataLenLen])
		expectedHmacSha1 := buf[dataLenLen:idxData0]

		var dataBuf []byte
		if len(buf) < int(idxData0+dataLen) {
			dataBuf = make([]byte, dataLen)
		} else {
			dataBuf = buf[idxData0 : idxData0+dataLen]
		}
		if n, err := io.ReadFull(src, dataBuf); err != nil {
			if err == io.EOF {
				break
			}
			Log.Debug(fmt.Sprintf("conn=%p #%v read data error n=%v: %v", src, i, n, err))
			break
		}
		chunkIdBytes := make([]byte, 4)
		chunkId := src.GetAndIncrChunkId()
		binary.BigEndian.PutUint32(chunkIdBytes, chunkId)
		actualHmacSha1 := ss.HmacSha1(append(src.GetIv(), chunkIdBytes...), dataBuf)
		if !bytes.Equal(expectedHmacSha1, actualHmacSha1) {
			Log.Debug(fmt.Sprintf("conn=%p #%v read data hmac-sha1 mismatch, iv=%v chunkId=%v src=%v dst=%v len=%v expeced=%v actual=%v", src, i, src.GetIv(), chunkId, src.RemoteAddr(), dst.RemoteAddr(), dataLen, expectedHmacSha1, actualHmacSha1))
			break
		}

		if n, err := dst.Write(dataBuf); err != nil {
			Log.Debug(fmt.Sprintf("conn=%p #%v write data error n=%v: %v", dst, i, n, err))
			break
		}
		if is_res {
			err := storage.IncrSize(user, n)
			if err != nil {
				Log.Error(err)
			}
			Log.Debug(fmt.Sprintf("[port-%d] store size: %d", user.GetPort(), n))
		}
	}
	return
}
Example #8
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
}
Example #9
0
func handleConnection(conn *ss.Conn, port string, pflag *uint32, openvpn string) {
	var host string

	newConnCnt := atomic.AddUint64(&connCnt, 1) // connCnt++
	if newConnCnt%logCntDelta == 0 {
		log.Printf("Number of client connections reaches %d\n", newConnCnt)
	}

	// function arguments are always evaluated, so surround debug statement
	// with if statement
	ss.Debug.Printf("new client %s->%s\n", conn.RemoteAddr().String(), conn.LocalAddr())
	closed := false
	defer func() {
		ss.Debug.Printf("closed pipe %s<->%s\n", conn.RemoteAddr(), host)
		atomic.AddUint64(&connCnt, ^uint64(0)) // connCnt--
		if !closed {
			conn.Close()
		}
	}()

	h, p, extra, err := getRequest(conn)
	if err != nil {
		log.Println("error getting request", conn.RemoteAddr(), conn.LocalAddr(), err)
		return
	}
	host = h + ":" + p
	ss.Debug.Println("connecting", host)
	addr, err := net.ResolveIPAddr("ip", h)
	if err != nil {
		log.Println(err)
		return
	}
	ip := addr.String()
	if (strings.HasPrefix(ip, "127.") && (p != "1194" || openvpn != "ok")) ||
		strings.HasPrefix(ip, "10.8.") || ip == "::1" {
		log.Printf("illegal connect to local network(%s)\n", ip)
		return
	}
	remote, err := net.Dial("tcp", net.JoinHostPort(ip, p))
	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 {
			ss.Debug.Println("write request extra error:", err)
			return
		}
	}
	ss.Debug.Printf("ping %s<->%s", conn.RemoteAddr(), host)
	go ss.PipeThenClose(conn, remote, ss.SET_TIMEOUT, pflag, port, "out")
	ss.PipeThenClose(remote, conn, ss.NO_TIMEOUT, pflag, port, "in")
	closed = true
	return
}