Beispiel #1
0
func tcpClient(addr string, key, message []byte) ([]byte, error) {
	tcpaddr, err := net.ResolveTCPAddr("tcp", addr)
	if err != nil {
		return nil, err
	}

	ciphertext, err := libsodium.EncryptData(key, message)
	if err != nil {
		return nil, err
	}

	tcpconn, err := net.DialTCP("tcp", nil, tcpaddr)
	if err != nil {
		return nil, err
	}
	defer tcpconn.Close()

	tcpconn.SetWriteDeadline(time.Now().Add(time.Duration(20) * time.Second))
	_, err = tcpconn.Write(netstring.Marshall(ciphertext))
	if err != nil {
		return nil, err
	}

	tcpconn.SetReadDeadline(time.Now().Add(time.Duration(20) * time.Second))
	bufReader := bufio.NewReader(tcpconn)
	var buf bytes.Buffer
	var ip []byte
	for {
		rData, err := bufReader.ReadBytes(',')
		if err != nil {
			if err == io.EOF {
				return nil, err
			}
			buf.Write(rData)
			continue
		}
		buf.Write(rData)
		ip, err = netstring.Unmarshall(buf.Bytes())
		if err != nil {
			if err == netstring.ErrNsLenNotEqaulOrgLen {
				continue
			}
			return nil, err
		}
		break
	}
	return ip, nil
}
Beispiel #2
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)
	}
}
Beispiel #3
0
func handleUDPConn(udpconn *net.UDPConn, key []byte, receiveData []byte) {
	//udpconn.SetReadDeadline(time.Now().Add(time.Duration(20) * time.Second))
	receiveDatalen, addr, err := udpconn.ReadFrom(receiveData)
	if err != nil {
		log.Printf("udpconn ReadFrom err : %v\n", err)
	}

	receiveData, err = netstring.Unmarshall(receiveData[:receiveDatalen])
	if err != nil {
		log.Printf("netstring unmarshall error : %v\n", err)
		return
	}

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

	homeip = addr.String()
}