Пример #1
0
func process_connection(conn net.Conn) {
	defer conn.Close()
	buf := make([]byte, 512)
	for {
		fmt.Print("server: ready to read\n")
		n, err := conn.Read(buf)
		if err != nil {
			if err == io.EOF {
				break
			}
			if err != nil {
				fmt.Printf("conn.Read() failed: %s\n", err)
			}
			break
		}

		fmt.Printf("server: received %q\n", string(buf[:n]))

		n, err = conn.Write([]byte("world"))
		fmt.Println("server: wrote back to client")

		if err != nil {
			fmt.Printf("conn.Write() failed: %s\n", err)
			break
		}
	}
	fmt.Println("server: conn: closed")
}
Пример #2
0
func handleApiRequest(conn net.Conn) {
	// Make a buffer to hold incoming data.
	buf := make([]byte, 1024)
	// Read the incoming connection into the buffer.
	for {
		n, err := conn.Read(buf)
		if err != nil {
			if err == io.EOF {
				fmt.Println("read eof. closing")
			} else {
				fmt.Println("Error reading:", err.Error())
			}
			conn.Close()
			break
		}
		clean_cmd := strings.TrimSpace(string(buf[:n]))
		command := strings.Split(clean_cmd, " ")
		log.Println("received command: '" + clean_cmd + "'")
		req := Req{command, &conn}
		fn := getHandler(clean_cmd)
		if fn != nil {
			err := fn(req)
			if err != nil {
				conn.Write([]byte(err.Error() + "\n"))
			}
		} else {
			conn.Write([]byte("unrecognized command\n"))
		}
	}
}
Пример #3
0
func handleConnection(c net.Conn) {
	defer c.Close()

	buffer := make([]byte, MAXBUFFER)

	for {
		mlen, err := c.Read(buffer)

		if err != nil {
			return
		}

		if mlen < 3 {
			continue
		}

		if mlen > MAXBUFFER {
			msg := fmt.Sprintf("Message exceeded %d bytes", MAXBUFFER)
			warn(msg)
			c.Write([]byte(msg))
			return
		}

		resp := handleCommand(string(buffer[:mlen]))

		c.Write([]byte(resp))
	}

}
Пример #4
0
func Pipe(src, dst net.Conn, end chan byte) {
	// Should not use io.Copy here.
	// io.Copy will try to use the ReadFrom interface of TCPConn, but the src
	// here is not a regular file, so sendfile is not applicable.
	// io.Copy will fallback to the normal copy after discovering this,
	// introducing unnecessary overhead.
	buf := make([]byte, 4096)
	for {
		SetReadTimeout(src)
		n, err := src.Read(buf)
		// read may return EOF with n > 0
		// should always process n > 0 bytes before handling error
		if n > 0 {
			if _, err = dst.Write(buf[0:n]); err != nil {
				Debug.Println("write:", err)
				break
			}
		}
		if err != nil {
			if err != io.EOF {
				Debug.Println("read:", err)
			}
			break
		}
	}
	end <- 1
}
Пример #5
0
func readDHTMsg(conn net.Conn) (*DHTMsg, error) {
	buf := make([]byte, 4096)
	_, err := conn.Read(buf[:8])
	if err != nil {
		return nil, err
	}

	length, bytesRead := binary.Uvarint(buf[:8])
	if bytesRead < 0 {
		return nil, errors.New("Unable to parse length of dht protobuf")
	}

	_, err = conn.Read(buf[:length])
	if err != nil {
		return nil, err
	}

	dhtMsg := new(DHTMsg)
	err = proto.Unmarshal(buf[:length], dhtMsg)
	if err != nil {
		return nil, err
	}

	return dhtMsg, nil
}
Пример #6
0
func read(buf []byte, con net.Conn) {
	n, err := con.Read(buf)
	if err != nil && err.String() == "Timeout() == true" {
		com.Log(6, "Read time-out reached. Read "+fmt.Sprint(n)+" bytes.")
	}
	com.Log(8, "Answer recived!")
}
Пример #7
0
func (this *Server) receive(buf []byte, conn net.Conn) ([]byte, error) {
	conn.SetDeadline(time.Now().Add(this.connTimeout))
	readNum := 0
	length := len(buf)

	var num int
	var err error
	for readNum < length {
		num, err = conn.Read(buf[readNum:])
		if err != nil {
			if netErr, ok := err.(net.Error); ok && netErr.Temporary() {
				time.Sleep(time.Second)
				continue
			}
			return nil, err
		}
		this.logger.Debug("Read %d bytes: %s", num, string(buf))
		readNum += num
	}

	_, err = conn.Write([]byte("ok"))
	if err != nil {
		return nil, err
	}

	return buf, nil
}
Пример #8
0
// 客户端连接的处理逻辑。 首先握手,握手失败关闭连接;然后读数据,写入 Dispatcher 的处理队列。
func Handler(conn net.Conn, hsPwd string, inputChid string) {
	defer conn.Close()

	chid := ""
	if len(inputChid) < 1 {
		ch, recvers, err := HandShake(conn, hsPwd)
		if err != nil {
			return
		}
		chid = ch
		createConnQ <- &ConnInfo{conn, chid, 600, recvers}
	} else {
		chid = inputChid
		createConnQ <- &ConnInfo{conn, chid, 0, nil}
	}

	for {
		data := make([]byte, 1048576)
		n, err := conn.Read(data) // 读出数据,放入 Dispatcher 的发送队列
		if err != nil {           // 关闭时给 Dispatcher 发送通知
			if err == io.EOF {
				log.Println("Connection closed!")
			} else {
				log.Println("Read error: ", err)
			}
			removeConnQ <- chid
			break
		}
		conn.SetDeadline(time.Now().Add(time.Duration(120) * time.Second))
		log.Println("Read data:", string(data[:n]))
		sendQ <- SendQEle{chid, bytes.NewBuffer(data[:n])}
	}
}
Пример #9
0
func handleClient(conn net.Conn) {
	conn.SetReadDeadline(time.Now().Add(2 * time.Minute)) // 2分钟无接收信息超时
	//func (c *TCPConn) SetReadDeadline(t time.Time) error
	//func (c *TCPConn) SetWriteDeadline(t time.Time) error

	defer conn.Close()

	for {
		request := make([]byte, 128)
		//128 位读取信息
		read_len, err := conn.Read(request)

		if err != nil {
			fmt.Println(err)
			break
		}

		if read_len == 0 {
			break // connection already closed by client
		} else if string(request) == "timestamp" {
			daytime := strconv.FormatInt(time.Now().Unix(), 10)
			conn.Write([]byte(daytime))
		} else {
			daytime := time.Now().String()
			conn.Write([]byte(daytime))
		}

	}
}
Пример #10
0
func (ch *ConnectHandler) HandleConnectRequest(conn net.Conn) {
	buff := make([]byte, 33)
	bytes, err := conn.Read(buff)
	if err != nil || bytes != 33 {
		conn.Close()
		log.Print("Malformed Connect packet")
		return
	}
	ttl := uint8(buff[0])
	var port uint32
	binary.Read(_bytes.NewBuffer(buff[1:5]), binary.LittleEndian, &port)
	target := string(buff[5:bytes])
	if target == ch.MyID {
		log.Print("New ConnectLocalRequest to port: " + strconv.FormatUint(uint64(port), 10))
		ch.Out <- NewEvent("ConnectLocalRequest", &ConnectLocalPayload{conn, port})
		return
	}
	if ttl == 0 {
		log.Print("TTL == 0 -> dont forward")
		conn.Close()
		return
	}
	log.Print("New ConnectForwardRequest")
	ch.Out <- NewEvent("ConnectForwardRequest", &ConnectForwardPayload{conn, target, ttl, port})
}
Пример #11
0
func serveConn(c net.Conn) error {
	defer c.Close()

	pub, priv, err := box.GenerateKey(rand.Reader)
	if err != nil {
		return fmt.Errorf("could not generate key: %s", err)
	}

	n, err := c.Write(pub[:])
	if err != nil || n != 32 {
		return fmt.Errorf("handshake failed, could not send public key:%s", err)
	}

	var clientPub [32]byte
	if n, err := c.Read(clientPub[:]); n != 32 || err != nil {
		return fmt.Errorf("handshake failed, did not receive public key:%s", err)
	}

	sr := NewSecureReader(c, priv, &clientPub)
	sw := NewSecureWriter(c, priv, &clientPub)

	if _, err := io.Copy(sw, sr); err != nil {
		return fmt.Errorf("serve copy failed: %s", err)
	}

	return nil
}
Пример #12
0
// WithErrorCode wraps a connection and enables you to close it with an error
// code on one side and read it on the other after the connection is closed.
//
// Both ends of a connection must wrap it with this function for it to work.
func WithErrorCode(whole net.Conn) (ErrorCodeRWC, error) {

	// Throw dice (write and read a random byte) to determine who's going
	// to be multiplex server and client.
	writeErrCh := make(chan error)
	var myDice byte
	var theirDice [1]byte
	for {
		myDice = byte(rand.Intn(256))
		go func() {
			_, err := whole.Write([]byte{myDice})
			writeErrCh <- err
		}()

		_, err := whole.Read(theirDice[:])
		if err != nil {
			return nil, err
		}

		err = <-writeErrCh
		if err != nil {
			return nil, err
		}

		if myDice != theirDice[0] {
			break
		}
	}

	if myDice > theirDice[0] {
		return client(whole)
	} else {
		return server(whole)
	}
}
func (cM *ConnectionManager) messageReady(conn net.Conn, user *User) {
	uChan := make(chan []byte)
	for {
		buf := make([]byte, INPUT_BUFFER_LENGTH)
		n, err := conn.Read(buf)
		if err != nil {
			conn.Close()
		}
		if n == 0 {
			conn.Close()
		}
		fmt.Println(n, "character message from user", user.Name)
		if user.Initiated == false {
			fmt.Println("New User is", string(buf))
			user.Initiated = true
			user.UChannel = uChan
			user.Name = string(buf[:n])
			user.Connection = &conn
			go user.Listen()

			minusYouCount := strconv.FormatInt(int64(connectionCount-1), 10)
			conn.Write([]byte("Welcome to the chat, " + user.Name + ", there are " + minusYouCount + " other users"))
		} else {
			sendMessage := []byte(user.Name + ": " + strings.TrimRight(string(buf), " \t\r\n"))
			for _, u := range Users {
				if evalMessageRecipient(sendMessage, u.Name) == true {
					u.UChannel <- sendMessage
				}
			}

		}

	}
}
Пример #14
0
func handleConnection(n net.Conn) {
	l := make([]byte, 1024)
	_, err := n.Read(l)
	if err != nil {
		panic("server read error")
	}

	// Bind Resp
	d, _ := hex.DecodeString("000000158000000900000000000000016875676f00")
	n.Write(d)

	time.Sleep(100 * time.Millisecond)

	// Invalid CMD ID
	d, _ = hex.DecodeString("0000001090000015000000005222b523")
	n.Write(d)

	time.Sleep(100 * time.Millisecond)

	// PDU Len different than read bytes
	d, _ = hex.DecodeString("000000178000000900000000000000016875676f00")
	n.Write(d)

	time.Sleep(100 * time.Millisecond)

	// Max PDU Len err
	d, _ = hex.DecodeString("0000F01080000015000000005222b526")
	n.Write(d)
}
Пример #15
0
//	We receive the chart script from our parent, we have to handle the data and send it to children.
func (s *Server) HandleChartTransfer(socket net.Conn) {
	file, _ := os.Create("./resources/chart.html")

	log.Println("Begginning receiving chart")

	for {
		read := make([]byte, 4096)

		n, _ := socket.Read(read)

		if sip.ExtractType(string(read[:n])) == "END" {
			break
		}

		file.Write(read[:n])

		socket.Write([]byte("INF||"))
	}

	log.Println("Done receiving chart")

	file.Close()

	for i := 0; i < s.ChildNumber; i++ {
		SendChart(s.Children[i])
	}
}
Пример #16
0
func handleClient(conn net.Conn) {
	//	defer conn.Close()
	//	daytime := time.Now().String()
	//	conn.Write([]byte(daytime))
	conn.SetReadDeadline(time.Now().Add(2 * time.Minute)) // set 2 minutes timeout
	request := make([]byte, 128)                          // set maxium request length to 128KB to prevent flood attack
	defer conn.Close()                                    // close connection before exit
	for {
		read_len, err := conn.Read(request)
		fmt.Println("read info: ", string(request))
		if err != nil {
			fmt.Println(err)
			break
		}
		fmt.Println(string(request))
		if read_len == 0 {
			break // connection already closed by client
		} else if string(request) == "timestamp" {
			fmt.Println("daytime timestamp")
			daytime := strconv.FormatInt(time.Now().Unix(), 10)
			conn.Write([]byte(daytime))
		} else {
			daytime := time.Now().String()
			conn.Write([]byte(daytime))
		}

		request = make([]byte, 128) // clear last read content
	}
}
Пример #17
0
func connectToStdio(stdin <-chan string, conn net.Conn) {
	go func() {

	}()

	buf := make([]byte, 1024)
	for {
		conn.SetReadDeadline(time.Now().Add(time.Millisecond))
		n, err := conn.Read(buf[0:])
		if err != nil {
			nerr, ok := err.(net.Error)
			if !ok || !nerr.Timeout() {
				log.Println(err)
				return
			}
		}
		os.Stdout.Write(buf[:n])

		select {
		case msg := <-stdin:
			_, err := conn.Write([]byte(msg))
			if err != nil {
				return
			}
		default:
		}
	}
}
Пример #18
0
// handles incoming requests
func handleIncomingConn(conn net.Conn, messageChannel chan *GatewayEvent) {
	defer conn.Close()

	// TODO send an initialization message (see https://github.com/Syncbak-Git/nsca/blob/master/packet.go#L163)

	// Make a buffer to hold incoming data.
	buf := make([]byte, 1024)
	// Read the incoming connection into the buffer.
	n, err := conn.Read(buf)
	if err != nil {
		Logger().Warning.Println("Error reading incoming request", err.Error())
		return
	}

	// attempt to parse the message
	if n < 1024 {
		buf = buf[:n]
	}
	message, err := parseMessage(buf)

	// continue down processing pipeline
	if err != nil {
		Logger().Warning.Println("Failed to parse message", err.Error())
		// TODO: determine how to send proper error response
		conn.Write([]byte("Message could not be processed."))
	} else {
		Logger().Trace.Printf("Processing message: %v\n", message)
		messageChannel <- newMessageEvent(message)
	}
	conn.Close()
}
Пример #19
0
func handleClient(conn net.Conn) {
	var buf [512]byte
	for {
		n, err := conn.Read(buf[0:])
		if err != nil {
			return
		}
		line := string(buf[0:n])

		//*******LOGIC*************************************************************************************
		m := map[string]string{"google.com": "8.8.8.8", "cedille.etsmtl.ca": "142.137.247.120"}

		for key, value := range m {
			// for each pair in the map, print key and value
			if line == key {
				fmt.Println(value)
			} else {
				fmt.Println("not mapped")
			}
		}
		//*******END OF LOGIC******************************************************************************
		_, err2 := conn.Write(buf[0:n])
		if err2 != nil {
			return
		}
	}
}
Пример #20
0
// This function is expected to be called as a goroutine.
// TODO: Track and log bytes copied, like TCP
func (udp *udpProxySocket) proxyClient(cliAddr net.Addr, svrConn net.Conn, activeClients *clientCache, timeout time.Duration) {
	defer svrConn.Close()
	var buffer [4096]byte
	for {
		n, err := svrConn.Read(buffer[0:])
		if err != nil {
			if !logTimeout(err) {
				glog.Errorf("Read failed: %v", err)
			}
			break
		}
		svrConn.SetDeadline(time.Now().Add(timeout))
		if err != nil {
			glog.Errorf("SetDeadline failed: %v", err)
			break
		}
		n, err = udp.WriteTo(buffer[0:n], cliAddr)
		if err != nil {
			if !logTimeout(err) {
				glog.Errorf("WriteTo failed: %v", err)
			}
			break
		}
	}
	activeClients.mu.Lock()
	delete(activeClients.clients, cliAddr.String())
	activeClients.mu.Unlock()
}
Пример #21
0
func handleRead(c net.Conn) {
	r := bufio.NewReader(c)
	for {
		length, err := getLength(r)
		if err != nil {
			log.Println(err)
			if _, isFrameErr := err.(FrameError); isFrameErr {
				// give up and continue loop
				log.Println(err)
				continue
			} else {
				return
			}
		}

		content := make([]byte, length)
		n, err := r.Read(content)

		l := 0
		if err != nil {
			log.Println(err)
		}

		for ; err == nil && n+l < len(content); l, err = c.Read(content[n:]) {
			n += l
		}

		fmt.Printf("  Reply: %s\n", content)
		fmt.Print("Enter angle: ")
	}
}
Пример #22
0
func handleCient(conn net.Conn) {
	conn.SetDeadline(time.Now().Add(2 * time.Minute))
	request := make([]byte, 128)
	defer conn.Close()

	for {
		read_len, err := conn.Read(request)

		if err != nil {
			fmt.Fprintf(os.Stderr, "error: %s", err)
			break
		}

		fmt.Printf(string(read_len))

		// if read_len == 0 {
		// 	break
		// } else if string(request) == "timestamp" {
		daytime := time.Now().String()
		conn.Write([]byte(daytime))
		// }
	}

	request = make([]byte, 128)
}
Пример #23
0
/*
 * This function is called by the main to handle the chat functionality of new connection
 * The function reads the user name and saves it, then waits for user messages and broadcast them
 */
func handleConnection(client net.Conn) {
	reader := bufio.NewReader(client)
	//receive the user name
	buff := make([]byte, 512)
	clientNameb, _ := client.Read(buff)
	clientName := string(buff[0:clientNameb])
	newSession.names = append(newSession.names, clientName)
	newSession.connections = append(newSession.connections, client)

	for {
		//receive the user message
		line, err := reader.ReadBytes('\n')
		if err != nil {
			break
		}
		//broadcast client message
		message := clientName + ":" + string(line)
		for _, currentClient := range newSession.connections {
			if currentClient != nil {
				currentClient.Write([]byte(message))
			}
		}

	}
}
Пример #24
0
//handle read and write
func handleConnection(conn net.Conn) {

	//handle read
	go func(conn net.Conn) {
		reader := bufio.NewReader(os.Stdin)
		for {
			fmt.Print(">>")
			line, _, _ := reader.ReadLine()
			conn.Write([]byte(line))
		}
	}(conn)
	//handle write
	go func(conn net.Conn) {
		bs := make([]byte, 1024)
		for {
			l, err := conn.Read(bs)
			if err != nil {
				fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
				conn.Close()
			}
			fmt.Println("<<", string(bs[:l]))
		}
	}(conn)

}
Пример #25
0
func (t *Telnet) recv(c net.Conn) (int, error) {
	buf := make([]byte, 512)

	count := 0
	for {
		err := c.SetReadDeadline(time.Now().Add(time.Millisecond * 500))
		if err != nil {
			return count, fmt.Errorf("setting read deadline: %v\n", err)
		}

		n, err := c.Read(buf)
		if err != nil {
			if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
				return count, nil
			}
			return count, fmt.Errorf("read error: %v\n", err)
		}

		for i := 0; i < n; i++ {
			if cnt := t.decodeCommand(buf[i:n]); cnt > 0 {
				i += cnt
				continue
			}

			t.debugf("%2.2x %c\n", buf[i], buf[i])
		}

		count += n

		if time.Now().After(t.deadline) {
			return count, errors.New("deadline exceeded")
		}
	}
}
Пример #26
0
func httpServer(c net.Conn) {
	buf := make([]byte, 5120)
	nr, _ := c.Read(buf)
	fmt.Println(string(buf[:nr]))
	c.Write([]byte(stdresponse))
	c.Close()
}
Пример #27
0
func handleConnection(client net.Conn) {
	defer client.Close()

	// sock version
	ver := make([]byte, 1)
	if n, _ := client.Read(ver); n != 1 {
		log.Println("MethodRequest packet is too short")
		return
	}

	var proxy SockProxy

	switch ver[0] {
	case 0x04:
		proxy = new(Sock4)
	case 0x05:
		proxy = new(Sock5)
	default:
		log.Println("invalid socks version:", ver)
		return
	}

	if err := proxy.Proxy(client); err != nil {
		log.Println("Proxy error:", err)
		return
	}

	return
}
Пример #28
0
// Receive the file in blocks
func Receive(conn net.Conn, filePath string) {
	// Defer closing the Connection handle
	defer conn.Close()

	// Open output file
	fout, err := os.Create(filePath)
	if err != nil {
		log.Println("create ", filePath, "failed...", err)
		log.Fatal(err)
	}

	// Defer closing the output file handle
	defer fout.Close()

	// File Writer Buffer init.
	w := bufio.NewWriter(fout)
	inBuffer := make([]byte, blockSize)

	for {
		numRead, err := conn.Read(inBuffer)

		if err != nil || numRead == 0 {
			log.Print("Encountered the end of file", numRead, err)
			break
		}

		numWritten, _ := w.Write(inBuffer[:numRead])

		log.Println(numRead, "bytes received", numWritten, "bytes written")
		w.Flush()
	}
}
Пример #29
-1
func connectSocksServer(socks net.Conn, domain string, port int) (err error) {
	handshakeWithSocksServer(socks)
	w := bufio.NewWriter(socks)
	//send connect command
	w.Write([]byte("\x05\x01\x00\x03"))
	w.WriteByte(byte(len(domain)))
	w.Write([]byte(domain))
	w.Write(int2nl(port))
	w.Flush()

	b := make([]byte, 256)
	socks.Read(b[:4])
	if b[0] != 5 || b[1] != 0 {
		return errors.New("cannot connect to server")
	}
	switch b[3] {
	case 1: //ipv4
		socks.Read(b[:6]) //discard the result
	case 3:
		socks.Read(b[:1])
		socks.Read(b[:b[0]+2])
	case 4:
		socks.Read(b[:16])
	}
	return
}
Пример #30
-1
func receiveConn(conn net.Conn){
	var buffer []byte
	var err error
	var n int

	// if the max length of request is 128k
	// also can use bufio.NewReader().ReadLine()
	buffer = make([]byte,128)
	for {
		n, err = conn.Read(buffer)

		// if client connection closed will happen io eof
		// other reason example network timeout will happen
		// timeout error
		if err != nil {
			if err == io.EOF {
				log.Println("[Request][EOF]:", "client disconnect")
			}
			conn.Close()
			break
		}

		if n != 0 {
			fmt.Println("[Receive]:", string(buffer))
			conn.Write(buffer)
		}else {
			conn.Write([]byte("error request"))
		}

		buffer = make([]byte, 128)    //clear buffer
	}
}