Пример #1
0
func (srv *Server) readTCP(conn *net.TCPConn, timeout time.Duration) ([]byte, error) {
	conn.SetReadDeadline(time.Now().Add(timeout))
	l := make([]byte, 2)
	n, err := conn.Read(l)
	if err != nil || n != 2 {
		if err != nil {
			return nil, err
		}
		return nil, ErrShortRead
	}
	length, _ := unpackUint16(l, 0)
	if length == 0 {
		return nil, ErrShortRead
	}
	m := make([]byte, int(length))
	n, err = conn.Read(m[:int(length)])
	if err != nil || n == 0 {
		if err != nil {
			return nil, err
		}
		return nil, ErrShortRead
	}
	i := n
	for i < int(length) {
		j, err := conn.Read(m[i:int(length)])
		if err != nil {
			return nil, err
		}
		i += j
	}
	n = i
	m = m[:n]
	return m, nil
}
Пример #2
0
func (server *TcpServer) Start() (err error) {
	for {
		var conn *net.TCPConn
		if conn, err = server.TCPListener.AcceptTCP(); err != nil {
			return err
		}
		if server.keepAlive != nil {
			if err := conn.SetKeepAlive(server.keepAlive.(bool)); err != nil {
				return err
			}
		}
		if server.keepAlivePeriod != nil {
			if kap, ok := (net.Conn(conn)).(iKeepAlivePeriod); ok {
				if err := kap.SetKeepAlivePeriod(server.keepAlivePeriod.(time.Duration)); err != nil {
					return err
				}
			}
		}
		if server.linger != nil {
			if err := conn.SetLinger(server.linger.(int)); err != nil {
				return err
			}
		}
		if server.noDelay != nil {
			if err := conn.SetNoDelay(server.noDelay.(bool)); err != nil {
				return err
			}
		}
		if server.readBuffer != nil {
			if err := conn.SetReadBuffer(server.readBuffer.(int)); err != nil {
				return err
			}
		}
		if server.writerBuffer != nil {
			if err := conn.SetWriteBuffer(server.writerBuffer.(int)); err != nil {
				return err
			}
		}
		if server.deadline != nil {
			if err := conn.SetDeadline(server.deadline.(time.Time)); err != nil {
				return err
			}
		}
		if server.readDeadline != nil {
			if err := conn.SetReadDeadline(server.readDeadline.(time.Time)); err != nil {
				return err
			}
		}
		if server.writerDeadline != nil {
			if err := conn.SetWriteDeadline(server.writerDeadline.(time.Time)); err != nil {
				return err
			}
		}
		if server.config != nil {
			server.ServeTCP(tls.Client(conn, server.config))
		} else {
			server.ServeTCP(conn)
		}
	}
}
Пример #3
0
func pipeThenClose(src, dst *net.TCPConn, finishChannel chan bool) {
	defer func() {
		src.CloseRead()
		dst.CloseWrite()
		finishChannel <- true
	}()

	buf := asocks.GetBuffer()
	defer asocks.GiveBuffer(buf)

	for {
		src.SetReadDeadline(time.Now().Add(60 * time.Second))
		n, err := src.Read(buf)
		if n > 0 {
			data := buf[0:n]
			encodeData(data)
			if _, err := dst.Write(data); err != nil {
				break
			}
		}
		if err != nil {
			break
		}
	}
}
Пример #4
0
func receiveTcpConn(conn *net.TCPConn, rc TcpReceiveCaller) {
	for {
		buf := bufio.NewReader(conn)
		line, err := buf.ReadBytes('\n')
		if err != nil {
			// remove client
			addr := conn.RemoteAddr().String()
			if v, ok := clients[addr]; ok {
				uid := v.UserId
				delete(clients, addr)
				addr2 := users[uid]
				if strings.Index(addr2, "$") == -1 {
					delete(users, uid)
				} else {
					users[uid] = strings.Replace(strings.Replace(addr2, addr, "", 1), "$$", "$", -1)
				}
			}
			printf(true, "[ CLIENT][ DISCONN] - IP : %s disconnect!active clients : %d",
				conn.RemoteAddr().String(), len(clients))
			break

		}
		if d, err := rc(conn, line[:len(line)-1]); err != nil { // remove '\n'
			conn.Write([]byte("error$" + err.Error()))
		} else if d != nil {
			conn.Write(d)
		}
		conn.Write([]byte("\n"))
		conn.SetReadDeadline(time.Now().Add(ReadDeadLine)) // discount after 5m
	}
}
Пример #5
0
//
// A TCP 'echo' example.
// Demonstrates using a timeout, and a 'graceful' shutdown if one occurs.
// 'Tested' using 'telnet localhost 45678'
//
func runReads(tcpConn *net.TCPConn) bool {
	br := bufio.NewReader(tcpConn)
	for {
		// Set a timeout value, which needs to be set before each and every read.
		d := time.Duration(30 * 1e9) // 30 seconds
		w := time.Now()              // from now
		w = w.Add(d)
		tcpConn.SetReadDeadline(w) // Set the deadline
		//
		buffer, err := br.ReadBytes('\n') // '\n' is delimiter
		// If the read times out, this prints something like:
		// Error = read tcp 127.0.0.1:57609: resource temporarily unavailable
		if err != nil {
			fmt.Printf("Error = %v\n", err)
			return false
			// panic("wtf04")
		}
		//
		fmt.Printf("Bytes Read: %d\n", len(buffer))
		var data = string(buffer)
		fmt.Printf("Data Read: |%q|\n", data)

		// This is now an 'echo' example.
		out := "echo: " + data
		tcpConn.Write([]byte(out))

		// The \r in this data from telnet is a bit surprising ...
		if data == "quit\r\n" {
			fmt.Println("Breaking....")
			break
		}
	}
	return true
}
Пример #6
0
func session(conn *net.TCPConn) {
	fmt.Println("here")
	var buf [2048]byte
	code := 0
	for {
		t := time.Now().Add(time.Millisecond * 100)
		conn.SetReadDeadline(t)
		n, err := conn.Read(buf[:])
		e, ok := err.(net.Error)

		if err != nil && ok && !e.Timeout() {
			fmt.Println(err)
			break
		}

		if n > 0 {
			process(conn, buf[:n])
		} else {
			msg := fmt.Sprintf("%v", code)
			code++
			conn.Write([]byte(msg))
		}
	}
	fmt.Println("session ended")
}
Пример #7
0
func (dc *DefaultConnector) receive(conn *net.TCPConn) ([]byte, error) {
	err := conn.SetReadDeadline(time.Now().Add(dc.config.ReadTimeout))
	if err != nil {
		return nil, err
	}

	header := make([]byte, 8)
	_, err = io.ReadFull(conn, header)
	if err != nil {
		return nil, err
	}

	decoder := NewBinaryDecoder(header)
	length, err := decoder.GetInt32()
	if err != nil {
		return nil, err
	}
	response := make([]byte, length-4)
	_, err = io.ReadFull(conn, response)
	if err != nil {
		return nil, err
	}

	return response, nil
}
Пример #8
0
// 协议封装读取
func TCPConnRead(conn *net.TCPConn) ([]byte, error) {
	conn.SetReadDeadline(time.Now().Add(time.Second * 30))
	result := bytes.NewBuffer(nil)
	data := make([]byte, 4)
	num, err := conn.Read(data)
	if err != nil || num != 4 {
		if err == nil {
			err = errors.New("length read error")
		}
		return nil, err
	}
	result.Write(data[0:num])
	var length int32
	err = binary.Read(result, binary.LittleEndian, &length)
	if err != nil {
		return nil, err
	}
	if length > MAX_PACKET_SIZE {
		return nil, errors.New("too large packet! packet size should less than 1M")
	}
	data = make([]byte, length)
	result = bytes.NewBuffer(nil)
	num, err = io.ReadFull(conn, data)
	if err != nil {
		return nil, err
	}
	result.Write(data[0:num])
	return result.Bytes(), nil
}
// read a reply to a buffer based on the expected message type
// return error if reply message has different type of command than expected
func readHelloReply(conn *net.TCPConn) (proto.Message, error) {
	duration := time.Second * 10
	timeNow := time.Now()
	err := conn.SetReadDeadline(timeNow.Add(duration))
	if err != nil {
		TimeEncodedPrint("Cant set read timeout", err.Error())
		return nil, err
	}
	length := int32(0)
	err = binary.Read(conn, binary.LittleEndian, &length)
	if DEBUG_READING_MESSAGE {
		fmt.Println("TRYING TO READ MESSAGE LENGTH => ", length, " ERROR: ", err)
	}

	if err != nil {
		return nil, err
	}

	if BYPASS_CONNECTION_SERVER {
		tempBuf := make([]byte, 8)
		_, err = io.ReadFull(conn, tempBuf)
		if DEBUG_READING_MESSAGE {
			fmt.Println("Trying to read extra 8 bytes:", tempBuf, " PROBLEM: ", err)
		}

		if err != nil {
			return nil, err
		}
		length = length - 8
	}

	rbuf := make([]byte, length)
	n, err := io.ReadFull(conn, rbuf)

	cmd := int(rbuf[0])

	switch cmd {
	case S2C_HelloInfoResult_CMD:
		res := &Auth_S2C.HelloInfoResult{}
		err := proto.Unmarshal(rbuf[1:], res)
		if err != nil {
			log.Fatal(err)
		} else {
			return res, nil
		}

	case ERROR_ErrorInfo_CMD:
		res := &Auth_S2C.ErrorInfo{}
		err := proto.Unmarshal(rbuf[1:], res)
		if err != nil {
			log.Fatal(err)
		}
		msg := fmt.Sprint("Server returns error: ")
		return res, errors.New(msg)
	default:
		log.Fatal("Unexpected CMD: ", cmd, "length is: ", length, " number bytes read: ", n, " error: ", err)
	}
	return nil, nil

}
Пример #10
0
Файл: duo.go Проект: api4me/next
func (t *Duo) Pipe(conn *net.TCPConn) {
	fd := t.Fd(conn)
	defer func() {
		t.Logger.Printf("disconnected: %s\n", fd)
		conn.Close()
		delete(t.Conn, fd)
	}()

	// Save in map
	t.Conn[fd] = conn

	// Read data
	reader := bufio.NewReader(conn)
	for {
		body, err := t.Unpack(reader)
		if err != nil {
			if err == io.EOF {
				return
			}
			if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
				return
			}
			t.Logger.Print(err)
		}

		conn.SetReadDeadline(time.Now().Add(20 * time.Second))

		if len(body) == 0 {
			continue
		}

		t.handler(conn, body)
		reader.Reset(conn)
	}
}
Пример #11
0
//处理连接请求
func (this *server) handlerConnection(conn *net.TCPConn) {

	defer logger.CatchException()

	logger.Infof("New connection coming ... IP=%s ", conn.RemoteAddr())

	conn.SetNoDelay(true)                                        //无延迟
	conn.SetKeepAlive(true)                                      //保持激活
	conn.SetReadBuffer(64 * 1024)                                //设置读缓冲区大小
	conn.SetWriteBuffer(64 * 1024)                               //设置写缓冲区大小
	conn.SetReadDeadline(time.Now().Add(30000000 * time.Second)) //设置读超时

	session := network.NewSession(conn)
	defer session.Close()

	for {
		msg, err := session.RecvMSG()
		if err != nil {
			logger.Infof("RecvMsgs IP=%s err=%v", conn.RemoteAddr(), err.Error())
			return
		}

		ret := this.ProcessMessage(session, msg)
		if ret == false {
			return
		}
	}
}
Пример #12
0
// Takes two existing TCP connections and copies all incoming traffic to the
// other channel. Returns only upon an error
// This function has some commented out code. This was me playing with TCP
// keepalive and the annoying missing API from go.
// It doesn't work so it's now kept simple and just disconnects after inactivity.
func (p *proxy) pipe(src, dst *net.TCPConn) {
	islocal := src == p.lconn

	// Detecting a broken/down connection in TCP is a little tricky as it turns
	// out:
	// http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/usingkeepalive.html
	// $ tail /proc/sys/net/ipv4/tcp_keepalive_*
	// ==> /proc/sys/net/ipv4/tcp_keepalive_intvl <==
	// 75
	// ==> /proc/sys/net/ipv4/tcp_keepalive_probes <==
	// 9
	// ==> /proc/sys/net/ipv4/tcp_keepalive_time <==
	// 7200
	// Unfortunately GO sets both, interval and idle time :(
	// http://felixge.de/2014/08/26/tcp-keepalive-with-golang.html

	// src.SetKeepAlive(true)
	// src.SetKeepAlivePeriod(TCP_KEEP_ALIVE) // Bad don't set (read blog post above)
	// linuxEnableKeepAlive(src)

	// directional copy (16k buffer)
	buff := make([]byte, 0x3fff)
	// This loop is our main copy loop. It takes each packet and just shoves it
	// into the other side. This works for both ways
	for {
		// We will set a timeout so that we also drop clients after a while of
		// no activity.
		// Problem: This also dropps the connection even if sitting on an idle
		// shell. But who really leaves it hanging for days without any input/output?
		src.SetReadDeadline(time.Now().Add(TCP_READ_TIMEOUT))
		n, err := src.Read(buff)
		if err != nil {
			if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
				// Activate TCPs keepalive now which will close the connection
				// if the client is gone
				// TODO: Doesnt work:
				// linuxEnableKeepAlive(src)
				p.disconnect("Inactive client '%s'\n", err)
				return
			} else {
				p.disconnect("Read failed '%s'\n", err)
				return
			}
		}
		b := buff[:n]
		// write out result
		n, err = dst.Write(b)
		if err != nil {
			p.disconnect("Write failed '%s'\n", err)
			return
		}
		if islocal {
			p.sentBytes += uint64(n)
		} else {
			p.receivedBytes += uint64(n)
		}
	}
}
// read a reply to a buffer based on the expected message type
// return error if reply message has different type of command than expected
func readReply(conn *net.TCPConn) (proto.Message, error) {
	duration := time.Millisecond * 20
	timeNow := time.Now()
	err := conn.SetReadDeadline(timeNow.Add(duration))
	if err != nil {
		TimeEncodedPrint("Cant set read timeout", err.Error())
		return nil, err
	}
	length := int32(0)
	err = binary.Read(conn, binary.LittleEndian, &length)
	if err != nil {
		return nil, nil
	}

	if DEBUG_STEP {
		fmt.Println("RECEIVE MESSAGE LENGTH: ", length)
	}
	// now wait longer for the message data
	duration = time.Millisecond * 100
	timeNow = time.Now()
	err = conn.SetReadDeadline(timeNow.Add(duration))

	rbuf := make([]byte, length)
	io.ReadFull(conn, rbuf)
	if DEBUG_STEP {
		fmt.Println(rbuf)
	}

	cmd := int(rbuf[0])

	switch cmd {
	case S2C_HelloInfoResult_CMD:
		res := &Auth_S2C.HelloInfoResult{}
		err := proto.Unmarshal(rbuf[1:], res)
		if err != nil {
			log.Fatal(err)
		} else {
			return res, nil
		}

	case ERROR_ErrorInfo_CMD:
		res := &Auth_S2C.ErrorInfo{}
		err := proto.Unmarshal(rbuf[1:], res)
		if err != nil {
			log.Fatal(err)
		}
		msg := fmt.Sprint("Server returns error: ")
		return res, errors.New(msg)
	default:
		log.Fatal("Unexpected CMD: ", cmd)
	}
	return nil, nil

}
Пример #14
0
func (s Sender) sendData(data []byte, conn *net.TCPConn) bool {
	if len(data) == 0 {
		return true
	}

	if conn == nil {
		return false
	}
	/*
	   lenBuf := make([]byte, 4)
	   nData := len(data)
	   binary.PutUvarint(lenBuf, uint64(nData))
	   data = append(lenBuf, data...)
	*/

	st := time.Now()
	packId := tcp_pack.GetPackId(data)

	conn.SetDeadline(time.Now().Add(5 * time.Minute)) //设置超时
	loglib.Info(fmt.Sprintf("sender%d start sending pack:%s length:%d", s.id, packId, len(data)))
	n, err := conn.Write(data)
	ed := time.Now()
	loglib.Info(fmt.Sprintf("sender%d end sending pack:%s length:%d elapse:%s", s.id, packId, n, ed.Sub(st)))

	lib.CheckError(err)

	//写失败了就不用等应答了,肯定拿不到
	if err == nil {
		conn.SetReadDeadline(time.Now().Add(8 * time.Minute)) //设置超时
		time1 := time.Now()
		var temp []byte = make([]byte, 128)
		count, err := conn.Read(temp)
		if err == nil {
			loglib.Info(fmt.Sprintf("sender%d get anwser data len:%d for pack:%s elapse:%s", s.id, count, packId, time.Now().Sub(time1)))
		} else {
			loglib.Info(fmt.Sprintf("sender%d get anwser data len:%d for pack:%s elapse:%s, error:%s", s.id, count, packId, time.Now().Sub(time1), err.Error()))
		}

		temp = temp[:count]
		if string(temp) == "ok" { //发送成功
			return true
		} else if string(temp) == "wrong header" {
			//包头错误,丢弃
			loglib.Info(packId + " has wrong header, retry later!")
			return false
		} else { //发送失败
			//报警
			return false
		}
	} else {
		loglib.Warning(fmt.Sprintf("write pack %s error:%s", packId, err.Error()))
	}
	return false
}
Пример #15
0
/*
	keep routine for write and read
*/
func serverKeeper(conn *net.TCPConn) {
	// conn.SetKeepAlive(true)
	request := make([]byte, 1024) // set maxium request length to 128B to prevent flood attack
	defer func() {
		sendChan <- "&**& quit this server &**&" //退出协程并且删掉主对象
	}() // close connection before exit

	// send
	go func() {
		for {
			sendData := <-sendChan
			if sendData != "&**& quit this server &**&" {
				// fmt.Println("server sending...", sendData)
				_, err := conn.Write([]byte(sendData))
				checkError(err)
			} else {
				//崩溃退出关闭发送协程
				conn.Close()
				fmt.Println("quit server Keeper success")
				return
			}
		}
	}()

	//read
	for {
		conn.SetReadDeadline(time.Now().Add(2 * time.Minute)) // set 2 minutes timeout
		read_len, err := conn.Read(request)

		if err != nil {
			if err.Error() == "EOF" {
				fmt.Println("this is EOF")
				break
			}
			fmt.Println(err)
			fmt.Println(err.Error())
			//break
		}

		if read_len == 0 {
			break // connection already closed by client
		} else {
			fmt.Println("receive", string(request))
			temp := gocommand.DeCode(string(request))
			if temp == " !heart beat! " || temp == "" {
				//heart beat
			} else {
				receiveChan <- temp
			}
		}
		request = make([]byte, 1024) // clear last read content
	}
}
// read a reply to a buffer based on the expected message type
// return error if reply message has different type of command than expected
func readHelloReply(conn *net.TCPConn) (proto.Message, error) {
	duration, _ := time.ParseDuration("1s")
	timeNow := time.Now()
	err := conn.SetReadDeadline(timeNow.Add(duration))
	if err != nil {
		TimeEncodedPrint("Cant set read timeout", err.Error())
		return nil, err
	}
	length := int32(0)
	err = binary.Read(conn, binary.LittleEndian, &length)
	if err != nil {
		return nil, err
	}

	if BYPASS_CONNECTION_SERVER {
		tempBuf := make([]byte, 8)
		_, err = io.ReadFull(conn, tempBuf)
		if err != nil {
			return nil, err
		}
		length = length - 8
	}

	rbuf := make([]byte, length)
	io.ReadFull(conn, rbuf)

	cmd := int(rbuf[0])

	switch cmd {
	case S2C_HelloInfoResult_CMD:
		res := &Auth_S2C.HelloInfoResult{}
		err := proto.Unmarshal(rbuf[1:], res)
		if err != nil {
			log.Fatal(err)
		} else {
			return res, nil
		}

	case ERROR_ErrorInfo_CMD:
		res := &Auth_S2C.ErrorInfo{}
		err := proto.Unmarshal(rbuf[1:], res)
		if err != nil {
			log.Fatal(err)
		}
		msg := fmt.Sprint("Server returns error: ")
		return res, errors.New(msg)
	default:
		log.Fatal("Unexpected CMD: ", cmd)
	}
	return nil, nil

}
Пример #17
0
func readStickPackLoop(c *net.TCPConn, rchan chan gotcp.Packet) {

	defer func() {
		recover()
		c.Close()

	}()

	reader := bufio.NewReader(c)
	unCompleteBuffer := make([]byte, 0)
	buffer := make([]byte, 1024)
	for {
		/*
			select {
			case <-c.srv.exitChan:
				return

			case <-c.closeChan:
				return

			default:
			}
		*/
		c.SetReadDeadline(time.Now().Add(time.Second * 30))
		n, err := reader.Read(buffer)

		if e, ok := err.(net.Error); ok && e.Timeout() {
			continue
			// This was a timeout
		} else if err != nil {
			if err == io.EOF {
				l4g.Info("client read a eof error: %v", err)
			}

			l4g.Info("client read a error: %v", err)
			return
			// This was an error, but not a timeout

		}

		if n == 1 && string(buffer[:1]) == "P" {
			l4g.Debug("connection %p reciev ping", c)

		}
		if n > 0 {
			//fmt.Println("n is ========================================", n)
			unCompleteBuffer = gotcp.Unpack(append(unCompleteBuffer, buffer[:n]...), rchan)

		}

	}
}
Пример #18
0
func (n *Node) receive(conn *net.TCPConn) (*message, error) {
	dec := gob.NewDecoder(conn)
	m := new(message)

	deadline := time.Now().Add(n.getNetworkTimeout())
	if err := conn.SetReadDeadline(deadline); err != nil {
		return nil, err
	}
	if err := dec.Decode(&m); err != nil {
		return nil, err
	}
	return m, nil
}
Пример #19
0
func readBytes(conn *net.TCPConn, buf []byte) (int, error) {
	off := 0
	for off != len(buf) {
		if err := conn.SetReadDeadline(time.Now().Add(time.Second * 90)); err != nil {
			return 0, err
		}
		if n, err := conn.Read(buf[off:]); err != nil {
			return off, err
		} else {
			off += n
		}
	}
	return off, nil
}
Пример #20
0
func readDataRoutine(fd int, did string, hash string, conn *net.TCPConn, callback ReadCallback) error {
	buf := make([]byte, 1024*32)

	for {
		log.Println("[getrelayv2]fd=", fd, " Start to Read")

		n, err := conn.Read(buf)
		conn.SetReadDeadline(time.Now().Add(socket_read_timeout * time.Second))
		if err != nil || err == io.EOF {
			if err == io.EOF {
				if n > 0 { //Recieve Content
					is404 := strings.Contains(string(buf), "404 Not Found")
					if is404 == true { // Recieve 404 report and close connection, no need to reconnect
						closeFD(conn, fd, callback, true, error_404)
						log.Println("[getrelayv2]readDataRoutine", " did=", did, " fd=", fd, "EOF&404")
						return errors.New("404 found")
					}
					// Not 404,  send to callback and reconnect
					callback.ReadBytes(buf[0:n])
					log.Println("[getrelayv2]readDataRoutine", "sendcallbac:", string(buf[0:n]))
					go reconnect(fd, did, hash, callback)
					log.Println("[getrelayv2]readDataRoutine", " did=", did, " fd=", fd, "EOF&Content")
					return errors.New("EOF found")
				} else { // no content , reconnect again
					//closeFD(conn, fd, callback , false, error_none)
					log.Println("[getrelayv2]readDataRoutine", " did=", did, " fd=", fd, "EOF")
					go reconnect(fd, did, hash, callback)
					return nil
				}
			} else { // Read Error
				closeFD(conn, fd, callback, true, mapIoError(err))
				log.Println("Read Error =", err)
				return errors.New("TCP Read Error:")
			}
		} // End of EOF or read error

		if n > 0 {
			is404 := strings.Contains(string(buf), "404 Not Found")
			if is404 == true { // Recieve 404 report and close connection, no need to reconnect
				closeFD(conn, fd, callback, true, error_404)
				log.Println("[getrelayv2]readDataRoutine", " did=", did, " fd=", fd, "404")
				return errors.New("404 found")
			}
			// Not 404
			callback.ReadBytes(buf[0:n])
			log.Println("[getrelayv2]readDataRoutine", " did=", did, " fd=", fd, " SendToCallback=", string(buf[0:n]))
		}
	}
	return nil
}
func loop(conn *net.TCPConn) {
	defer conn.Close()

	conn.SetLinger(5)
	conn.SetKeepAlive(false)
	conn.SetNoDelay(true)
	now := time.Now()

	conn.SetReadDeadline(now.Add(readWriteLimit))

	if _, err := io.ReadFull(conn, buf); err == nil {
		conn.Write(response)
	}
}
Пример #22
0
// Demo multiple echo clients.
// 'Test' using 'telnet localhost 45678' from multiple open terminals.
func getData(c *net.TCPConn) {
	var buffer = make([]byte, 4096)
	a := c.RemoteAddr()
	fmt.Printf("Net: %s, Remote: %s\n", a.Network(), a.String())
	for {
		if shutdown {
			fmt.Println(c, "Shutdown")
			break
		}
		fmt.Println(c, "Starting Read ...")
		_ = c.SetReadDeadline(time.Now().Add(1 * time.Minute))
		bytesRead, err := c.Read(buffer)
		if err != nil && err.(net.Error).Timeout() {
			continue
		}
		if err != nil {
			fmt.Printf("Error = %v\n", err)
			break
		}
		//
		fmt.Println(c, "Bytes Read", bytesRead)
		bufData := buffer[0:bytesRead]
		fmt.Println(c, "Raw Buffer", bufData)
		var data = string(bufData)
		fmt.Println(c, "Data Read", data)
		//
		s := "Echo: " + data
		if _, err := c.Write([]byte(s)); err != nil {
			fmt.Printf("Error = %v\n", err)
			panic("wtfwr01")
		}
		//
		if strings.HasPrefix(data, "quit") {
			break
		}
		//
		if strings.HasPrefix(data, "shutdown") {
			shutdown = true
		}
	}
	//
	fmt.Println(c, "Starting Close() 1")
	err := c.Close()
	if err != nil {
		fmt.Printf("Error = %v\n", err)
		panic("wtf05")
	}
	//
}
Пример #23
0
func (s *Server) handleConnection(conn *net.TCPConn) {
	defer conn.Close()

	conn.SetReadDeadline(time.Now().Add(time.Second))
	r := bufio.NewReader(conn)
	_, err := r.ReadString('\x00')
	if err != nil {
		if err != io.EOF {
			log.Println(err)
		}
		return
	}
	conn.Write(s.b)
	log.Println("fsp: Sent policy file to", conn.RemoteAddr().String())
}
Пример #24
0
func (server *Server) setupSocket(conn *net.TCPConn) (err error) {
	if err = conn.SetLinger(0); err != nil {
		return
	}
	if server.ConfigReadBuffer != 0 {
		if err = conn.SetReadBuffer(int(server.ConfigReadBuffer)); err != nil {
			return
		}
	}
	if err = conn.SetKeepAlive(true); err != nil {
		return
	}
	if err = conn.SetReadDeadline(time.Now().Add(server.ConfigIdleTimeout)); err != nil {
		return
	}
	return
}
Пример #25
0
func handleTCPConn(tcpconn *net.TCPConn, encryptKey []byte, buffer *bytes.Buffer, bpool *bpool.SizedBufferPool) {
	defer tcpconn.Close()
	defer bpool.Put(buffer)
	var receiveData []byte
	//tcpconn need read all data in 20 second ,otherwise Timeout() will be true
	tcpconn.SetReadDeadline(time.Now().Add(time.Duration(20) * time.Second))
	bufReader := bufio.NewReader(tcpconn)
	for {
		rData, err := bufReader.ReadBytes(',')
		if err != nil {
			if err == io.EOF {
				log.Printf("TCPConn Read error\n")
				return
			}
			buffer.Write(rData)
			continue
		}

		buffer.Write(rData)

		receiveData, err = netstring.Unmarshall(buffer.Bytes())
		if err != nil {
			if err == netstring.ErrNsLenNotEqaulOrgLen {
				continue
			} else {
				log.Printf("netstring unmarshall error : %v\n", err)
				return
			}
		}

		break
	}

	_, err := libsodium.DecryptData(encryptKey, receiveData)
	if err != nil {
		log.Printf("tcp DecryptData error : %v\n", err)
		return
	}

	tcpconn.SetWriteDeadline(time.Now().Add(time.Duration(20) * time.Second))
	_, err = tcpconn.Write(netstring.Marshall([]byte(homeip)))
	if err != nil {
		log.Printf("tcpconn error : %v\n", err)
	}
}
Пример #26
0
func (cli *MelonClient) Run(conn *net.TCPConn, recvChan chan []MyPacket, closed func(conn *net.TCPConn)) {
	var temp string
	buffer := make([]byte, 1024)
	for {
		n, err := conn.Read(buffer)
		if err != nil {
			closed(conn)
			return
		}
		if n == 0 {
			closed(conn)
			return
		}
		conn.SetReadDeadline(time.Now().Add(1 * time.Minute))
		remain, pks := CheckPacket(temp + string(buffer[:n]))
		recvChan <- pks
		temp = remain
	}
}
Пример #27
0
func handleReceivingMsg(conn *net.TCPConn, userid uint64, shouldQuit chan bool) {
	defer func() {
		shouldQuit <- true
		conn.Close()

		logger.Info("Close reading connection for user %d")
	}()

	for {
		now := time.Now()
		timeout := now.Add(time.Hour * time.Duration(readTimeoutInHour))
		conn.SetReadDeadline(timeout)

		msgTypeByte := make([]byte, 1)
		_, err := io.ReadFull(conn, msgTypeByte)
		if err != nil {
			logger.Errorf("Connection Read Msg Type Error. Error: %s.", err)
			break
		}

		msgTypeByte = append(make([]byte, 1), msgTypeByte[0])
		msgType := uint16(binary.BigEndian.Uint16(msgTypeByte))

		msgLenByte := make([]byte, 4)
		_, err = io.ReadFull(conn, msgLenByte)
		if err != nil {
			logger.Errorf("Connection Read Msg Length Error. Error: %s.", err)
			break
		}

		msgLen := int(binary.BigEndian.Uint32(msgLenByte))

		buf := make([]byte, int64(msgLen))
		_, err = io.ReadFull(conn, buf)
		if err != nil {
			logger.Errorf("Connection Read Msg Content Error. Error: %s", err)
			break
		}

		connService.HandleReceivingMsg(msgType, buf)

	}
}
Пример #28
0
func handleClient(source *net.TCPConn) {
	atomic.AddInt32(&daemon.status.actives, 1)
	defer func() {
		atomic.AddInt32(&daemon.status.actives, -1)
		daemon.wg.Done()
	}()

	Info("accept new connection: %v", source.RemoteAddr())

	source.SetKeepAlive(true)
	source.SetKeepAlivePeriod(time.Second * 60)
	source.SetLinger(-1)

	// read req
	// set read request timeout
	source.SetReadDeadline(time.Now().Add(time.Second * 30))
	err, req := ReadReq(source)
	if err != nil {
		source.Close()
		Error("conn:%v, read req failed: %v", source.RemoteAddr(), err)
		return
	}

	// cancel read timeout
	var t time.Time
	source.SetReadDeadline(t)

	// judge: new conn or reuse conn
	switch req := req.(type) {
	case *NewConnReq:
		Info("new conn request:%v", req)
		onNewConn(source, req)
	case *ReuseConnReq:
		Info("reuse conn request:%v", req)
		onReuseConn(source, req)
	default:
		Info("unknown request:%v", req)
		source.Close()
		return
	}
	Info("connection close: %v", source.RemoteAddr())
}
Пример #29
0
func waitRegister(conn *net.TCPConn) *Client {
	conn.SetReadDeadline(time.Now().Add(10 * time.Second))
	buf := make([]byte, 10)
	n, err := io.ReadFull(conn, buf)
	if err != nil {
		log.Errorf("readfull header failed (%v)", err)
		conn.Close()
		return nil
	}

	var header Header
	if err := header.Deserialize(buf[0:n]); err != nil {
		log.Errorf("parse header (%v)", err)
		conn.Close()
		return nil
	}

	//log.Printf("body len %d", header.Len)
	data := make([]byte, header.Len)
	if _, err := io.ReadFull(conn, data); err != nil {
		log.Errorf("readfull body failed: (%v)", err)
		conn.Close()
		return nil
	}

	if header.Type != MSG_REGISTER {
		log.Warnf("not register message")
		conn.Close()
		return nil
	}

	devid := string(data)
	log.Infof("recv register devid (%s)", devid)
	if DevMap.Check(devid) {
		log.Warnf("device (%s) register already", devid)
		conn.Close()
		return nil
	}
	client := InitClient(conn, devid)
	return client
}
Пример #30
0
func (server *Server) addConnection(tcpConn *net.TCPConn) *Connection {
	clientId := tcpConn.RemoteAddr().String()
	var err error
	if server.ConfigDebug {
		log.Printf("Server.addConnection: %s", clientId)
	}

	// TODO: set expected clientLocks to average+1
	if err = server.initClientLocks(clientId, 1); err != nil {
		log.Printf("Server.addConnection: %s %s", clientId, err.Error())
		return nil
	}

	if err := server.setupSocket(tcpConn); err != nil {
		log.Printf("Server.addConnection: %s setupSocket error: %s", clientId, err.Error())
		return nil
	}

	conn := NewConnection(server, clientId)
	conn.handlers = map[dlock.RequestType]HandlerFunc{
		dlock.RequestType_Ping: handlePing,
		dlock.RequestType_Lock: handleLock,
	}
	conn.funClose = tcpConn.Close
	conn.funResetIdleTimeout = func() error { return tcpConn.SetReadDeadline(time.Now().Add(server.ConfigIdleTimeout)) }
	conn.funResetReadTimeout = func() error { return tcpConn.SetReadDeadline(time.Now().Add(server.ConfigReadTimeout)) }
	conn.funResetWriteTimeout = func() error { return tcpConn.SetWriteDeadline(time.Now().Add(server.ConfigWriteTimeout)) }

	if server.ConfigReadBuffer == 0 {
		conn.r = bufio.NewReader(tcpConn)
	} else {
		conn.r = bufio.NewReaderSize(tcpConn, int(server.ConfigReadBuffer))
	}
	conn.w = bufio.NewWriter(tcpConn)

	server.wg.Add(1)
	go conn.loop()

	return conn
}