Пример #1
0
// readBlob reads an OSC Blob from the blob byte array. Padding bytes are removed
// from the reader and not returned.
func readBlob(reader *bufio.Reader) (blob []byte, n int, err error) {
	// First, get the length
	var blobLen int
	if err = binary.Read(reader, binary.BigEndian, &blobLen); err != nil {
		return nil, 0, err
	}
	n = 4 + blobLen

	// Read the data
	blob = make([]byte, blobLen)
	if _, err = reader.Read(blob); err != nil {
		return nil, 0, err
	}

	// Remove the padding bytes
	numPadBytes := padBytesNeeded(blobLen)
	if numPadBytes > 0 {
		n += numPadBytes
		dummy := make([]byte, numPadBytes)
		if _, err = reader.Read(dummy); err != nil {
			return nil, 0, err
		}
	}

	return blob, n, nil
}
Пример #2
0
func (rb *ReaderBase) readBulk(r *bufio.Reader) (err error) {
	err = rb.readIneger(r)
	if err != nil {
		return
	}
	if rb.integer == -1 {
		rb.bulk = nil
		return
	}
	rb.bulk = make([]byte, rb.integer)

	n := 0
	written := 0

	for written < rb.integer {
		buf := make([]byte, rb.integer-written)
		n, err = r.Read(buf)
		if err != nil {
			return
		}

		if n > 0 {
			copy(rb.bulk[written:], buf[0:n])
			written += n
		}
	}
	err = rb.readCrLf(r)
	return
}
Пример #3
0
func handshake(client net.Conn, config *Config) (bouncer *BouncerConfig, remainder []byte) {
	// Setup a buffered reader over the client.
	var reader *bufio.Reader = bufio.NewReader(client)

	// Attempt to handshake with the client and determine the requested config.
	var match chan *BouncerConfig = make(chan *BouncerConfig, 1)
	go seekshake(reader, config, match)

	// Block until handshake is done or we hit our timeout.
	select {
	case bouncer = <-match:
		// Grab the remaining portion of the handshake.
		remainder = make([]byte, reader.Buffered())
		reader.Read(remainder)

		if bouncer != nil {
			log.Printf("LOGIN %s", client.RemoteAddr())
		} else {
			log.Printf("REJECT %s", client.RemoteAddr())
		}
		return bouncer, remainder
	case <-time.After(time.Duration(config.Auth.Timeout) * time.Second):
		log.Printf("TIMEOUT %s", client.RemoteAddr())
		return nil, []byte{}
	}
}
Пример #4
0
func (mcs *MemcacheServer) handleSet(addr string, reader *bufio.Reader, writer *bufio.Writer, args []string) {
	if len(args) > 6 || len(args) < 5 {
		writer.WriteString("ERROR\r\n")
		writer.Flush()
		return
	}
	// args[1] key
	// args[2] flags
	// args[3] exptime
	// args[4] bytes
	// args[5] noreply

	mcs.Logger.Debug("Memcache", "[%s] -> Set %s", addr, args)

	expirytime, err := strconv.Atoi(args[3])
	if err != nil {
		writer.WriteString("SERVER_ERROR\r\n")
		writer.Flush()
		return
	}

	flags, err := strconv.Atoi(args[2])
	flags = flags & 0xFFFF
	if err != nil {
		writer.WriteString("SERVER_ERROR\r\n")
		writer.Flush()
		return
	}

	bytes, err := strconv.Atoi(args[4])
	if err != nil {
		writer.WriteString("SERVER_ERROR\r\n")
		writer.Flush()
		return
	}

	var buf []byte = make([]byte, bytes, bytes)
	n, err := reader.Read(buf)
	if err != nil || n != len(buf) {
		writer.WriteString("SERVER_ERROR\r\n")
		writer.Flush()
		return
	}

	_, err = reader.ReadString('\n')
	if err != nil {
		writer.WriteString("SERVER_ERROR\r\n")
		writer.Flush()
		return
	}

	var expparam *time.Time = nil
	if expirytime != 0 {
		expiry := time.Now().UTC().Add(time.Duration(expirytime) * time.Second)
		expparam = &expiry
	}
	mcs.Server.SetKey(args[1], buf[:], int16(flags), expparam)
	writer.WriteString("STORED\r\n")
	writer.Flush()
}
func deserializeByReader(reader *bufio.Reader) (*pb.MobileSuiteProtobuf, error) {
	buff, _ := reader.Peek(4)
	data := bytes.NewBuffer(buff)
	var length int32
	err := binary.Read(data, binary.BigEndian, &length)
	if err != nil {
		return nil, err
	}
	fmt.Println(length)
	if int32(reader.Buffered()) < length+4 {
		return nil, err
	}

	pack := make([]byte, int(4+length))
	_, err = reader.Read(pack)
	if err != nil {
		return nil, err
	}
	msg := pack[4:]
	var dst pb.MobileSuiteProtobuf
	proto.Unmarshal(msg, &dst)
	fmt.Println(&dst)

	var testMsg pb.TestMessage
	proto.Unmarshal(dst.Message, &testMsg)
	fmt.Println(&testMsg)

	return &dst, nil
}
Пример #6
0
func readBodyIdentity(r *bufio.Reader, dst []byte) ([]byte, error) {
	dst = dst[:cap(dst)]
	if len(dst) == 0 {
		dst = make([]byte, 1024)
	}
	offset := 0
	for {
		nn, err := r.Read(dst[offset:])
		if nn <= 0 {
			if err != nil {
				if err == io.EOF {
					return dst[:offset], nil
				}
				return dst[:offset], err
			}
			panic(fmt.Sprintf("BUG: bufio.Read() returned (%d, nil)", nn))
		}
		offset += nn
		if len(dst) == offset {
			b := make([]byte, round2(2*offset))
			copy(b, dst)
			dst = b
		}
	}
}
Пример #7
0
func (cmd *cmdSync) PSyncPipeCopy(c net.Conn, br *bufio.Reader, bw *bufio.Writer, offset int64, copyto io.Writer) (int64, error) {
	defer c.Close()
	var nread atomic2.Int64
	go func() {
		defer c.Close()
		for {
			time.Sleep(time.Second * 5)
			if err := sendPSyncAck(bw, offset+nread.Get()); err != nil {
				return
			}
		}
	}()

	var p = make([]byte, 8192)
	for {
		n, err := br.Read(p)
		if err != nil {
			return nread.Get(), nil
		}
		if _, err := copyto.Write(p[:n]); err != nil {
			return nread.Get(), err
		}
		nread.Add(int64(n))
	}
}
Пример #8
0
// decodeP6 reads a binary pixmap
func decodeP6(r *bufio.Reader, img draw.Image, width, height uint) {
	var x, y, pix int

	mask := byte(readU(r))
	mul := 255 / mask
	data := make([]byte, width*height*3)

	space(r)

	_, err := r.Read(data)
	check(err)

	for y = 0; y < int(height); y++ {
		for x = 0; x < int(width); x++ {
			img.Set(x, y, color.RGBA{
				(data[pix] & mask) * mul,
				(data[pix+1] & mask) * mul,
				(data[pix+2] & mask) * mul,
				0xff,
			})

			pix += 3
		}
	}
}
Пример #9
0
func readSection(reader *bufio.Reader, readN int) ([]byte, error) {
	buf := make([]byte, readN)

	var err error
	n := 0
	for n < readN {
		m, err := reader.Read(buf[n:])
		if err != nil {
			break
		}
		n += m
	}

	if err != nil {
		return buf, err
	}

	end, err := reader.ReadString('\n')
	switch {
	case n != readN:
		return buf, io.ErrUnexpectedEOF
	case err == io.EOF:
		// That's ok
	case err != nil:
		return buf, err
	case end != "\r\n":
		return buf, errors.New("Unexpected end of section")
	}
	return buf, nil
}
Пример #10
0
//读取规定长度的数据
func (self LengthBasedFrameDecoder) Read(reader *bufio.Reader) (*bytes.Buffer, error) {
	var length int32

	err := Read(reader, b.BigEndian, &length)
	if nil != err {
		return nil, err
	} else if length <= 0 {
		return nil, errors.New("TOO SHORT PACKET")
	}

	if length > self.MaxFrameLength {
		return nil, errors.New("TOO LARGE PACKET!")
	}

	buff := make([]byte, int(length))
	tmp := buff
	l := 0
	for {
		rl, err := reader.Read(tmp)
		if nil != err {
			return nil, err
		}
		l += rl

		if l < int(length) {
			tmp = tmp[rl:]
			continue
		} else {
			break
		}
	}
	return bytes.NewBuffer(buff), nil
}
Пример #11
0
func readFile(path string) {
	var w *bufio.Writer = bufio.NewWriter(os.Stdout)
	defer w.Flush()

	fmt.Fprintf(w, "read file start: %s\n", path)

	file, err := os.OpenFile(path, os.O_RDONLY, 0666) // 打开文件

	if err != nil {
		fmt.Printf("open file err: %v\n", err)
		return
	}

	defer file.Close() // 延时关闭文件

	var buff []byte = make([]byte, 1024)
	var r *bufio.Reader = bufio.NewReader(file)

	for {
		n, _ := r.Read(buff)
		if n <= 0 {
			fmt.Fprintf(w, "read file end: %s %d\n", path, n)
			return
		}

		w.Write(buff[0:n])
	}
}
Пример #12
0
func appendBodyFixedSize(r *bufio.Reader, dst []byte, n int) ([]byte, error) {
	if n == 0 {
		return dst, nil
	}

	offset := len(dst)
	dstLen := offset + n
	if cap(dst) < dstLen {
		b := make([]byte, round2(dstLen))
		copy(b, dst)
		dst = b
	}
	dst = dst[:dstLen]

	for {
		nn, err := r.Read(dst[offset:])
		if nn <= 0 {
			if err != nil {
				if err == io.EOF {
					err = io.ErrUnexpectedEOF
				}
				return dst[:offset], err
			}
			panic(fmt.Sprintf("BUG: bufio.Read() returned (%d, nil)", nn))
		}
		offset += nn
		if offset == dstLen {
			return dst, nil
		}
	}
}
Пример #13
0
func readN(rd *bufio.Reader, n int) ([]byte, error) {
	// b, err := rd.ReadN(n)
	b := make([]byte, n)

	_, err := io.ReadFull(rd, b)
	if err == bufio.ErrBufferFull {
		tmp := make([]byte, n)
		r := copy(tmp, b)
		b = tmp

		for {
			nn, err := rd.Read(b[r:])
			r += nn
			if r >= n {
				// Ignore error if we read enough.
				break
			}
			if err != nil {
				return nil, err
			}
		}
	} else if err != nil {
		return nil, err
	}
	return b, nil
}
Пример #14
0
func (u *udpgwPacket) read(r *bufio.Reader) error {
	bs, err := r.Peek(2)
	if nil != err {
		return err
	}
	u.length = binary.LittleEndian.Uint16(bs)
	//binary.Read(r, binary.BigEndian, &u.length)
	r.Discard(2)
	//log.Printf("###First %d  %d %d %p", u.length, binary.BigEndian.Uint16(bs), len(bs), r)
	_, err = r.Peek(int(u.length))
	if nil != err {
		//log.Printf("### %v", err)
		return err
	}
	bodylen := u.length
	binary.Read(r, binary.BigEndian, &u.flags)
	binary.Read(r, binary.BigEndian, &u.conid)
	bodylen -= 3
	if bodylen > 0 {
		if (u.flags & flagIPv6) != 0 {
			u.addr.ip = make(net.IP, 16)

		} else {
			u.addr.ip = make(net.IP, 4)
		}
		r.Read(u.addr.ip)
		bodylen -= uint16(len(u.addr.ip))
		binary.Read(r, binary.BigEndian, &u.addr.port)
		bodylen -= 2
		u.content = make([]byte, int(bodylen))
		r.Read(u.content)
	}
	return nil
}
Пример #15
0
func readAndWriteTLS(r *bufio.Reader, w *bufio.Writer, con *tls.Conn, verbose bool) <-chan bool {
	c := make(chan bool)
	go func() {
		defer func() {
			(*con).Close()
			c <- false
		}()
		for {
			buf := make([]byte, 1024)
			message, errRead := r.Read(buf)
			if errRead != nil {
				if errRead != io.EOF {
					if verbose {
						log.Println("READ ERROR: ", errRead)
					}
				}
				break
			}
			_, errWrite := w.Write(buf[:message])
			w.Flush()
			if errWrite != nil {
				if verbose {
					log.Println("WRITE ERROR: ", errWrite)
				}
				return
			}
		}
	}()
	return c
}
Пример #16
0
func (d *Decoder) Decode(in *bufio.Reader, out *bytes.Buffer) (err error) {
	for {
		b, err := in.ReadByte()
		if err != nil {
			break
		}
		switch b {
		case '=':
			char := make([]byte, 2)
			in.Read(char)
			code, _ := strconv.ParseUint(string(char), 16, 8)
			out.WriteByte(byte(code))
		case '_':
			err = out.WriteByte(' ')
		case ' ':
			return errors.New("Invalid char ` `")
		case '?':
			b, err = in.ReadByte()
			if b == '=' {
				return nil
			}
			return errors.New("Unexpected `?`")
		default:
			err = out.WriteByte(b)
		}
	}
	return err
}
Пример #17
0
func readBodyIdentity(r *bufio.Reader, maxBodySize int, dst []byte) ([]byte, error) {
	dst = dst[:cap(dst)]
	if len(dst) == 0 {
		dst = make([]byte, 1024)
	}
	offset := 0
	for {
		nn, err := r.Read(dst[offset:])
		if nn <= 0 {
			if err != nil {
				if err == io.EOF {
					return dst[:offset], nil
				}
				return dst[:offset], err
			}
			panic(fmt.Sprintf("BUG: bufio.Read() returned (%d, nil)", nn))
		}
		offset += nn
		if maxBodySize > 0 && offset > maxBodySize {
			return dst[:offset], ErrBodyTooLarge
		}
		if len(dst) == offset {
			n := round2(2 * offset)
			if maxBodySize > 0 && n > maxBodySize {
				n = maxBodySize + 1
			}
			b := make([]byte, n)
			copy(b, dst)
			dst = b
		}
	}
}
Пример #18
0
// decodeP4 reads a binary bitmap
func decodeP4(r *bufio.Reader, img draw.Image, width, height uint) {
	var x, y, bit int

	bytes := int(math.Ceil((float64(width) / 8)))
	bits := newBitset(uint(bytes) * height * 8)
	pad := (bytes * 8) - int(width)

	space(r)

	_, err := r.Read(bits)
	check(err)

	for y = 0; y < int(height); y++ {
		for x = 0; x < int(width); x++ {
			if bits.Test(bit) {
				img.Set(x, y, color.Alpha{0xff})
			} else {
				img.Set(x, y, color.Alpha{0x00})
			}

			bit++
		}

		bit += pad
	}
}
Пример #19
0
func chompFrontmatterEndComment(r *bufio.Reader) (err error) {
	candidate, err := r.Peek(32)
	if err != nil {
		return err
	}

	str := string(candidate)
	lineEnd := strings.IndexAny(str, "\n")
	if lineEnd == -1 {
		return nil
	}
	testStr := strings.TrimSuffix(str[0:lineEnd], "\r")
	if strings.Index(testStr, HTMLCommentStart) != -1 {
		return nil
	}

	//TODO: if we can't find it, Peek more?
	if strings.HasSuffix(testStr, HTMLCommentEnd) {
		buf := make([]byte, lineEnd)
		if _, err = r.Read(buf); err != nil {
			return
		}
		if err = chompWhitespace(r); err != nil {
			return err
		}
	}

	return nil
}
Пример #20
0
func (self ProtobufProbe) DeserializeByReader(reader *bufio.Reader) (*protocol.MobileSuiteModel, int32, error) {
	lengthByte, _ := reader.Peek(4)
	lengthBuff := bytes.NewBuffer(lengthByte)
	var length int32
	err := binary.Read(lengthBuff, binary.LittleEndian, &length)
	if err != nil {
		log.Error("when deserializeByReader:", err.Error())
		return nil, -1, err
	}

	if int32(reader.Buffered()) < length+4 {
		log.Error("int32(reader.Buffered()) < length + 4")
		return nil, -1, err
	}

	pack := make([]byte, int(4+length))
	_, err = reader.Read(pack)
	if err != nil {
		log.Error("when deserializeByReader:", err.Error())
		return nil, -1, err
	}
	var dst protocol.MobileSuiteModel
	var msgType int32
	msgType, err = self.Deserialize(pack, &dst)
	log.Debug(length, msgType, dst)
	return &dst, msgType, nil
}
Пример #21
0
func (c *DefaultServerCodec) ReadRequestBody(rd *bufio.Reader, proto *Proto) (err error) {
	var (
		n       = int(0)
		t       = int(0)
		bodyLen = int(proto.PackLen - int32(proto.HeaderLen))
	)
	log.Debug("read body len: %d", bodyLen)
	if bodyLen > 0 {
		proto.Body = make([]byte, bodyLen)
		// no deadline, because readheader always incoming calls readbody
		for {
			if t, err = rd.Read(proto.Body[n:]); err != nil {
				log.Error("body: buf.Read() error(%v)", err)
				return
			}
			if n += t; n == bodyLen {
				log.Debug("body: rd.Read() fill ok")
				break
			} else if n < bodyLen {
				log.Debug("body: rd.Read() need %d bytes", bodyLen-n)
			} else {
				log.Error("body: readbytes %d > %d", n, bodyLen)
			}
		}
	} else {
		proto.Body = nil
	}
	return
}
Пример #22
0
func readBulkStr(r *bufio.Reader) (Resp, error) {
	b, err := r.ReadBytes(delimEnd)
	if err != nil {
		return Resp{}, err
	}
	size, err := strconv.ParseInt(string(b[1:len(b)-2]), 10, 64)
	if err != nil {
		return Resp{}, errParse
	}
	if size < 0 {
		return Resp{typ: Nil}, nil
	}
	total := make([]byte, size)
	b2 := total
	var n int
	for len(b2) > 0 {
		n, err = r.Read(b2)
		if err != nil {
			return Resp{}, err
		}
		b2 = b2[n:]
	}

	// There's a hanging \r\n there, gotta read past it
	trail := make([]byte, 2)
	for i := 0; i < 2; i++ {
		c, err := r.ReadByte()
		if err != nil {
			return Resp{}, err
		}
		trail[i] = c
	}

	return Resp{typ: BulkStr, val: total}, nil
}
Пример #23
0
func (b *Broker) HandleRequest(rb *bufio.Reader, c net.Conn) error {
	buf := make([]byte, 1024)
	request := new(task.TaskRequest)
	readLen, err := rb.Read(buf)
	if err != nil {
		b.WriteError(err, c)
		return err
	}

	err = json.Unmarshal(buf[:readLen], request)
	if err != nil {
		b.WriteError(err, c)
		return err
	}

	now := time.Now().Unix()
	if request.StartTime == 0 {
		request.StartTime = now
	}

	if request.StartTime <= now {
		err = b.AddRequestToRedis(request)
		if err != nil {
			b.WriteError(err, c)
			return err
		}
	} else {
		afterTime := time.Second * time.Duration(request.StartTime-now)
		b.timer.NewTimer(afterTime, b.AddRequestToRedis, request)
	}

	return b.WriteOK(c)
}
Пример #24
0
// Read Optional param
func (op *pduOptParam) read(r *bufio.Reader) (err os.Error) {
	// Read first 4 descripter bytes
	p := make([]byte, 4)
	_, err = r.Read(p)
	if err != nil {
		return
	}
	op.tag = uint16(unpackUint(p[0:2]))
	op.length = uint16(unpackUint(p[2:4]))
	// Read value data
	if op.length > 0 {
		vp := make([]byte, op.length)
		_, err = r.Read(vp)
		if err != nil {
			return
		}
		// Determine data type of value
		switch op.tag {
		case TAG_ADDITIONAL_STATUS_INFO_TEXT, TAG_RECEIPTED_MESSAGE_ID, TAG_SOURCE_SUBADDRESS, TAG_DEST_SUBADDRESS, TAG_NETWORK_ERROR_CODE, TAG_MESSAGE_PAYLOAD, TAG_CALLBACK_NUM, TAG_CALLBACK_NUM_ATAG, TAG_ITS_SESSION_INFO:
			op.value = string(vp)
		case TAG_DEST_ADDR_SUBUNIT, TAG_SOURCE_ADDR_SUBUNIT, TAG_DEST_NETWORK_TYPE, TAG_SOURCE_NETWORK_TYPE, TAG_DEST_BEARER_TYPE, TAG_SOURCE_BEARER_TYPE, TAG_SOURCE_TELEMATICS_ID, TAG_PAYLOAD_TYPE, TAG_MS_MSG_WAIT_FACILITIES, TAG_PRIVACY_INDICATOR, TAG_USER_RESPONSE_CODE, TAG_LANGUAGE_INDICATOR, TAG_SAR_TOTAL_SEGMENTS, TAG_SAR_SEGMENT_SEQNUM, TAG_SC_INTERFACE_VERSION, TAG_DISPLAY_TIME, TAG_MS_VALIDITY, TAG_DPF_RESULT, TAG_SET_DPF, TAG_MS_AVAILABILITY_STATUS, TAG_DELIVERY_FAILURE_REASON, TAG_MORE_MESSAGES_TO_SEND, TAG_MESSAGE_STATE, TAG_CALLBACK_NUM_PRES_IND, TAG_NUMBER_OF_MESSAGES, TAG_SMS_SIGNAL, TAG_ITS_REPLY_TYPE, TAG_USSD_SERVICE_OP:
			op.value = uint8(vp[0])
		case TAG_DEST_TELEMATICS_ID, TAG_USER_MESSAGE_REFERENCE, TAG_SOURCE_PORT, TAG_DESTINATION_PORT, TAG_SAR_MSG_REF_NUM:
			op.value = uint16(unpackUint(vp))
		case TAG_QOS_TIME_TO_LIVE:
			op.value = uint32(unpackUint(vp))
		}
	} else {
		op.value = nil
	}
	return
}
Пример #25
0
func readPacket(br *bufio.Reader) ([]byte, error) {
	// Drop bytes preceding HEADER_BYTE
	_, err := br.ReadBytes(HEADER_BYTE)
	if err != nil {
		return nil, err
	}

	// Get packet length field
	packet := make([]byte, 4)
	read_bytes := 0
	for read_bytes < 4 {
		tmp := make([]byte, 4)
		nread, err := br.Read(tmp)
		if err != nil {
			return nil, err
		}
		copy(packet[read_bytes:], tmp[:nread])
		read_bytes += nread
	}
	pktlen := int(binary.BigEndian.Uint32(packet))

	// Get rest of packet
	packet = make([]byte, pktlen)
	read_bytes = 0
	for read_bytes < pktlen {
		tmp := make([]byte, pktlen)
		nread, err := br.Read(tmp)
		if err != nil {
			return nil, err
		}
		copy(packet[read_bytes:], tmp[:nread])
		read_bytes += nread
	}
	return packet, nil
}
Пример #26
0
func Unpack(reader *bufio.Reader) ([]byte, error) {

	return reader.ReadBytes('\n')
	//if global.PackSplitType =="breakline" {

	//	return reader.ReadBytes('\n')
	//}

	lengthByte, _ := reader.Peek(4)
	lengthBuff := bytes.NewBuffer(lengthByte)
	var length int32
	err := binary.Read(lengthBuff, binary.LittleEndian, &length)
	if err != nil {
		return nil, err
	}
	fmt.Println("Get length :", length)
	if int32(reader.Buffered()) < length+4 {
		return nil, err
	}

	pack := make([]byte, int(4+length))
	_, err = reader.Read(pack)
	if err != nil {
		return nil, err
	}
	return pack[4:], nil
}
Пример #27
0
func (hub *MsgHub) msgProc(id int, reader *bufio.Reader) (err error) {
	var msgType byte
	var controlType byte

	msgType, err = reader.ReadByte()
	if err != nil {
		ERROR.Println("read from incoming error, detail:", err)
		return
	}
	switch msgType {
	case StringMsgType:
		//drop msg, should be ping
		var bs []byte
		bs, err = reader.ReadSlice('\n')
		if err != nil {
			return
		} else {
			INFO.Println(id, "said:", string(bs[:len(bs)-1]))
		}
	case ControlMsgType: //cronntrol msg
		if controlType, err = reader.ReadByte(); err != nil {
			return
		}
		switch controlType {
		case AddRouteControlType, RemoveRouteControlType:
			var msg RouteControlMsg
			var buf = make([]byte, msg.Len())
			buf[0] = ControlMsgType
			buf[1] = controlType
			reader.Read(buf[2:])
			if err = msg.Unmarshal(buf); err != nil {
				return
			}
			if msg.ControlType == AddRouteControlType {
				hub.AddRoute(msg.Id, msg.Type, id, nil)
			} else {
				hub.RemoveRoute(msg.Id, msg.Type)
			}
		case OfflineControlType:
			if err = hub.OfflineIncomingControlMsg(ControlMsgType, OfflineMsgType, reader); err != nil {
				return
			}
		}
	case RouteMsgType, TempRouteMsgType:
		var msg DeliverMsg
		if msg.To, msg.Carry, err = readRouteMsgBody(reader); err != nil {
			return
		}
		msg.MsgType = msgType
		hub.LocalDispatch(&msg)
	case OfflineMsgType:
		if err = hub.OfflineIncomingMsg(OfflineMsgType, reader); err != nil {
			return
		}
	default:
		err = UnknownMsg
	}
	return nil
}
Пример #28
0
// Reads transfer-encoding: chunked payloads from the connection reader.
func (c *Connection) readChunkedData() error {
	var err error
	var line []byte
	var size uint64
	var start time.Time

	start = time.Now()
	writer := &nonEmptyWriter{os.Stdout}

	var buffer *bytes.Buffer
	var decompressor *gzip.Reader
	var zipReader *bufio.Reader
	var data []byte

	if c.conf.GZip == true {
		buffer = bytes.NewBufferString("")
	}

	for err == nil {
		line, _, err = c.reader.ReadLine()
		if err != nil {
			return err
		}
		size, err = decodeHexString(line)
		if err != nil {
			str := fmt.Sprintf("Expected hex, got %v", string(line))
			return errors.New(str)
		}
		if c.conf.GZip == false {
			_, err = io.CopyN(writer, c.reader, int64(size))
		} else {
			_, err = io.CopyN(buffer, c.reader, int64(size))
			if err != nil {
				return err
			}
			if decompressor == nil {
				decompressor, err = gzip.NewReader(buffer)
				defer decompressor.Close()
				if err != nil {
					return err
				}
				zipReader = bufio.NewReader(decompressor)
			}
			data = make([]byte, 512, 512)
			_, err = zipReader.Read(data)
			if err != nil {
				return err
			}
			strBuffer := bytes.NewBuffer(data)
			io.CopyN(writer, strBuffer, int64(len(data)))
		}
		if c.conf.TTL > 0 {
			if time.Now().Sub(start).Nanoseconds() > c.conf.TTL {
				return nil
			}
		}
	}
	return err
}
Пример #29
0
func (p *ProxyConnection) parseStream(reader *bufio.Reader) error {
	for {
		cmd := types.Command{
			Args: make([]string, 2),
		}

		line, err := reader.ReadString('\n')
		if err != nil {
			return errors.New("Got read error while we don't get arguments count: " + err.Error())
		}

		if line[0] != '*' {
			return errors.New(fmt.Sprintf("First character of client's request is '%s' (expected: '*')", line[0]))
		}

		args_count, err := strconv.Atoi(line[1:])
		if err != nil {
			return errors.New("Can't convert arguments count to integer: " + err.Error())
		}

		for args_count > 0 {
			args_count--

			line, err := reader.ReadString('\n')
			if err != nil {
				return errors.New("Error while reading data from client:" + err.Error())
			}

			log.Println("read: ", string(line))

			// Bulk strings
			if line[0] == '*' {
				length, err := strconv.Atoi(line[1:])
				if err != nil {
					return err
				}
				log.Println("Reading bulk string of length ", length)
				buf := make([]byte, length)
				readed_bytes := 0
				for readed_bytes < length {
					n, err := reader.Read(buf[readed_bytes:])
					if err != nil {
						return err
					}
					readed_bytes += n
					log.Printf("%d out of %d bytes readed", readed_bytes, length)
				}
				arg := string(buf)
				cmd.Args = append(cmd.Args, arg)
				log.Printf("Appending argument: '%s'\n", arg)
			}

		}

		return nil

	}
}
Пример #30
0
func handleCas(firstline string, conn net.Conn, reader *bufio.Reader) error {
	commands := strings.Fields(firstline)
	filename := commands[1]
	if len(commands) < 4 {
		debugServer("Compare and swap: insufficient arguments\n")
		fmt.Fprintf(conn, "%v \r\n", cmderr)
		conn.Close()
		return cmderr
	}
	vers, err := strconv.ParseInt(commands[2], 10, 64)
	if err != nil {
		fmt.Fprintf(conn, "%v \r\n", cmderr)
		conn.Close()
		return cmderr
	}

	numbytes, err := strconv.ParseInt(commands[3], 10, 64)
	if err != nil {
		fmt.Fprintf(conn, "%v \r\n", cmderr)
		conn.Close()
		return cmderr
	}

	var exptime int64 = -1
	if len(commands) == 5 {
		exptime, err = strconv.ParseInt(commands[4], 10, 64)
		if err != nil {
			fmt.Fprintf(conn, "%v \r\n", cmderr)
			conn.Close()
			return cmderr
		}
	}

	var content = make([]byte, numbytes+2)
	n, ok := reader.Read(content)
	if len(content) != n {
		debugServer(fmt.Sprintf("Number of bytes %v not equal to length of content %v in CAS\n", n, len(content)))
	}
	fileMap.RLock()
	curr := fileMap.dict[filename].version
	if curr != vers {
		fileMap.RUnlock()
		fmt.Fprintf(conn, "%v %v \r\n", verserr, curr)
		return verserr
	}
	const modePerm os.FileMode = 0755
	ok = ioutil.WriteFile(filename, content, modePerm)
	if ok != nil {
		fileMap.RUnlock()
		fmt.Fprintf(conn, "%v \r\n", interr)
		return interr
	}
	fileMap.dict[filename].version = curr + 1
	fileMap.dict[filename].exptime = time.Now().Add(time.Duration(exptime) * time.Millisecond)
	fileMap.RUnlock()
	fmt.Fprintf(conn, "OK %v \r\n", curr+1)
	return nil
}