Ejemplo n.º 1
0
func handleConnection(conn *net.TCPConn) error {
	defer conn.Close()

	handlerChan <- 1
	defer func() {
		handlerChan <- -1
	}()

	var ws *websocket.Conn

	conn.SetDeadline(time.Now().Add(socksTimeout))
	err := AwaitSocks4aConnect(conn, func(dest string) (*net.TCPAddr, error) {
		// Disable deadline.
		conn.SetDeadline(time.Time{})
		Log("SOCKS request for %s", dest)
		destAddr, err := net.ResolveTCPAddr("tcp", dest)
		if err != nil {
			return nil, err
		}
		wsUrl := url.URL{Scheme: "ws", Host: dest}
		ws, err = websocket.Dial(wsUrl.String(), "", wsUrl.String())
		if err != nil {
			return nil, err
		}
		Log("WebSocket connection to %s", ws.Config().Location.String())
		return destAddr, nil
	})
	if err != nil {
		return err
	}
	defer ws.Close()
	proxy(conn, ws)
	return nil
}
Ejemplo n.º 2
0
Archivo: send.go Proyecto: zoglee/netty
func send(tcpconn *net.TCPConn, rsp *Response) (err error) {
	Len := uint32(PkgLenSize) + uint32(len(rsp.Head)) + uint32(len(rsp.Body))
	Hlen := uint16(Uint16Size) + uint16(len(rsp.Head))
	data := make([]byte, 0, int(Len)) // len:0, cap:Len; TODO(zog): cache
	buf := bytes.NewBuffer(data)      // TODO(zog): 复用
	binary.Write(buf, binary.BigEndian, Len)
	binary.Write(buf, binary.BigEndian, Hlen)
	buf.Write(rsp.Head)
	buf.Write(rsp.Body)
	if debug {
		glog.Infof("sent bytes to %s, len: %d",
			tcpconn.RemoteAddr().String(), len(buf.Bytes()))
		glog.Flush()
	}

	tcpconn.SetDeadline(time.Now().Add(100 * time.Millisecond))
	if _, err = tcpconn.Write(buf.Bytes()); err != nil {
		return err
	}

	if debug {
		glog.Infof("sent data(len:%d): %v", buf.Len(), buf.Bytes())
		glog.Flush()
	}

	return nil
}
Ejemplo n.º 3
0
func newRCConn(c *net.TCPConn, iface *Interface) (*RCConn, error) {
	// Leave enough room in the completion queue for any operation,
	// including inline sends, to return an error. CQ overruns
	// sometimes cause internal errors in the HCA, which can make the
	// kernel very unhappy.
	qp, err := iface.NewQueuePair(10)
	if err != nil {
		return nil, err
	}

	if err := c.SetDeadline(ioDeadline()); err != nil {
		checkClose(qp)
		return nil, err
	}
	destLid, destQpn, destPsn, err := writeReadQPParams(c, iface.Lid(), qp.Qpn(), qp.Psn())
	if err != nil {
		checkClose(qp)
		return nil, err
	}

	messages, meta := CreateBuffers()

	if err := qp.Setup(destLid, destQpn, destPsn, messages); err != nil {
		checkClose(qp)
		return nil, err
	}

	laddr, raddr := c.LocalAddr(), c.RemoteAddr()

	rcc := &RCConn{iface, laddr, raddr, qp, math.MaxInt64, true, messages, meta, false}
	return rcc, nil
}
Ejemplo n.º 4
0
func recv(uid int64, gid int64, conn *net.TCPConn) {
	seq := 1

	n := count * (concurrent)
	total := n
	for i := 0; i < n; i++ {
		conn.SetDeadline(time.Now().Add(40 * time.Second))
		msg := ReceiveMessage(conn)
		if msg == nil {
			log.Println("receive nill message")
			total = i
			break
		}

		if msg.cmd != MSG_GROUP_IM {
			log.Println("mmmmmm:", Command(msg.cmd))
			i--
		}

		if msg.cmd == MSG_GROUP_IM {
			//m := msg.body.(*IMMessage)
			//log.Printf("sender:%d receiver:%d content:%s", m.sender, m.receiver, m.content)
		}
		seq++
		ack := &Message{MSG_ACK, seq, DEFAULT_VERSION, &MessageACK{int32(msg.seq)}}
		SendMessage(conn, ack)
	}
	log.Printf("%d received:%d", uid, total)
	c <- true
}
Ejemplo n.º 5
0
func (t *TCPProxy) dialToPipe(ctx context.Context, client *net.TCPConn) {
	svConn, err := t.openSvConn()
	if err != nil {
		log.Println(err)
		closeConn(client)
		return
	}
	deadline := time.Now().Add(t.PipeDeadLine)
	printErr(log.Println, svConn.SetDeadline(deadline))
	printErr(log.Println, client.SetDeadline(deadline))
	errSv2Cl := pipe(client, svConn)
	errCl2Sv := pipe(svConn, client)
	select {
	case err = <-errCl2Sv:
	case err = <-errSv2Cl:
	case <-ctx.Done():
	}
	if err != nil && err != io.EOF {
		log.Printf("pipe err:%s addr:%s", err, t.DialAddr)
	}
	closeConn(client)
	closeConn(svConn)

	//残ったメッセージを読み捨てる
	for range errCl2Sv {
	}
	for range errSv2Cl {
	}
}
Ejemplo n.º 6
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)
		}
	}
}
Ejemplo n.º 7
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
}
Ejemplo n.º 8
0
func handleConn(conn *net.TCPConn, resp responses) {
	defer conn.Close()

	p := &peerState{}
	p.ipPort = ipPort(conn.RemoteAddr().String())
	for {

		conn.SetDeadline(time.Now().Add(connectionTimeout))
		m, err := readMessage(conn)
		if err != nil {
			log.Println("handleConn:", err)
			resp.delNodeChan <- p.ipPort.toNetworkAddress()
			return
		}

		command := m.h.command
		log.Printf("got command: %v", command)
		switch command {

		case "version":
			err = handleVersion(conn, p, m, resp.addNodeChan)
		case "addr":
			err = handleAddr(conn, p, m, resp.addrsChan)
		case "verack":
			err = handleVerack(conn, p, resp.addNodeChan)
		case "inv":
			err = handleInv(conn, p, m, resp.invChan)
		case "msg":
			err = handleMsg(conn, p, m, resp.msgChan)
		case "broadcast":
			err = handleBroadcast(conn, p, m, resp.broadcastChan)
		default:
			// XXX
			err = fmt.Errorf("ignoring unknown command %q", command)
			log.Println(err.Error())
			err = nil
		}

		// The handler functions must be able to run concurrenly, so don't use
		// m after calling the functions above.

		if err != nil {
			log.Printf("error while processing command %v: %v", command, err)
			resp.delNodeChan <- ipPort(conn.RemoteAddr().String()).toNetworkAddress()
			// Disconnects from node.
			return
		}
	}
}
Ejemplo n.º 9
0
func (s *Service) serve(conn *net.TCPConn) {
	defer conn.Close()
	defer s.waitGroup.Done()
	for {
		select {
		case <-s.ch:
			return
		default:
		}
		conn.SetDeadline(time.Now().Add(1e9))
		buf := make([]byte, 4096)
		readCount, err := conn.Read(buf)
		if err != nil {
			break
		}
		s.receivedChan <- buf[:readCount]
	}
}
Ejemplo n.º 10
0
// readDiamondMetrics reads from the connection
func (d Diamond) readDiamondMetrics(conn *net.TCPConn) {
	defer conn.Close()
	conn.SetKeepAlive(true)
	conn.SetKeepAlivePeriod(time.Second)
	reader := bufio.NewReader(conn)
	log.Info("Diamond collector connection started: ", conn.RemoteAddr())
	for {
		// TODO: verify that timeout is actually working.
		conn.SetDeadline(time.Now().Add(1e9))
		line, err := reader.ReadBytes('\n')
		if err != nil {
			break
		}
		log.Debug("Read from Diamond collector: ", string(line))
		d.incoming <- line
	}
	log.Info("Diamond collector connection closed: ", conn.RemoteAddr())
}
Ejemplo n.º 11
0
Archivo: recv.go Proyecto: zoglee/netty
func recv(tcpconn *net.TCPConn) (req *Request, err error) {
	// TODO(zog): 用 bytes.Buffer 优化
	var Len uint32
	var Hlen uint16

	tcpconn.SetDeadline(time.Now().Add(100 * time.Millisecond)) // TODO(zog): is 100ms good?
	if err = binary.Read(tcpconn, binary.BigEndian, &Len); err != nil {
		return nil, err
	}
	if int(Len) < MinAllowedPkgLen || int(Len) > MaxAllowedPkgLen {
		err = fmt.Errorf("invalid package len: Len=%d(min:%d, max:%d)",
			Len, MinAllowedPkgLen, MaxAllowedPkgLen)
		return nil, err
	}

	data := make([]byte, int(Len)-Uint32Size) // TODO(zog): cache

	tcpconn.SetDeadline(time.Now().Add(100 * time.Millisecond))
	if n, rerr := io.ReadFull(tcpconn, data); err != nil {
		err = fmt.Errorf("read package data n:%d(expect:%d), err: %s",
			n, len(data), rerr)
		return nil, err
	}

	Hlen = (uint16(data[1]) | uint16(data[0])<<8)
	if (int(Hlen) < MinAllowedPkgTotalHeadLen) ||
		(int(Hlen) > MaxAllowedPkgTotalHeadLen) ||
		(int(Hlen) > len(data)-MinAllowedPkgBodyLen) {
		err = fmt.Errorf("invalid Hlen: %d, (min:%d, max:%d), over expect max: %d",
			Hlen, MinAllowedPkgTotalHeadLen, MaxAllowedPkgTotalHeadLen, len(data))
		return nil, err
	}

	if debug {
		glog.Infof("Len:%d, Hlen:%d, len(data):%d, data:%v",
			Len, Hlen, len(data), data)
		glog.Flush()
	}

	return &Request{
		Head: data[2 : 2+(Hlen-2)],
		Body: data[2+(Hlen-2):],
	}, nil
}
Ejemplo n.º 12
0
func (t *TCPInput) receiveMessages(conn *net.TCPConn, messageReader rowmessage.MessageReader) {
	errCount := 0
	msgCount := 0
	defer conn.Close()
	defer func() {
		log.Printf("TCPInput.receiveMessages: total=%d", msgCount)
	}()

	for {
		conn.SetDeadline(time.Now().Add(TCPInputTimeout))
		msg, err := messageReader.ReadMsg()
		if err != nil {
			if err == io.EOF {
				log.Printf("TCPInput.receiveMessages: EOF!")
				return
			}

			netErr, ok := err.(net.Error)
			if ok {
				if netErr.Timeout() && !netErr.Temporary() {
					log.Printf("TCPInput.receiveMessages: timeout conn=%v", conn)
					return
				}
				errCount++
				if errCount > TCPMaxErrors {
					log.Printf("TCPInput.receiveMessages: max errors reached err=%s", msg, err)
					return
				}
			}

			log.Printf("TCPInput.receiveMessages: error=%s", err)
			continue
		}
		errCount = 0
		// log.Printf("TCPInput.receiveMessages: msg=%v err=%s", msg, err)
		t.messages <- msg
		msgCount++
	}
}
Ejemplo n.º 13
0
func connectionHandler(conn *net.TCPConn, out chan *oakmole.Record) {
	defer conn.Close()
	timeBegin := time.Now()
	conn.SetKeepAlive(false)
	conn.SetLinger(0)
	conn.SetDeadline(timeBegin.Add(IOTimeout))

	addrLocal := conn.LocalAddr().(*net.TCPAddr)
	addrRemote := conn.RemoteAddr().(*net.TCPAddr)

	log.Println("New connection from", addrRemote)

	// TODO: reuse existing buffers
	buffer := make([]byte, ReadBufferSize)
	var httpRequest *http.Request
	totalSize := 0
	for i := 1; i <= 3 && totalSize < ReadBufferSize; i++ {
		size, err := conn.Read(buffer[totalSize:])
		totalSize += size
		if err == io.EOF {
			break
		}

		if err != nil {
			// Only log IO timeout on first Read().
			// Later it just means that client already sent everything.
			if netErr, ok := err.(net.Error); i == 1 || !ok || !netErr.Timeout() {
				log.Println("Read: try:", i, "local:", addrLocal, "remote:", addrRemote, "error:", err)
			}
			if i == 1 {
				return
			}
			break
		}

		// Try to parse HTTP request.
		// This allows to stop reading from socket early.
		// TODO: reuse existing bufio.Reader
		bufReader := bufio.NewReader(bytes.NewReader(buffer))
		httpRequest, err = http.ReadRequest(bufReader)
		httpRequest.Body.Close()
		if err == nil {
			break
		} else {
			httpRequest = nil
		}
	}
	buffer = buffer[:totalSize]

	record := &oakmole.Record{
		Timestamp: uint64(timeBegin.UnixNano() / 1000),
		LocalIP:   addrLocal.IP,
		RemoteIP:  addrRemote.IP,
		Body:      buffer,
	}
	if httpRequest != nil {
		record.HttpHost = []byte(httpRequest.Host)
	} else {
		record.HttpHost = readHost(buffer)
	}
	// log.Println("Read: success local:", addrLocal, "remote:", addrRemote, "size:", totalSize, "first bytes:", string(buffer[:20]))

	// t1 := time.Now()
	out <- record
	// outSendTime := time.Now().Sub(t1)
	// log.Println("connectionHandler: out<- time:", outSendTime)

	if httpRequest != nil && httpRequest.Method == "GET" && httpRequest.RequestURI == "/robots.txt" {
		conn.Write(robotsDisallowBytes)
	}
}
Ejemplo n.º 14
0
func send(uid int64, gid int64, conn *net.TCPConn) {
	ack_c := make(chan int, 100)
	close_c := make(chan bool)

	seq := 1

	go func() {
		c := count * (concurrent - 1)
		total := c
		for i := 0; i < c; i++ {
			conn.SetDeadline(time.Now().Add(40 * time.Second))
			msg := ReceiveMessage(conn)
			if msg == nil {
				log.Println("receive nill message")
				total = i
				break
			}

			if msg.cmd == MSG_ACK {
				i--
				ack_c <- 0
				continue
			}

			if msg.cmd != MSG_GROUP_IM {
				log.Println("mmmmmm:", Command(msg.cmd))
				i--
			}

			if msg.cmd == MSG_GROUP_IM {
				//m := msg.body.(*IMMessage)
				//log.Printf("sender:%d receiver:%d content:%s", m.sender, m.receiver, m.content)
			}
			seq++
			ack := &Message{MSG_ACK, seq, DEFAULT_VERSION, &MessageACK{int32(msg.seq)}}
			SendMessage(conn, ack)
		}
		log.Printf("%d received:%d", uid, total)
		close(close_c)
	}()

	for i := 0; i < count; i++ {
		content := fmt.Sprintf("test....%d", i)
		seq++
		msg := &Message{MSG_GROUP_IM, seq, DEFAULT_VERSION, &IMMessage{uid, gid, 0, int32(i), content}}
		SendMessage(conn, msg)
		var e bool
		select {
		case <-ack_c:
		case <-close_c:
			for {
				ack := ReceiveMessage(conn)
				if ack == nil {
					e = true
					break
				}
				if ack.cmd == MSG_ACK {
					break
				}
			}
		}
		if e {
			break
		}
	}

	<-close_c

	conn.Close()
	log.Printf("%d send complete", uid)
	c <- true
}
Ejemplo n.º 15
0
func CheckStatusOldConn(conn *net.TCPConn, host string, port uint16) (*MinecraftStatus, time.Duration, error) {
	buff := &bytes.Buffer{}
	buff.Grow(512)
	buff.Write([]byte{0xFE, 0x01, 0xFA})
	buff.Write(pack_utf16be("MC|PingHost"))
	hostpacked := pack_utf16be(host)
	binary.Write(buff, binary.BigEndian, int16(len(hostpacked)+5)) // host + uint8 protocol + int32 port
	binary.Write(buff, binary.BigEndian, uint8(LAST_OLD_PROTOCOL))
	buff.Write(hostpacked)
	binary.Write(buff, binary.BigEndian, int32(port))

	conn.SetDeadline(time.Now().Add(DEADLINE))
	_, err := conn.Write(buff.Bytes())
	if err != nil {
		return nil, 0, fmt.Errorf("CheckStatusOld error sending: %s", err)
	}

	t1 := time.Now()

	var c [1]byte
	_, err = conn.Read(c[:])
	if err != nil {
		return nil, 0, fmt.Errorf("CheckStatusOld error reading packet id: %s", err)
	}
	if c[0] != 0xFF {
		return nil, 0, fmt.Errorf("CheckStatusOld bad response packet id: %d", c[0])
	}
	msg, err := read_utf16be(conn, 512)
	if err != nil {
		return nil, 0, fmt.Errorf("CheckStatusOld error reading response string: %s", err)
	}

	// TODO: zastanowic sie czy nie lepiej uzyc fmt.Sscanf
	status := &MinecraftStatus{}
	if strings.HasPrefix(msg, "§1") { // 1.4 +
		params := strings.Split(msg, "\x00")
		if len(params) != 6 {
			return nil, 0, fmt.Errorf("CheckStatusOld bad param count %d (1)", len(params))
		}
		status.ProtocolVersion, err = strconv.Atoi(params[1])
		if err != nil {
			return nil, 0, fmt.Errorf("CheckStatusOld error converting protocol version")
		}
		status.GameVersion = params[2]
		status.Description = params[3]
		status.Players, err = strconv.Atoi(params[4])
		if err != nil {
			return nil, 0, fmt.Errorf("CheckStatusOld error converting player count")
		}
		status.Slots, err = strconv.Atoi(params[5])
		if err != nil {
			return nil, 0, fmt.Errorf("CheckStatusOld error converting slot count")
		}

	} else { // < 1.4
		params := strings.Split(msg, "§")
		if len(params) != 3 {
			return nil, 0, fmt.Errorf("CheckStatusOld bad param count %d (2)", len(params))
		}
		// last protocol and game version with this response format
		status.ProtocolVersion = 39
		status.GameVersion = "1.3.1"
		status.Description = params[0]
		status.Players, err = strconv.Atoi(params[1])
		if err != nil {
			return nil, 0, fmt.Errorf("CheckStatusOld error converting player count")
		}
		status.Slots, err = strconv.Atoi(params[2])
		if err != nil {
			return nil, 0, fmt.Errorf("CheckStatusOld error converting slot count")
		}
	}

	return status, time.Since(t1), nil
}
Ejemplo n.º 16
0
func (s *StratumServer) setDeadline(conn *net.TCPConn) {
	conn.SetDeadline(time.Now().Add(s.timeout))
}
Ejemplo n.º 17
0
// handleConn handles a single incoming TCP connection
func (m *Memberlist) handleConn(conn *net.TCPConn) {
	m.logger.Printf("[DEBUG] memberlist: TCP connection %s", LogConn(conn))

	defer conn.Close()
	metrics.IncrCounter([]string{"memberlist", "tcp", "accept"}, 1)

	conn.SetDeadline(time.Now().Add(m.config.TCPTimeout))
	msgType, bufConn, dec, err := m.readTCP(conn)
	if err != nil {
		if err != io.EOF {
			m.logger.Printf("[ERR] memberlist: failed to receive: %s %s", err, LogConn(conn))
		}
		return
	}

	switch msgType {
	case userMsg:
		if err := m.readUserMsg(bufConn, dec); err != nil {
			m.logger.Printf("[ERR] memberlist: Failed to receive user message: %s %s", err, LogConn(conn))
		}
	case pushPullMsg:
		join, remoteNodes, userState, err := m.readRemoteState(bufConn, dec)
		if err != nil {
			m.logger.Printf("[ERR] memberlist: Failed to read remote state: %s %s", err, LogConn(conn))
			return
		}

		if err := m.sendLocalState(conn, join); err != nil {
			m.logger.Printf("[ERR] memberlist: Failed to push local state: %s %s", err, LogConn(conn))
			return
		}

		if err := m.mergeRemoteState(join, remoteNodes, userState); err != nil {
			m.logger.Printf("[ERR] memberlist: Failed push/pull merge: %s %s", err, LogConn(conn))
			return
		}
	case pingMsg:
		var p ping
		if err := dec.Decode(&p); err != nil {
			m.logger.Printf("[ERR] memberlist: Failed to decode TCP ping: %s %s", err, LogConn(conn))
			return
		}

		if p.Node != "" && p.Node != m.config.Name {
			m.logger.Printf("[WARN] memberlist: Got ping for unexpected node %s %s", p.Node, LogConn(conn))
			return
		}

		ack := ackResp{p.SeqNo, nil}
		out, err := encode(ackRespMsg, &ack)
		if err != nil {
			m.logger.Printf("[ERR] memberlist: Failed to encode TCP ack: %s", err)
			return
		}

		err = m.rawSendMsgTCP(conn, out.Bytes())
		if err != nil {
			m.logger.Printf("[ERR] memberlist: Failed to send TCP ack: %s %s", err, LogConn(conn))
			return
		}
	default:
		m.logger.Printf("[ERR] memberlist: Received invalid msgType (%d) %s", msgType, LogConn(conn))
	}
}
Ejemplo n.º 18
0
// handle connection
func (self *Server) HandleConn(conn *net.TCPConn) {
	r := bufio.NewReader(conn)
	TTL := self.Conf["ttl"].(float64)
	self.extendTTL(conn, TTL)
	for {
		b, err := r.ReadBytes('\n')
		if err == io.EOF {
			break
		} else if err != nil {
			self.closeConn(conn)
			return
		} else {
			self.extendTTL(conn, TTL)
		}
		args := bytes.Split(bytes.ToLower(bytes.TrimRight(b, "\r\n")), []byte(" "))
		switch string(args[0]) {
		case "ping":
			conn.Write([]byte("PONG\r\n"))
			break
		case "set":
			if len(args[1:]) == 2 {
				ok := self.Store.Set(string(args[1]), args[2])
				conn.Write([]byte(boolToString(ok) + "\r\n"))
			}
			break
		case "app":
			if len(args[1:]) >= 2 {
				ok := self.Store.App(string(args[1]), args[2:]...)
				conn.Write([]byte(boolToString(ok) + "\r\n"))
			}
			break
		case "get":
			if len(args[1:]) == 1 {
				v := self.Store.Get(string(args[1]))
				v = append(v, []byte("\r\n"))
				conn.Write(bytes.Join(v, []byte(" ")))
			}
			break
		case "del":
			if len(args[1:]) == 1 {
				ok := self.Store.Del(string(args[1]))
				conn.Write([]byte(boolToString(ok) + "\r\n"))
			}
			break
		case "exp":
			if len(args[1:]) == 2 {
				n, _ := strconv.Atoi(string(args[2]))
				ok := self.Store.Exp(string(args[1]), int64(n))
				conn.Write([]byte(boolToString(ok) + "\r\n"))
			}
			break
		case "ttl":
			if len(args[1:]) == 1 {
				v := self.Store.TTL(string(args[1]))
				n := strconv.Itoa(v)
				conn.Write([]byte(n + "\r\n"))
			}
			break
		case "haskey":
			if len(args[1:]) == 1 {
				ok := self.Store.HasKey(string(args[1]))
				conn.Write([]byte(boolToString(ok) + "\r\n"))
			}
			break
		case "getval":
			if len(args[1:]) >= 2 {
				var ns []int
				for i := 2; i < len(args[2:]); i++ {
					n, _ := strconv.Atoi(string(args[i]))
					ns = append(ns, n)
				}
				v := self.Store.GetVal(string(args[1]), ns...)
				v = append(v, []byte("\r\n"))
				conn.Write(bytes.Join(v, []byte(" ")))
			}
			break
		case "delval":
			if len(args[1:]) == 2 {
				ok := self.Store.DelVal(string(args[1]), args[2])
				conn.Write([]byte(boolToString(ok) + "\r\n"))
			}
			break
		case "save":
			if len(args[1:]) == 1 {
				ok := self.Store.SaveSnapshot(string(args[1]))
				conn.Write([]byte(boolToString(ok) + "\r\n"))
			}
			break
		case "load":
			if len(args[1:]) == 1 {
				ok := self.Store.LoadSnapshot(string(args[1]))
				conn.Write([]byte(boolToString(ok) + "\r\n"))
			}
			break
		case "purge":
			ok := self.Store.Purge()
			conn.Write([]byte(boolToString(ok) + "\r\n"))
			break
		case "exit":
			conn.SetDeadline(time.Now())
			break
		}
	}
}
Ejemplo n.º 19
0
// extend conn ttl
func (self *Server) extendTTL(conn *net.TCPConn, ttl float64) {
	if ttl > 0 {
		conn.SetDeadline(time.Now().Add(time.Duration(ttl) * time.Second))
	}
}
Ejemplo n.º 20
0
func (service *TcpService) ServeTCP(conn *net.TCPConn) (err error) {
	if service.keepAlive != nil {
		if err = conn.SetKeepAlive(service.keepAlive.(bool)); err != nil {
			return err
		}
	}
	if service.keepAlivePeriod != nil {
		if kap, ok := (net.Conn(conn)).(iKeepAlivePeriod); ok {
			if err = kap.SetKeepAlivePeriod(service.keepAlivePeriod.(time.Duration)); err != nil {
				return err
			}
		}
	}
	if service.linger != nil {
		if err = conn.SetLinger(service.linger.(int)); err != nil {
			return err
		}
	}
	if service.noDelay != nil {
		if err = conn.SetNoDelay(service.noDelay.(bool)); err != nil {
			return err
		}
	}
	if service.readBuffer != nil {
		if err = conn.SetReadBuffer(service.readBuffer.(int)); err != nil {
			return err
		}
	}
	if service.writeBuffer != nil {
		if err = conn.SetWriteBuffer(service.writeBuffer.(int)); err != nil {
			return err
		}
	}
	if service.timeout != nil {
		if err = conn.SetDeadline(time.Now().Add(service.timeout.(time.Duration))); err != nil {
			return err
		}
	}
	go func(conn net.Conn) {
		if service.config != nil {
			tlsConn := tls.Server(conn, service.config)
			tlsConn.Handshake()
			conn = tlsConn
		}
		var data []byte
		var err error
		for {
			if service.readTimeout != nil {
				err = conn.SetReadDeadline(time.Now().Add(service.readTimeout.(time.Duration)))
			}
			if err == nil {
				data, err = receiveDataOverTcp(conn)
			}
			if err == nil {
				data = service.Handle(data, conn)
				if service.writeTimeout != nil {
					err = conn.SetWriteDeadline(time.Now().Add(service.writeTimeout.(time.Duration)))
				}
				if err == nil {
					err = sendDataOverTcp(conn, data)
				}
			}
			if err != nil {
				conn.Close()
				break
			}
		}
	}(conn)
	return nil
}
Ejemplo n.º 21
0
func handleClient(conn *net.TCPConn) {
	success := false
	defer func() {
		if !success {
			conn.Close()
			fmt.Printf("Closed client conn.\n")
		}
	}()

	err := conn.SetDeadline(time.Now().Add(1 * time.Second))
	if err != nil {
		fmt.Printf("Error setting deadling on client conn.\n")
		return
	}
	w := bufio.NewReader(conn)
	line, err := w.ReadString('\n')
	if err != nil {
		fmt.Printf("Error reading from player: %v\n", err)
		return
	}
	name := strings.TrimSpace(line)
	game := getGame(name)
	active_games_mutex.Lock()
	fmt.Printf("%d active games:\n", len(active_games))
	for name := range active_games {
		fmt.Printf("%s\n", name)
	}
	active_games_mutex.Unlock()
	if game == nil {
		err_msg := fmt.Sprintf("Game '%s' does not exist.\n", name)
		conn.Write([]byte(err_msg))
		fmt.Printf(err_msg)
		return
	}

	line, err = w.ReadString('\n')
	if err != nil {
		fmt.Printf("Error reading from player: %v\n", err)
		return
	}
	var seat int = -1
	_, err = fmt.Sscanf(line, "%d", &seat)
	if err != nil || seat < 0 || seat > 3 {
		var err_msg string
		if err != nil {
			err_msg = fmt.Sprintf("Unable to parse seat: '%s': %v\n", strings.TrimSpace(line), err)
		} else {
			err_msg = fmt.Sprintf("Invalid seat: %d\n", seat)
		}
		conn.Write([]byte(err_msg))
		fmt.Printf(err_msg)
		return
	}
	fmt.Printf("Asking for seat %d\n", seat)
	if !game.TakeSeat(seat, conn) {
		err_msg := fmt.Sprintf("Seat %d is already taken.\n", seat)
		conn.Write([]byte(err_msg))
		fmt.Printf(err_msg)
		return
	}
	fmt.Printf("Got seat %d\n", seat)
	conn.SetDeadline(time.Time{})
	success = true
}
Ejemplo n.º 22
0
func (this *TFunServer) serveCalls(tcpClient *net.TCPConn,
	remoteAddr string,
	processor thrift.TProcessor,
	inputProtocol thrift.TProtocol,
	outputProtocol thrift.TProtocol) (callsN int64, errsN int64) {
	var (
		t1      time.Time
		elapsed time.Duration
	)

	for {
		t1 = time.Now()
		if config.Engine.Rpc.IoTimeout > 0 { // read + write
			tcpClient.SetDeadline(t1.Add(config.Engine.Rpc.IoTimeout))
		}

		_, ex := processor.Process(inputProtocol, outputProtocol)
		callsN++ // call num increment first anyway

		elapsed = time.Since(t1)
		this.stats.CallLatencies.Update(elapsed.Nanoseconds() / 1e6)
		this.stats.CallPerSecond.Mark(1)

		if ex == nil {
			// rpc func called/Processed without any error
			continue
		}

		// exception thrown, maybe system wise or app wise

		/*
			thrift exceptions

			TException
				|
				|- TApplicationException
				|- TProtocolException (BAD_VERSION), it should never be thrown, we skip it
				|- TTransportException
		*/
		if err, isTransportEx := ex.(thrift.TTransportException); isTransportEx {
			if err.TypeId() != thrift.END_OF_FILE {
				// e,g. connection reset by peer: read a socket that was closed by peer, RST
				// e,g. broken pipe: write to socket that was closed by peer
				// e,g. read tcp i/o timeout
				log.Error("transport[%s]: %s", remoteAddr, ex.Error())
				errsN++
				this.saveCallError(err)
			} else {
				// EOF is not err, its normal end of session
				err = nil
			}

			callsN-- // in case of transport err, the call didn't finish
			this.stats.CallPerSession.Update(callsN)

			// for transport err, server always stop the session
			return
		}

		// TProtocolException should never happen
		// so ex MUST be servant generated TApplicationException
		// e,g Error 1064: You have an error in your SQL syntax
		errsN++
		this.saveCallError(ex)

		// it must be TApplicationException
		// the central place to log call err
		// servant needn't dup err log
		log.Error("caller[%s]: %s", remoteAddr, ex.Error())
	}

	this.stats.CallPerSession.Update(callsN)
	return
}
Ejemplo n.º 23
0
func (server *TcpServer) handle() (err error) {
	defer func() {
		if e := recover(); e != nil && err == nil {
			err = fmt.Errorf("%v", e)
		}
	}()
	if server.listener == nil {
		return nil
	}
	var conn *net.TCPConn
	if conn, err = server.listener.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)
	}
	return nil
}