Beispiel #1
0
// NewConnection creates a SSMP connection out of a streaming netwrok connection.
//
// This method blocks until either a first message is received or a 10s timeout
// elapses.
//
// Each accepted connection spawns a goroutine continuously reading from the
// underlying network connection and triggering the Dispatcher. The caller must
// keep track of the returned Connection and call the Close method to stop the
// read goroutine and close the udnerlying netwrok connection.
//
// errInvalidLogin is returned if the first message is not a well-formed LOGIN
// request.
// errUnauthorized is returned if the authenticator doesn't accept the provided
// credentials.
func NewConnection(c net.Conn, a Authenticator, d *Dispatcher) (*Connection, error) {
	r := ssmp.NewDecoder(c)
	c.SetReadDeadline(time.Now().Add(10 * time.Second))
	verb, err := r.DecodeVerb()
	if err != nil || !ssmp.Equal(verb, ssmp.LOGIN) {
		return nil, ErrInvalidLogin
	}
	user, err := r.DecodeId()
	if err != nil {
		return nil, ErrInvalidLogin
	}
	scheme, err := r.DecodeId()
	if err != nil {
		return nil, ErrInvalidLogin
	}
	var cred []byte
	if r.AtEnd() {
		cred = []byte{}
	} else if cred, err = r.DecodePayload(); err != nil {
		return nil, ErrInvalidLogin
	}
	if !a.Auth(c, user, scheme, cred) {
		return nil, ErrUnauthorized
	}
	r.Reset()
	cc := &Connection{
		c:    c,
		r:    r,
		User: string(user),
	}
	go cc.readLoop(d)
	cc.Write(respOk)
	return cc, nil
}
Beispiel #2
0
func (p *multiplexer) connectToDest(frm *frame, key string, tun *Conn) {
	defer func() {
		ex.CatchException(recover())
	}()
	var (
		dstConn net.Conn
		err     error
		target  = string(frm.data)
	)
	dstConn, err = net.DialTimeout("tcp", target, GENERAL_SO_TIMEOUT)
	frm.length = 0
	if err != nil {
		p.router.removePreRegistered(key)
		log.Errorf("Cannot connect to [%s] for %s error: %s\n", target, key, err)
		frm.action = FRAME_ACTION_OPEN_N
		tunWrite2(tun, frm)
	} else {
		if log.V(1) {
			log.Infoln("OPEN", target, "for", key)
		}
		dstConn.SetReadDeadline(ZERO_TIME)
		edge := p.router.register(key, target, tun, dstConn, false) // write edge
		frm.action = FRAME_ACTION_OPEN_Y
		if tunWrite2(tun, frm) == nil {
			p.relay(edge, tun, frm.sid) // read edge
		} else { // send open_y failed
			SafeClose(tun)
		}
	}
}
Beispiel #3
0
func (cons *Socket) processConnection(conn net.Conn) {
	cons.AddWorker()
	defer cons.WorkerDone()
	defer conn.Close()

	buffer := shared.NewBufferedReader(socketBufferGrowSize, cons.flags, cons.offset, cons.delimiter)

	for cons.IsActive() && !cons.IsFuseBurned() {
		conn.SetReadDeadline(time.Now().Add(cons.readTimeout))
		err := buffer.ReadAll(conn, cons.Enqueue)
		if err == nil {
			if err = cons.sendAck(conn, true); err == nil {
				continue // ### continue, all is well ###
			}
		}

		// Silently exit on disconnect/close
		if !cons.IsActive() || shared.IsDisconnectedError(err) {
			return // ### return, connection closed ###
		}

		// Ignore timeout related errors
		if netErr, isNetErr := err.(net.Error); isNetErr && netErr.Timeout() {
			continue // ### return, ignore timeouts ###
		}

		Log.Error.Print("Socket transfer failed: ", err)
		cons.sendAck(conn, false)

		// Parser errors do not drop the connection
		if err != shared.BufferDataInvalid {
			return // ### return, close connections ###
		}
	}
}
Beispiel #4
0
func handleClient(conn net.Conn) {
	conn.SetReadDeadline(time.Now().Add(2 * time.Minute))
	defer conn.Close()

	b := bufio.NewReader(conn)

	for {
		status, err := b.ReadString('\n')
		if err != nil {
			if err == io.EOF {
				fmt.Println("Client Disconnected.")
			} else {
				fmt.Println(err)
			}
			break
		}

		// Clean up the input
		status = strings.Replace(status, "\r", "", -1)
		status = strings.Replace(status, "\n", "", -1)

		switch status {
		case "register":
			fmt.Println("Registered")
			conn.Write([]byte("Registered Client\n"))
			break
		default:
			break
		}
	}
}
Beispiel #5
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:
		}
	}
}
Beispiel #6
0
func ReadMessage(conn net.Conn, timeout time.Duration) (*Message, error) {
	conn.SetReadDeadline(time.Now().Add(DefaultHeartbeatTimeout))
	var lengthBuf [2]byte
	_, err := conn.Read(lengthBuf[:])
	if err != nil {
		return nil, err
	}

	length := int(binary.BigEndian.Uint16(lengthBuf[:]))
	if length > DefaultMessageLengthCap {
		return nil, errors.New("message is too long")
	}

	buf := bytes.NewBuffer(make([]byte, 0, length))
	_, err = io.CopyN(buf, conn, int64(length))
	if err != nil {
		return nil, err
	}

	var handle = &codec.MsgpackHandle{}
	var decoder = codec.NewDecoder(buf, handle)
	var result = &Message{}
	err = decoder.Decode(result)
	if err != nil {
		return nil, err
	}

	return result, nil
}
Beispiel #7
0
func handleClient(conn net.Conn) {
	conn.SetReadDeadline(time.Now().Add(2 * time.Minute))
	request := make([]byte, 128)
	defer conn.Close()
	for {
		read_len, err := conn.Read(request)
		fmt.Println(read_len)
		if err != nil {
			fmt.Println(err)
			break
		}

		if read_len == 0 {
			break
		} 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))
		}

		request = make([]byte, 128)
	}
}
Beispiel #8
0
func handleConn(conn net.Conn) {
	defer conn.Close()
	for {
		conn.SetReadDeadline(time.Now().Add(10 * time.Second))
		strReq, err := read(conn)
		if err != nil {
			if err == io.EOF {
				fmt.Println("The connection is closed by another side. (Server)")
			} else {
				fmt.Printf("Read Error: %s (Server)\n", err)
			}
			break
		}
		fmt.Printf("Received request: %s (Server)\n", strReq)

		i32Req, err := strconv.Atoi(strReq)
		if err != nil {
			n, err := write(conn, err.Error())
			if err != nil {
				fmt.Printf("Write Eoor (writen %d bytes:) %s (Server)\n", err)
			}
			fmt.Printf("Sent response (written %d bytes %s (server)\n", n, err)
			continue
		}

		f64Resp := math.Cbrt(float64(i32Req))
		respMsg := fmt.Sprintf("The cube root of %d is %f.", i32Req, f64Resp)
		n, err := write(conn, respMsg)
		if err != nil {
			fmt.Printf("Write Error: %s (Server)\n", err)
		}
		fmt.Printf("Sent response (writtn %d bytes:) %s (Server)\n", n, respMsg)
	}
}
Beispiel #9
0
// testRacyRead tests that it is safe to mutate the input Read buffer
// immediately after cancelation has occurred.
func testRacyRead(t *testing.T, c1, c2 net.Conn) {
	go chunkedCopy(c2, rand.New(rand.NewSource(0)))

	var wg sync.WaitGroup
	defer wg.Wait()

	c1.SetReadDeadline(time.Now().Add(time.Millisecond))
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()

			b1 := make([]byte, 1024)
			b2 := make([]byte, 1024)
			for j := 0; j < 100; j++ {
				_, err := c1.Read(b1)
				copy(b1, b2) // Mutate b1 to trigger potential race
				if err != nil {
					checkForTimeoutError(t, err)
					c1.SetReadDeadline(time.Now().Add(time.Millisecond))
				}
			}
		}()
	}
}
Beispiel #10
0
// ----------------------------------------------------------------------
//
//   RECEIVE LOGIC
//
// ----------------------------------------------------------------------
func conn_read(conn net.Conn, timeout time.Duration, buffer []byte) (int, error) {
	if timeout != time.Duration(0) {
		conn.SetReadDeadline(time.Now().Add(timeout))
	}

	position := 0
	length := len(buffer)

	for position < length {
		bytesRead, err := conn.Read(buffer[position:])
		if err != nil {
			if err == io.EOF {
				log.Println("conn_read", "CLOSED")
				return 0, CHANNEL_CLOSED
			} else if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
				log.Println("conn_read", "TIMEOUT")
				return 0, CHANNEL_TIMEOUT
			} else {
				// we should do better than this
				log.Println("conn_read", err)
				return 0, CHANNEL_CLOSED
			}
		} else {
			position += bytesRead
		}
	}

	return position, nil
}
Beispiel #11
0
// monitorConnection is called for bidi connections and watches for the client
// to disappear. this func blocks until the connection closes or generates a
// a non-timeout error (possibly protocol related).
func (w *Writer) monitorConnection(conn net.Conn) {
	defer close(w.finish)
	var err error
	for {
		conn.SetReadDeadline(time.Now().Add(1 * time.Second))

		// test the connection by attempting to read a FINISH control frame.
		// we should only see this if we've initiated a close by sending a
		// STOP, but it doesn't hurt to start watching for this before then
		// because we're really not expecting the client to send anything
		// else at this point. we also don't have to write anything special
		// back to the client if we receive it because the client closes their
		// end of the connection upon sending.
		_, err = w.readControl(ControlTypeFinish)
		if err == io.EOF {
			// connection closed
		} else if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
			// timeout
			time.Sleep(5 * time.Second) // TODO(jdef) extract constant
			continue
		}
		break
	}
	w.setError(err)
}
Beispiel #12
0
func NewConn(client *Client, network, addr string, connectTimeout, readTimeout, writeTimeout time.Duration) (*Conn, error) {
	client.CountNewConn++
	var conn net.Conn
	var err error
	if connectTimeout > 0 {
		conn, err = net.DialTimeout(network, addr, connectTimeout)
	} else {
		conn, err = net.Dial(network, addr)
	}
	if err != nil {
		return nil, err
	}
	if readTimeout > 0 {
		conn.SetReadDeadline(time.Now().Add(readTimeout))
	}
	if writeTimeout > 0 {
		conn.SetWriteDeadline(time.Now().Add(writeTimeout))
	}
	this := &Conn{
		Conn:         conn,
		Client:       client,
		ReadTimeout:  readTimeout,
		WriteTimeout: writeTimeout,
	}
	return this, nil
}
Beispiel #13
0
func copyBytes(dst, src net.Conn, wg *sync.WaitGroup, writeDeadline, readDeadline time.Duration) {
	defer wg.Done()
	n, err := io.Copy(dst, src)
	if err != nil {
		log.Errorf("proxy i/o error: %v", err)
	}

	if cr, ok := src.(*net.TCPConn); ok {
		cr.CloseRead()
	} else {
		// For TLS connections.
		wto := time.Now().Add(writeDeadline)
		src.SetWriteDeadline(wto)
	}

	if cw, ok := dst.(*net.TCPConn); ok {
		cw.CloseWrite()
	} else {
		// For TLS connections.
		rto := time.Now().Add(readDeadline)
		dst.SetReadDeadline(rto)
	}

	log.Debugf("proxy copied %d bytes %s -> %s", n, src.RemoteAddr(), dst.RemoteAddr())
}
Beispiel #14
0
func handleConnection(conn net.Conn) {
	defer conn.Close()
	conn.SetReadDeadline(time.Now().Add(time.Second * 3))

	r := bufio.NewReader(conn)

	size, err := r.ReadString(';')
	if err != nil {
		log.Println(err)
		fmt.Fprintf(conn, "Failed to read content length: %v\n", err)
		return
	}

	size = size[:len(size)-1]
	i, err := strconv.Atoi(size)
	if err != nil {
		log.Println(err)
		fmt.Fprintf(conn, "Failed to get content length from %s: %v\n", size, err)
		return
	}

	b := make([]byte, i)
	r.Read(b)

	intent := content.Intent{}
	if err := json.Unmarshal(b, &intent); err != nil {
		log.Println(err)
		fmt.Fprintf(conn, "Failed to decode request: %v", err)
	}

	content.Handle(conn, intent)
}
Beispiel #15
0
func (s *session) proxy(c1, c2 net.Conn) error {
	if debug {
		log.Println("Proxy", c1.RemoteAddr(), "->", c2.RemoteAddr())
	}

	atomic.AddInt64(&numProxies, 1)
	defer atomic.AddInt64(&numProxies, -1)

	buf := make([]byte, 65536)
	for {
		c1.SetReadDeadline(time.Now().Add(networkTimeout))
		n, err := c1.Read(buf)
		if err != nil {
			return err
		}

		atomic.AddInt64(&bytesProxied, int64(n))

		if debug {
			log.Printf("%d bytes from %s to %s", n, c1.RemoteAddr(), c2.RemoteAddr())
		}

		if s.rateLimit != nil {
			s.rateLimit(int64(n))
		}

		c2.SetWriteDeadline(time.Now().Add(networkTimeout))
		_, err = c2.Write(buf[:n])
		if err != nil {
			return err
		}
	}
}
Beispiel #16
0
func (mux *Mux) handleConn(conn net.Conn) error {
	// Wrap in a buffered connection in order to peek at the first byte.
	bufConn := newBufConn(conn)

	// Set a read deadline so connections with no data timeout.
	if err := conn.SetReadDeadline(time.Now().Add(mux.Timeout)); err != nil {
		return fmt.Errorf("set read deadline: %s", err)
	}

	// Peek at first byte from connection to determine handler.
	typ, err := bufConn.r.ReadByte()
	if err != nil {
		return fmt.Errorf("read header byte: %s", err)
	} else if err = bufConn.r.UnreadByte(); err != nil {
		return fmt.Errorf("unread header byte: %s", err)
	}

	// Reset read deadline and let the listener handle that.
	if err := conn.SetReadDeadline(time.Time{}); err != nil {
		return fmt.Errorf("reset set read deadline: %s", err)
	}

	// Lookup handler.
	h := mux.handlers[typ]
	if h == nil {
		return fmt.Errorf("unregistered header byte: 0x%02x", typ)
	}

	// Hand off connection to handler.
	h.c <- bufConn
	return nil
}
Beispiel #17
0
func handleConn(conn net.Conn) {
	defer func() {
		conn.Close()
		wg.Done()
	}()
	for {
		conn.SetReadDeadline(time.Now().Add(10 * time.Second))
		strReq, err := read(conn)
		if err != nil {
			if err == io.EOF {
				printLog("The connection is closed by another side. (Server)\n")
			} else {
				printLog("Read Error: %s (Server)\n", err)
			}
			break
		}
		printLog("Received request: %s (Server)\n", strReq)
		i32Req, err := convertToInt32(strReq)
		if err != nil {
			n, err := write(conn, err.Error())
			if err != nil {
				printLog("Write Error (written %d bytes): %s (Server)\n", err)
			}
			printLog("Sent response (written %d bytes): %s (Server)\n", n, err)
			continue
		}
		f64Resp := cbrt(i32Req)
		respMsg := fmt.Sprintf("The cube root of %d is %f.", i32Req, f64Resp)
		n, err := write(conn, respMsg)
		if err != nil {
			printLog("Write Error: %s (Server)\n", err)
		}
		printLog("Sent response (written %d bytes): %s (Server)\n", n, respMsg)
	}
}
Beispiel #18
0
func DefaultDial(proto, realm string) (io.ReadWriteCloser, error) {
	if proto != "tcp" && proto != "udp" {
		return nil, ErrInvalidProto(proto)
	}

	_, addrs, err := net.LookupSRV("kerberos", proto, realm)

	if err != nil {
		_, addrs, err = net.LookupSRV("kerberos-master", proto, realm)
		if err != nil {
			return nil, err
		}
	}

	var sock net.Conn

	for _, a := range addrs {
		addr := net.JoinHostPort(a.Target, strconv.Itoa(int(a.Port)))
		sock, err = net.Dial(proto, addr)
		if err == nil {
			break
		}
	}

	if err != nil {
		return nil, err
	}

	if proto == "udp" {
		// For datagram connections, we retry up to three times, then give up
		sock.SetReadDeadline(time.Now().Add(udpReadTimeout))
	}

	return sock, nil
}
Beispiel #19
0
func (rcv *TCP) handleConnection(conn net.Conn) {
	atomic.AddInt32(&rcv.active, 1)
	defer atomic.AddInt32(&rcv.active, -1)

	defer conn.Close()
	reader := bufio.NewReader(conn)

	for {
		conn.SetReadDeadline(time.Now().Add(2 * time.Minute))

		line, err := reader.ReadBytes('\n')

		if err != nil {
			if err == io.EOF {
				if len(line) > 0 {
					logrus.Warningf("[tcp] Unfinished line: %#v", line)
				}
			} else {
				atomic.AddUint32(&rcv.errors, 1)
				logrus.Error(err)
			}
			break
		}
		if len(line) > 0 { // skip empty lines
			if msg, err := points.ParseText(string(line)); err != nil {
				atomic.AddUint32(&rcv.errors, 1)
				logrus.Info(err)
			} else {
				atomic.AddUint32(&rcv.metricsReceived, 1)
				rcv.out <- msg
			}
		}
	}
}
Beispiel #20
0
// poll sends a packet and wait for a response. Both operations can timeout, they're retried up to retries times.
func poll(conn net.Conn, toSend []byte, respondBuffer []byte, retries int, timeout time.Duration) (int, error) {
	var err error
	for i := 0; i < retries+1; i++ {
		deadline := time.Now().Add(timeout)

		if err = conn.SetWriteDeadline(deadline); err != nil {
			log.Printf("Couldn't set write deadline. Retrying. Retry %d/%d\n", i, retries)
			continue
		}
		if _, err = conn.Write(toSend); err != nil {
			log.Printf("Couldn't write. Retrying. Retry %d/%d\n", i, retries)
			continue
		}

		deadline = time.Now().Add(timeout)
		if err = conn.SetReadDeadline(deadline); err != nil {
			log.Printf("Couldn't set read deadline. Retrying. Retry %d/%d\n", i, retries)
			continue
		}

		numRead := 0
		if numRead, err = conn.Read(respondBuffer); err != nil {
			log.Printf("Couldn't read. Retrying. Retry %d/%d\n", i, retries)
			continue
		}

		return numRead, nil
	}
	return 0, err
}
Beispiel #21
0
func slurp(conn net.Conn, maxbytes int, timeout float64) ([]byte, error) {
	buf := []byte{}
	readLimit := 32 * 1024
	if maxbytes > 0 {
		readLimit = maxbytes
	}
	readBytes := 0
	if timeout > 0 {
		conn.SetReadDeadline(time.Now().Add(time.Duration(timeout) * time.Second))
	}
	for {
		tmpBuf := make([]byte, readLimit)
		i, err := conn.Read(tmpBuf)
		if i > 0 {
			buf = append(buf, tmpBuf[:i]...)
			readBytes += i
			if i < readLimit || (maxbytes > 0 && maxbytes <= readBytes) {
				break
			}
		}
		if err == io.EOF {
			return buf, nil
		}
		if err != nil {
			return buf, err
		}
	}
	return buf, nil
}
Beispiel #22
0
func (srv *Server) readTCP(conn net.Conn, 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 := binary.BigEndian.Uint16(l)
	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
}
Beispiel #23
0
func handleConn(conn net.Conn) {
	defer conn.Close()

	// Read from connection
	buf := make([]byte, 512)
	conn.SetReadDeadline(time.Now().Add(TIMEOUT))
	n, err := conn.Read(buf)
	if err != nil {
		return
	}

	// Unmarshal message
	msg := Message{}
	err = json.Unmarshal(buf[:n], &msg)

	// Handle message
	switch msg.Type {
	case MSG_VOTE:
		fmt.Printf("%d: Got vote message.\n", id)
		go announceVote()
		fallthrough
	case MSG_PING:
		fmt.Printf("%d: Sending 'alive' message.\n", id)
		response := Message{Type: MSG_ALIVE, Sender: id}
		conn.Write(response.ToJSON())
	case MSG_LEADER:
		if msg.Sender > id {
			setLeader(msg.Sender)
		} else {
			fmt.Printf("%d: Leader with lower ID. Bullying!\n", id)
			go announceVote()
		}
	}

}
Beispiel #24
0
func (srv *Server) sentinel(c net.Conn, connClosed chan int) {
	select {
	case <-srv.stopAccepting:
		c.SetReadDeadline(time.Now().Add(3 * time.Second))
	case <-connClosed:
	}
}
Beispiel #25
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
	}
}
Beispiel #26
0
func (mux *Mux) handleConn(conn net.Conn) {
	defer mux.wg.Done()
	// Set a read deadline so connections with no data don't timeout.
	if err := conn.SetReadDeadline(time.Now().Add(mux.Timeout)); err != nil {
		conn.Close()
		mux.Logger.Printf("tcp.Mux: cannot set read deadline: %s", err)
		return
	}

	// Read first byte from connection to determine handler.
	var typ [1]byte
	if _, err := io.ReadFull(conn, typ[:]); err != nil {
		conn.Close()
		mux.Logger.Printf("tcp.Mux: cannot read header byte: %s", err)
		return
	}

	// Reset read deadline and let the listener handle that.
	if err := conn.SetReadDeadline(time.Time{}); err != nil {
		conn.Close()
		mux.Logger.Printf("tcp.Mux: cannot reset set read deadline: %s", err)
		return
	}

	// Retrieve handler based on first byte.
	handler := mux.m[typ[0]]
	if handler == nil {
		conn.Close()
		mux.Logger.Printf("tcp.Mux: handler not registered: %d", typ[0])
		return
	}

	// Send connection to handler.  The handler is responsible for closing the connection.
	handler.c <- conn
}
Beispiel #27
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))
		}

	}
}
Beispiel #28
0
func (s *Server) handle(clientConn net.Conn, id int) {
	log.Debug("[tcpez] New client(%s)", clientConn.RemoteAddr())
	s.clientConns[id] = clientConn
	for {
		// Timeout the connection after 5 mins
		clientConn.SetReadDeadline(time.Now().Add(5 * time.Minute))
		header, response, err := s.readHeaderAndHandleRequest(clientConn)
		if err != nil {
			if closableError(err) {
				// EOF the client has disconnected
				break
			}
			log.Error(err.Error())
			s.Stats.Increment("operation.failure")
			return
		}
		err = s.sendResponse(clientConn, header, response)
		if err != nil {
			if closableError(err) {
				// EOF the client has disconnected
				break
			}
			log.Error(err.Error())
			s.Stats.Increment("operation.failure")
			return
		}
		s.Stats.Increment("operation.success")
	}
	log.Debug("Closing connection %v", clientConn)
	clientConn.Close()
	delete(s.clientConns, id)
}
Beispiel #29
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")
		}
	}
}
Beispiel #30
0
func SockRead(con net.Conn, buf []byte) (n int, e error) {
	var toread int
	bw_mutex.Lock()
	TickRecv()
	if DownloadLimit == 0 {
		toread = len(buf)
	} else {
		toread = int(DownloadLimit) - dl_bytes_so_far
		if toread > len(buf) {
			toread = len(buf)
		} else if toread < 0 {
			toread = 0
		}
	}
	dl_bytes_so_far += toread
	bw_mutex.Unlock()

	if toread > 0 {
		// Wait 1 millisecond for a data, timeout if nothing there
		con.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
		n, e = con.Read(buf[:toread])
		bw_mutex.Lock()
		DlBytesTotal += uint64(n)
		dl_bytes_priod += uint64(n)
		bw_mutex.Unlock()
	} else {
		// supsend a task for awhile, to prevent stucking in a busy loop
		time.Sleep(100 * time.Millisecond)
	}
	return
}