Example #1
0
// socksAuthRFC1929 authenticates the client via RFC 1929 username/password
// auth.  As a design decision any valid username/password is accepted as this
// field is primarily used as an out-of-band argument passing mechanism for
// pluggable transports.
func socksAuthRFC1929(rw *bufio.ReadWriter, req *SocksRequest) (err error) {
	sendErrResp := func() {
		// Swallow the write/flush error here, we are going to close the
		// connection and the original failure is more useful.
		resp := []byte{socksAuthRFC1929Ver, socksAuthRFC1929Fail}
		rw.Write(resp[:])
		socksFlushBuffers(rw)
	}

	// Validate the fixed parts of the command message.
	if err = socksReadByteVerify(rw, "auth version", socksAuthRFC1929Ver); err != nil {
		sendErrResp()
		return
	}

	// Read the username.
	var ulen byte
	if ulen, err = socksReadByte(rw); err != nil {
		return
	}
	if ulen < 1 {
		sendErrResp()
		err = fmt.Errorf("RFC1929 username with 0 length")
		return
	}
	var uname []byte
	if uname, err = socksReadBytes(rw, int(ulen)); err != nil {
		return
	}
	req.Username = string(uname)

	// Read the password.
	var plen byte
	if plen, err = socksReadByte(rw); err != nil {
		return
	}
	if plen < 1 {
		sendErrResp()
		err = fmt.Errorf("RFC1929 password with 0 length")
		return
	}
	var passwd []byte
	if passwd, err = socksReadBytes(rw, int(plen)); err != nil {
		return
	}
	if !(plen == 1 && passwd[0] == 0x00) {
		// tor will set the password to 'NUL' if there are no arguments.
		req.Password = string(passwd)
	}

	// Mash the username/password together and parse it as a pluggable
	// transport argument string.
	if req.Args, err = parseClientParameters(req.Username + req.Password); err != nil {
		sendErrResp()
	} else {
		resp := []byte{socksAuthRFC1929Ver, socksAuthRFC1929Success}
		_, err = rw.Write(resp[:])
	}
	return
}
Example #2
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()
	}
}
Example #3
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
}
Example #4
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()
}
Example #5
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
}
Example #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
}
Example #7
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
}
Example #8
0
File: control.go Project: bfix/sid
/*
 * Read command/input from connection.
 * @param b *bufioReadWriter - reader
 * @return cmd string - read input
 * @return err error - error state
 */
func readCmd(b *bufio.ReadWriter) (cmd string, err error) {
	line, err := b.ReadBytes('\n')
	if err != nil {
		return "", err
	}
	// get rid of enclosing white spaces
	return strings.Trim(string(line), " \t\n\v\r"), nil
}
Example #9
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
}
Example #10
0
File: server.go Project: htee/htee
func writeResponse(bw *bufio.ReadWriter, body ...string) error {
	for _, chunk := range body {
		if _, err := bw.WriteString(chunk); err != nil {
			return err
		}
	}

	return bw.Flush()
}
Example #11
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()
}
Example #12
0
File: prot.go Project: Netflix/rend
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
}
Example #13
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
}
Example #14
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
}
Example #15
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)
}
Example #16
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)
}
Example #17
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)
}
Example #18
0
File: irc.go Project: napsy/gorobot
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
}
Example #19
0
File: irc.go Project: napsy/gorobot
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
}
Example #20
0
File: irc.go Project: napsy/gorobot
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
}
Example #21
0
File: irc.go Project: napsy/gorobot
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
}
Example #22
0
File: irc.go Project: napsy/gorobot
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
}
Example #23
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)
}
Example #24
0
File: irc.go Project: napsy/gorobot
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
}
Example #25
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)
	}
}
Example #26
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
}
Example #27
0
func (b BinProt) GAT(rw *bufio.ReadWriter, key []byte) ([]byte, error) {
	// Header
	writeReq(rw, GAT, len(key), 4, len(key), 0)
	// Extras
	binary.Write(rw, binary.BigEndian, common.Exp())
	// Body
	rw.Write(key)

	rw.Flush()

	// consume all of the response and return
	return consumeResponse(rw.Reader)
}
Example #28
0
func (b BinProt) Touch(rw *bufio.ReadWriter, key []byte) error {
	// Header
	writeReq(rw, Touch, len(key), 4, len(key)+4)
	// Extras
	binary.Write(rw, binary.BigEndian, common.Exp())
	// Body
	rw.Write(key)

	rw.Flush()

	// consume all of the response and discard
	return consumeResponse(rw.Reader)
}
Example #29
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
}
Example #30
0
// hijack connection
func hijack(rw http.ResponseWriter) (conn net.Conn, err error) {
	hj, ok := rw.(http.Hijacker)
	if !ok {
		err = errors.New("webserver doesn't support hijacking")
		return
	}
	var buf *bufio.ReadWriter
	conn, buf, err = hj.Hijack()
	if err != nil {
		return
	}
	buf.Flush()
	return
}