Exemple #1
0
func Interact(rw *bufio.ReadWriter, events chan<- Event, m *sb.Manager) (err error) {
	connC, err := NewConnection(m)
	if err != nil {
		return
	}
	go func() {
		for msg := range connC.Data.(*Connection).Messages {
			rw.WriteString(msg)
			rw.Flush()
		}
	}()

	events <- &NewConnectionEvent{connC}

	// rw.ReadLine seems to return a blank line immediately upon starting
	line, isPrefix, err := rw.ReadLine()
	for ; err == nil; line, isPrefix, err = rw.ReadLine() {
		if isPrefix {
			continue
		}
		s := bytes.NewBuffer(line).String()
		events <- &Command{s, connC}
	}

	events <- &DisconnectEvent{connC}

	return
}
Exemple #2
0
func (w *rpcWorker) callRPC(conn *bufio.ReadWriter, req *pdpb.Request) (resp *pdpb.Response, err error) {
	// Record some metrics.
	start := time.Now()
	label := metrics.GetCmdLabel(req)
	defer func() {
		if err == nil {
			cmdCounter.WithLabelValues(label).Inc()
			cmdDuration.WithLabelValues(label).Observe(time.Since(start).Seconds())
		} else {
			cmdFailedCounter.WithLabelValues(label).Inc()
			cmdFailedDuration.WithLabelValues(label).Observe(time.Since(start).Seconds())
		}
	}()

	msg := &msgpb.Message{
		MsgType: msgpb.MessageType_PdReq,
		PdReq:   req,
	}
	if err = util.WriteMessage(conn, newMsgID(), msg); err != nil {
		return nil, errors.Errorf("[pd] rpc failed: %v", err)
	}
	conn.Flush()
	if _, err = util.ReadMessage(conn, msg); err != nil {
		return nil, errors.Errorf("[pd] rpc failed: %v", err)
	}
	if msg.GetMsgType() != msgpb.MessageType_PdResp {
		return nil, errors.Trace(errInvalidResponse)
	}
	resp = msg.GetPdResp()
	if err = w.checkResponse(resp); err != nil {
		return nil, errors.Trace(err)
	}

	return resp, nil
}
Exemple #3
0
func recvMsg(rwr *bufio.ReadWriter, userId int64) {
	var (
		ok       bool
		conn     net.Conn
		closeErr error
	)

	//close old connection and channel
	if _, ok = us.chs[userId]; ok {
		conn = us.conns[userId]
		if closeErr = conn.Close(); closeErr != nil {
			println("close old connection error:", userId)
		}
	}

	//是为了其他的服务器可以读取redis的值来判断是否在线
	set(userId)

	res, _ := get(userId)
	log.Debug("%v", res)
	pushKafka(userId)

	var ta = make(chan Talk, 1)
	var ch Channel
	ch.ch = ta
	us.chs[userId] = ch
	for {
		talk := <-us.chs[userId].ch
		log.Debug("recv:%v", talk)
		str := fmt.Sprintf("<script>alert(\"%d:%s\")</script>", talk.userId, talk.msg)
		rwr.WriteString(str)
		rwr.Flush()
	}
}
func httpError(w http.ResponseWriter, bufrw *bufio.ReadWriter, code int) {
	w.Header().Set("Connection", "close")
	bufrw.WriteString(fmt.Sprintf("HTTP/1.0 %d %s\r\n", code, http.StatusText(code)))
	w.Header().Write(bufrw)
	bufrw.WriteString("\r\n")
	bufrw.Flush()
}
Exemple #5
0
// sendResponse send resp to client, sendResponse must be goroutine safe.
func (server *Server) writeHTTPResponse(rwr *bufio.ReadWriter, cb string, proto *Proto) (err error) {
	var pb []byte
	if proto.Body == nil {
		proto.Body = emptyJSONBody
	}
	if pb, err = json.Marshal(proto); err != nil {
		log.Error("json.Marshal() error(%v)", err)
		return
	}
	if len(cb) != 0 {
		if _, err = rwr.WriteString(cb); err != nil {
			log.Error("http rwr.Write() error(%v)", err)
			return
		}
		if err = rwr.WriteByte('='); err != nil {
			log.Error("http rwr.Write() error(%v)", err)
			return
		}
	}
	if _, err = rwr.Write(pb); err != nil {
		log.Error("http rwr.Write() error(%v)", err)
		return
	}
	if err = rwr.Flush(); err != nil {
		log.Error("http rwr.Flush() error(%v)", err)
	}
	proto.Reset()
	return
}
Exemple #6
0
func getMetadataCommon(rw *bufio.ReadWriter) (metadata, error) {
	if err := rw.Flush(); err != nil {
		return metadata{}, err
	}

	resHeader, err := binprot.ReadResponseHeader(rw)
	if err != nil {
		return metadata{}, err
	}

	err = binprot.DecodeError(resHeader)
	if err != nil {
		// read in the message "Not found" after a miss
		if _, ioerr := rw.Discard(int(resHeader.TotalBodyLength)); ioerr != nil {
			return metadata{}, ioerr
		}
		return metadata{}, err
	}

	serverFlags := make([]byte, 4)
	binary.Read(rw, binary.BigEndian, &serverFlags)

	var metaData metadata
	binary.Read(rw, binary.BigEndian, &metaData)

	return metaData, nil
}
Exemple #7
0
func simpleCmdLocal(rw *bufio.ReadWriter) error {
	if err := rw.Flush(); err != nil {
		return err
	}

	resHeader, err := binprot.ReadResponseHeader(rw)
	if err != nil {
		return err
	}
	defer binprot.PutResponseHeader(resHeader)

	err = binprot.DecodeError(resHeader)
	if err != nil {
		n, ioerr := rw.Discard(int(resHeader.TotalBodyLength))
		metrics.IncCounterBy(common.MetricBytesReadLocal, uint64(n))
		if ioerr != nil {
			return ioerr
		}
		return err
	}

	// Read in the message bytes from the body
	n, err := rw.Discard(int(resHeader.TotalBodyLength))
	metrics.IncCounterBy(common.MetricBytesReadLocal, uint64(n))

	return err
}
Exemple #8
0
func simpleCmdLocal(rw *bufio.ReadWriter) error {
	if err := rw.Flush(); err != nil {
		return err
	}

	resHeader, err := binprot.ReadResponseHeader(rw)
	if err != nil {
		return err
	}

	err = binprot.DecodeError(resHeader)
	if err != nil {
		if _, ioerr := rw.Discard(int(resHeader.TotalBodyLength)); ioerr != nil {
			return ioerr
		}
		return err
	}

	// Read in the message bytes from the body
	if _, err := rw.Discard(int(resHeader.TotalBodyLength)); err != nil {
		return err
	}

	return nil
}
Exemple #9
0
func complex_handshake(rw *bufio.ReadWriter, input []byte) bool {
	result, scheme, challenge, digest := validateClient(input)
	if !result {
		return result
	}
	log.Debugf("Validate Client %v scheme %v challenge %0X digest %0X", result, scheme, challenge, digest)
	s1 := create_s1()
	log.Debug("s1 length", len(s1))
	off := getDigestOffset(s1, scheme)
	log.Debug("s1 digest offset", off)
	buf := new(bytes.Buffer)
	buf.Write(s1[:off])
	buf.Write(s1[off+32:])
	tempHash, _ := HMACsha256(buf.Bytes(), GENUINE_FMS_KEY[:36])
	copy(s1[off:], tempHash)
	log.Debug("s1 length", len(s1))
	//compute the challenge digest
	tempHash, _ = HMACsha256(digest, GENUINE_FMS_KEY[:68])
	log.Debug("s2 length tempHash", len(tempHash))
	randBytes := create_s2()
	log.Debug("s2 length", len(randBytes))
	lastHash, _ := HMACsha256(randBytes, tempHash)
	log.Debug("s2 length lastHash", len(lastHash))
	log.Debug("s2 length", len(randBytes))
	buf = new(bytes.Buffer)
	buf.WriteByte(0x03)
	buf.Write(s1)
	buf.Write(randBytes)
	buf.Write(lastHash)
	log.Debug("send s0s1s2", buf.Len())
	rw.Write(buf.Bytes())
	rw.Flush()
	ReadBuf(rw, HANDSHAKE_SIZE)
	return true
}
Exemple #10
0
func writeChunks(r io.Reader, w *bufio.ReadWriter) error {
	buf := make([]byte, 32*1024)
	for {
		n, err := r.Read(buf)

		if n > 0 {
			length := fmt.Sprintf("%x\r\n", n)
			w.WriteString(length)

			_, err := w.Write(buf[0:n])
			if err != nil {
				return err
			}

			w.WriteString("\r\n")
			w.Flush()
		}

		if err != nil && err != io.EOF {
			return err
		}
		if err == io.EOF {
			break
		}
	}
	return nil
}
Exemple #11
0
func getLocal(rw *bufio.ReadWriter) (data []byte, flags uint32, err error) {
	if err := rw.Flush(); err != nil {
		return nil, 0, err
	}

	resHeader, err := binprot.ReadResponseHeader(rw)
	if err != nil {
		return nil, 0, err
	}

	err = binprot.DecodeError(resHeader)
	if err != nil {
		if _, ioerr := rw.Discard(int(resHeader.TotalBodyLength)); ioerr != nil {
			return nil, 0, ioerr
		}
		return nil, 0, err
	}

	var serverFlags uint32
	binary.Read(rw, binary.BigEndian, &serverFlags)

	// total body - key - extra
	dataLen := resHeader.TotalBodyLength - uint32(resHeader.KeyLength) - uint32(resHeader.ExtraLength)
	buf := make([]byte, dataLen)

	// Read in value
	if _, err := io.ReadFull(rw, buf); err != nil {
		return nil, 0, err
	}

	return buf, serverFlags, nil
}
Exemple #12
0
func hijacked500(brw *bufio.ReadWriter, protoMinor int, statuses *statusStats) {
	statuses.status5xx.Add(1)
	// Assumes HTTP/1.x
	s := fmt.Sprintf(resp500Format, protoMinor, time.Now().Format(http.TimeFormat))
	brw.WriteString(s)
	brw.Flush()
}
Exemple #13
0
func (ms MemcachedProtocolServer) writeLine(buf *bufio.ReadWriter, s string) error {
	_, err := buf.WriteString(fmt.Sprintf("%s\r\n", s))
	if err != nil {
		return err
	}
	err = buf.Flush()
	return err
}
Exemple #14
0
func writeMessage(w *bufio.ReadWriter, m Message) {
	raw := ""
	for k, v := range m {
		raw += k + ":" + v + "\r\n"
	}
	raw += "\r\n"
	w.WriteString(raw)
	w.Flush()
}
Exemple #15
0
func writeResponse(bw *bufio.ReadWriter, body ...string) error {
	for _, chunk := range body {
		if _, err := bw.WriteString(chunk); err != nil {
			return err
		}
	}

	return bw.Flush()
}
Exemple #16
0
func (t TextProt) Prepend(rw *bufio.ReadWriter, key []byte, value []byte) error {
	if _, err := fmt.Fprintf(rw, "prepend %s 0 0 %v\r\n%s\r\n", string(key), len(value), string(value)); err != nil {
		return err
	}

	rw.Flush()

	_, err := rw.ReadString('\n')
	return err
}
Exemple #17
0
func pushResponse(bufrw *bufio.ReadWriter, authCode string) bool {
	_, err := bufrw.Write([]byte(authCode))
	if err == nil {
		err = bufrw.Flush()
	}
	if err != nil {
		go_lib.LogErrorf("PushAuthCodeError: %s\n", err)
		return false
	}
	return true
}
Exemple #18
0
func writeReadLine(rw *bufio.ReadWriter, format string, args ...interface{}) ([]byte, error) {
	_, err := fmt.Fprintf(rw, format, args...)
	if err != nil {
		return nil, err
	}
	if err := rw.Flush(); err != nil {
		return nil, err
	}
	line, err := rw.ReadSlice('\n')
	return line, err
}
Exemple #19
0
func (b BinProt) Get(rw *bufio.ReadWriter, key []byte) error {
	// Header
	writeReq(rw, Get, len(key), 0, len(key))
	// Body
	rw.Write(key)

	rw.Flush()

	// consume all of the response and discard
	return consumeResponse(rw.Reader)
}
Exemple #20
0
func (b BinProt) GetWithOpaque(rw *bufio.ReadWriter, key []byte, opaque int) ([]byte, error) {
	// Header
	writeReq(rw, Get, len(key), 0, len(key), opaque)
	// Body
	rw.Write(key)

	rw.Flush()

	// consume all of the response and return
	return consumeResponseCheckOpaque(rw.Reader, opaque)
}
Exemple #21
0
func (b BinProt) GetE(rw *bufio.ReadWriter, key []byte) ([]byte, uint32, uint32, error) {
	// Header
	writeReq(rw, GetE, len(key), 0, len(key), 0)
	// Body
	rw.Write(key)

	rw.Flush()

	// consume all of the response and return
	return consumeResponseE(rw.Reader)
}
Exemple #22
0
func Register(rw *bufio.ReadWriter, user, real string) error {
	var (
		str string = fmt.Sprintf("USER %s 0 * :%s\r\n", user, real)
		err error
	)
	_, err = rw.Write([]byte(str))
	if err != nil {
		return err
	}
	rw.Flush()
	return nil
}
Exemple #23
0
func pushResponse(bufrw *bufio.ReadWriter, content interface{}, group string, op string) {
	literals := fmt.Sprintf("%v", content)
	_, err := bufrw.Write([]byte(literals))
	if err == nil {
		err = bufrw.Flush()
	}
	if err != nil {
		base.Logger().Errorf("Pushing response error (content=%v, group=%s, op=%s): %s\n", literals, group, op, err)
	} else {
		base.Logger().Errorf("The response '%v' has been pushed. (group=%s, op=%s)\n", literals, group, op)
	}
}
Exemple #24
0
func ChangeNick(rw *bufio.ReadWriter, nick string) error {
	var (
		str string = fmt.Sprintf("NICK %s\r\n", nick)
		err error
	)
	_, err = rw.Write([]byte(str))
	if err != nil {
		return err
	}
	rw.Flush()
	return nil
}
Exemple #25
0
func Part(rw *bufio.ReadWriter, channel string) error {
	var (
		str string = fmt.Sprintf("PART %s\r\n", channel)
		err error
	)
	_, err = rw.Write([]byte(str))
	if err != nil {
		return err
	}
	rw.Flush()
	return nil
}
Exemple #26
0
func Quit(rw *bufio.ReadWriter, reason string) error {
	var (
		str string = fmt.Sprintf("QUIT %s\r\n", reason)
		err error
	)
	_, err = rw.Write([]byte(str))
	if err != nil {
		return err
	}
	rw.Flush()
	return nil
}
Exemple #27
0
func (b BinProt) Delete(rw *bufio.ReadWriter, key []byte) error {
	// Header
	writeReq(rw, Delete, len(key), 0, len(key), 0)
	// Body
	rw.Write(key)

	rw.Flush()

	// consume all of the response and discard
	_, err := consumeResponse(rw.Reader)
	return err
}
Exemple #28
0
func Message(rw *bufio.ReadWriter, target, message string) error {
	var (
		str string = fmt.Sprintf("PRIVMSG %s :%s\r\n", target, message)
		err error
	)
	_, err = rw.Write([]byte(str))
	if err != nil {
		return err
	}
	rw.Flush()
	return nil
}
Exemple #29
0
func Ping(rw *bufio.ReadWriter, message string) error {
	var (
		str string = fmt.Sprintf("PING %s\r\n", message)
		err error
	)
	_, err = rw.Write([]byte(str))
	if err != nil {
		return err
	}
	rw.Flush()
	return nil
}
Exemple #30
0
// execute sends a command to redis, then reads and parses the response.
// It uses the old protocol and can be used by simple commands, such as DB.
// Redis protocol <http://redis.io/topics/protocol>
func (c *Client) execute(rw *bufio.ReadWriter, a ...interface{}) (v interface{}, err error) {
	//fmt.Printf("\nSending: %#v\n", a)
	// old redis protocol.
	_, err = fmt.Fprintf(rw, strings.Join(autoconv_args(a), " ")+"\r\n")
	if err != nil {
		return
	}
	if err = rw.Flush(); err != nil {
		return
	}
	return c.parseResponse(rw.Reader)
}