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()
}
Beispiel #2
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
}
Beispiel #3
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
}
Beispiel #4
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
}
Beispiel #5
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()
}
Beispiel #6
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()
	}
}
Beispiel #7
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
}
Beispiel #8
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()
}
Beispiel #9
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()
}
Beispiel #10
0
func newServerConn(rwc io.ReadWriteCloser, buf *bufio.ReadWriter, req *http.Request) (conn *Conn, err os.Error) {
	config := new(Config)
	var hs serverHandshaker = &hybiServerHandshaker{Config: config}
	code, err := hs.ReadHandshake(buf.Reader, req)
	if err == ErrBadWebSocketVersion {
		fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
		fmt.Fprintf(buf, "Sec-WebSocket-Version: %s\r\n", SupportedProtocolVersion)
		buf.WriteString("\r\n")
		buf.WriteString(err.String())
		return
	}
	if err != nil {
		hs = &hixie76ServerHandshaker{Config: config}
		code, err = hs.ReadHandshake(buf.Reader, req)
	}
	if err != nil {
		hs = &hixie75ServerHandshaker{Config: config}
		code, err = hs.ReadHandshake(buf.Reader, req)
	}
	if err != nil {
		fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
		buf.WriteString("\r\n")
		buf.WriteString(err.String())
		return
	}
	config.Protocol = nil

	err = hs.AcceptHandshake(buf.Writer)
	if err != nil {
		return
	}
	conn = hs.NewServerConn(buf, rwc, req)
	return
}
Beispiel #11
0
func buildHTTPResponse(bufrw *bufio.ReadWriter) {
	var newHeader http.Header = make(http.Header)

	newHeader.Add("Access-Control-Allow-Origin", "*")
	newHeader.Add("Content-Type", "application/json; charset=UTF-8")
	newHeader.Add("Cache-Control", "no-cache")
	newHeader.Add("X-AppServer", "GoAPP")
	// write status line
	bufrw.WriteString("HTTP/1.1 200 OK" + "\r\n")
	// write headers
	_ = newHeader.Write(bufrw)
	// write a black line
	bufrw.WriteString("\n")
}
Beispiel #12
0
// Run performs a single synchronous command on the GarageFeed.
func (g *GarageFeed) run(req garageReq, rw *bufio.ReadWriter) (result string, err error) {
	if rw.Reader.Buffered() > 0 {
		panic("should be no bytes pending")
	}

	// Write the command, flush the buffer.
	_, err = rw.WriteString(fmt.Sprintf("%s\n", req.command))
	if err != nil {
		return "", err
	}
	rw.Flush()

	// Now, wait for a single line respnse.
	return rw.ReadString('\n')
}
Beispiel #13
0
func newServerConn(rwc io.ReadWriteCloser, buf *bufio.ReadWriter, req *http.Request, config *Config, handshake func(*Config, *http.Request) error) (conn *Conn, err error) {
	var hs serverHandshaker = &hybiServerHandshaker{Config: config}
	code, err := hs.ReadHandshake(buf.Reader, req)
	if err == ErrBadWebSocketVersion {
		fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
		fmt.Fprintf(buf, "Sec-WebSocket-Version: %s\r\n", SupportedProtocolVersion)
		buf.WriteString("\r\n")
		buf.WriteString(err.Error())
		buf.Flush()
		return
	}
	if err != nil {
		fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
		buf.WriteString("\r\n")
		buf.WriteString(err.Error())
		buf.Flush()
		return
	}
	if handshake != nil {
		err = handshake(config, req)
		if err != nil {
			code = http.StatusForbidden
			fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
			buf.WriteString("\r\n")
			buf.Flush()
			return
		}
	}
	err = hs.AcceptHandshake(buf.Writer)
	if err != nil {
		code = http.StatusBadRequest
		fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
		buf.WriteString("\r\n")
		buf.Flush()
		return
	}
	conn = hs.NewServerConn(buf, rwc, req)
	return
}
Beispiel #14
0
func (s *Server) handleSingle(rw *bufio.ReadWriter) error {
	line, err := rw.ReadBytes('\n')
	if err != nil {
		return err
	}
	args := bytes.Fields(line)
	if len(args) == 0 {
		return nil
	}

	switch {
	case bytes.Equal(args[0], []byte("READ")):
		// READ topic offset limit\n
		if len(args) != 4 {
			fmt.Fprintf(rw, "ERR READ requires 3 arg, got %d\n", len(args)-1)
			return nil
		}
		s.mu.Lock()
		defer s.mu.Unlock()
		stack, ok := s.stacks[string(args[1])]
		if !ok {
			fmt.Fprintf(rw, "ERR stack %s does not exist\n", args[1])
			return nil
		}
		offset, err := strconv.ParseInt(string(args[2]), 10, 64)
		if err != nil || offset < 0 {
			fmt.Fprint(rw, "ERR invalid offset\n")
			return nil
		}
		limit, err := strconv.ParseInt(string(args[3]), 10, 64)
		if err != nil || limit <= 0 {
			fmt.Fprint(rw, "ERR invalid limit\n")
			return nil
		}

		if offset > int64(len(stack)) {
			return nil
		}
		if offset+limit > int64(len(stack)) {
			limit = int64(len(stack)) - offset
		}

		for i, msg := range stack[offset : offset+limit] {
			fmt.Fprintf(rw, "MSG %d %d\n", offset+int64(i), len(msg))
			rw.Write(msg)
			rw.WriteByte('\n')
		}
		rw.WriteString("END\n")

	case bytes.Equal(args[0], []byte("PUSH")):
		// PUSH topic msg-size\n
		// msg\n
		if len(args) != 3 {
			fmt.Fprintf(rw, "ERR PUSH requires 2 args, got %d\n", len(args)-1)
			return nil
		}

		msgsize, err := strconv.ParseInt(string(args[2]), 10, 64)
		if err != nil || msgsize <= 0 {
			fmt.Fprint(rw, "ERR invalid message size\n")
			return nil
		}

		b := make([]byte, msgsize+1)
		if n, err := rw.Read(b); err != nil {
			fmt.Fprintf(rw, "ERR cannot read: %s\n", err)
			return nil
		} else if n != len(b) {
			fmt.Fprint(rw, "ERR incompete message\n")
			return nil
		}
		if b[msgsize] != '\n' {
			fmt.Fprint(rw, "ERR invalid message termination\n")
			return nil
		}

		s.mu.Lock()
		defer s.mu.Unlock()
		s.stacks[string(args[1])] = append(s.stacks[string(args[1])], b[:msgsize])

		fmt.Fprint(rw, "OK\n")

	case bytes.Equal(args[0], []byte("LEN")):
		// LEN topic \n
		if len(args) != 2 {
			fmt.Fprintf(rw, "ERR LEN requires 1 arg, got %d\n", len(args)-1)
			return nil
		}
		s.mu.Lock()
		fmt.Fprintf(rw, "%d\n", len(s.stacks[string(args[1])]))
		defer s.mu.Unlock()
	case bytes.Equal(args[0], []byte("DUMP")):
		s.mu.Lock()
		for name, stack := range s.stacks {
			fmt.Fprintf(rw, "%s %s\n", name, stack)
		}
		rw.WriteString("END\n")
		defer s.mu.Unlock()

	default:
		fmt.Fprintf(rw, "ERR unknown command: %q\n", args)
	}
	return nil
}
Beispiel #15
0
func FlushHTTP(rw *bufio.ReadWriter) {
	rw.WriteString("\r\n")
	rw.Flush()
}