Golang ReadAtLeast示例

说明

golang readatleast示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: io

示例#1
文件: decode.go 项目: RezaDKhan/terraform

func decodeTransliterations() {
	r, err := zlib.NewReader(strings.NewReader(tableData))
	if err != nil {
		panic(err)
	}
	defer r.Close()
	tmp1 := make([]byte, 2)
	tmp2 := tmp1[:1]
	for {
		if _, err := io.ReadAtLeast(r, tmp1, 2); err != nil {
			if err == io.EOF {
				break
			}
			panic(err)
		}
		chr := getUint16(tmp1)
		if _, err := io.ReadAtLeast(r, tmp2, 1); err != nil {
			panic(err)
		}
		b := make([]byte, int(tmp2[0]))
		if _, err := io.ReadFull(r, b); err != nil {
			panic(err)
		}
		transliterations[int(chr)] = []rune(string(b))
	}
}

示例#2
文件: util.go 项目: tomzhang/afero

// readerContains reports whether subslice is within r.
func readerContains(r io.Reader, subslice []byte) bool {

	if r == nil || len(subslice) == 0 {
		return false
	}

	bufflen := len(subslice) * 4
	halflen := bufflen / 2
	buff := make([]byte, bufflen)
	var err error
	var n, i int

	for {
		i++
		if i == 1 {
			n, err = io.ReadAtLeast(r, buff[:halflen], halflen)
		} else {
			if i != 2 {
				// shift left to catch overlapping matches
				copy(buff[:], buff[halflen:])
			}
			n, err = io.ReadAtLeast(r, buff[halflen:], halflen)
		}

		if n > 0 && bytes.Contains(buff, subslice) {
			return true
		}

		if err != nil {
			break
		}
	}
	return false
}

示例#3
文件: testIo.go 项目: shawnpan/learnGo

func testReadAtLeast(fn string) {
	fmt.Println("testReadAtLeast---------------------------------------")
	r, err := os.Open(fn)
	if err != nil {
		fmt.Println("open file error:", fn, err)
		return
	}
	buf := make([]byte, 20)
	defer r.Close()
	_, rerr := io.ReadAtLeast(r, buf, 1)
	for {
		if rerr == nil {
			// fmt.Println(buf)
			fmt.Println(string(buf))
			fmt.Println("######", len(buf))
			_, rerr = io.ReadAtLeast(r, buf, 1)
		} else {
			if rerr == io.EOF {
				fmt.Println(" read at the end!!!")
			} else {
				fmt.Println("read error : ", rerr)
			}
			break
		}
	}
}

示例#4
文件: socks5.go 项目: cosiner/tunnel

func (s *Socks5) serverVerifyUserPass(conn net.Conn) error {
	var req [512]byte
	un, err := io.ReadAtLeast(conn, req[:], 2)
	if err != nil {
		return err
	}
	if req[0] != USER_PASS_VERIFY_VER {
		conn.Write([]byte{USER_PASS_VERIFY_VER, USER_PASS_VERIFY_FAILED})
		return ErrNoProxy
	}
	userLen := int(req[2])
	pn, err := io.ReadAtLeast(conn, req[un:], userLen+1)
	if err != nil {
		return err
	}
	passLen := int(req[userLen+2])
	_, err = io.ReadFull(conn, req[un+pn:3+userLen+passLen])
	if err != nil {
		return err
	}

	user := req[2 : 2+userLen]
	pass := req[3+userLen : 3+userLen+passLen]
	verified := s.userPass.Verify(string(user), string(pass))
	if verified {
		conn.Write([]byte{USER_PASS_VERIFY_VER, USER_PASS_VERIFY_SUCCESS})
		return nil
	}
	conn.Write([]byte{USER_PASS_VERIFY_VER, USER_PASS_VERIFY_FAILED})
	return ErrNoProxy
}

示例#5
文件: markdown.go 项目: tav/planfile-app

func (h *Hilite) Render(lang string, text []byte) ([]byte, error) {
	h.m.Lock()
	defer h.m.Unlock()
	size := make([]byte, 4)
	binary.BigEndian.PutUint32(size, uint32(len(lang)))
	h.w.Write(size)
	h.w.Write([]byte(lang))
	binary.BigEndian.PutUint32(size, uint32(len(text)))
	h.w.Write(size)
	h.w.Write(text)
	_, err := io.ReadAtLeast(h.r, size, 4)
	if err != nil {
		return nil, err
	}
	length := binary.BigEndian.Uint32(size)
	if length == 0 {
		return nil, io.EOF
	}
	out := make([]byte, length)
	_, err = io.ReadAtLeast(h.r, out, int(length))
	if err != nil {
		return nil, err
	}
	return out, nil
}

示例#6
文件: gpaxosprotomarsh.go 项目: WIZARD-CXY/golang-devops-stuff

func (t *PrepareReply) Unmarshal(rr io.Reader) error {
	var wire byteReader
	var ok bool
	if wire, ok = rr.(byteReader); !ok {
		wire = bufio.NewReader(rr)
	}
	var b [10]byte
	var bs []byte
	bs = b[:9]
	if _, err := io.ReadAtLeast(wire, bs, 9); err != nil {
		return err
	}
	t.Balnum = int32((uint32(bs[0]) | (uint32(bs[1]) << 8) | (uint32(bs[2]) << 16) | (uint32(bs[3]) << 24)))
	t.OK = uint8(bs[4])
	t.Ballot = int32((uint32(bs[5]) | (uint32(bs[6]) << 8) | (uint32(bs[7]) << 16) | (uint32(bs[8]) << 24)))
	alen1, err := binary.ReadVarint(wire)
	if err != nil {
		return err
	}
	t.Cstruct = make([]int32, alen1)
	for i := int64(0); i < alen1; i++ {
		bs = b[:4]
		if _, err := io.ReadAtLeast(wire, bs, 4); err != nil {
			return err
		}
		t.Cstruct[i] = int32((uint32(bs[0]) | (uint32(bs[1]) << 8) | (uint32(bs[2]) << 16) | (uint32(bs[3]) << 24)))
	}
	return nil
}

示例#7
文件: cmp.go 项目: niemeyer/snapd

func streamsEqual(fa, fb io.Reader) bool {
	bufa := make([]byte, bufsz)
	bufb := make([]byte, bufsz)
	for {
		ra, erra := io.ReadAtLeast(fa, bufa, bufsz)
		rb, errb := io.ReadAtLeast(fb, bufb, bufsz)
		if erra == io.EOF && errb == io.EOF {
			return true
		}
		if erra != nil || errb != nil {
			// if both files finished in the middle of a
			// ReadAtLeast, (returning io.ErrUnexpectedEOF), then we
			// still need to check what was read to know whether
			// they're equal.  Otherwise, we know they're not equal
			// (because we count any read error as a being non-equal
			// also).
			tailMightBeEqual := erra == io.ErrUnexpectedEOF && errb == io.ErrUnexpectedEOF
			if !tailMightBeEqual {
				return false
			}
		}
		if !bytes.Equal(bufa[:ra], bufb[:rb]) {
			return false
		}
	}
}

示例#8
文件: example_test.go 项目: Greentor/go

func ExampleReadAtLeast() {
	r := strings.NewReader("some io.Reader stream to be read\n")

	buf := make([]byte, 33)
	if _, err := io.ReadAtLeast(r, buf, 4); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s\n", buf)

	// buffer smaller than minimal read size.
	shortBuf := make([]byte, 3)
	if _, err := io.ReadAtLeast(r, shortBuf, 4); err != nil {
		fmt.Println("error:", err)
	}

	// minimal read size bigger than io.Reader stream
	longBuf := make([]byte, 64)
	if _, err := io.ReadAtLeast(r, longBuf, 64); err != nil {
		fmt.Println("error:", err)
	}

	// Output:
	// some io.Reader stream to be read
	//
	// error: short buffer
	// error: EOF
}

示例#9
文件: util.go 项目: clholgat/GoPHS

func GetProto(conn net.Conn) (*comm.OhHai, error) {
	// Read the first 8 bytes.
	buf := make([]byte, 8)
	_, err := io.ReadAtLeast(conn, buf, 8)
	if err != nil {
		return nil, err
	}

	// Convert first 8 bytes to int
	lenbuf := bytes.NewBuffer(buf)
	var length int64
	err = binary.Read(lenbuf, binary.LittleEndian, &length)
	if err != nil {
		panic(err)
	}

	// Get the protobuf from the connection
	buf = make([]byte, length)
	_, err = io.ReadAtLeast(conn, buf, int(length))
	if err != nil {
		return nil, err
	}

	// Unmarshal the protobuf
	message := &comm.OhHai{}
	err = proto.Unmarshal(buf, message)
	if err != nil {
		return nil, err
	}

	return message, nil
}

示例#10
文件: handshake.go 项目: TrevorSStone/gortmp

func HandshakeSample(c net.Conn, br *bufio.Reader, bw *bufio.Writer, timeout time.Duration) (err error) {
	defer func() {
		if r := recover(); r != nil {
			err = r.(error)
		}
	}()
	// Send C0+C1
	err = bw.WriteByte(0x03)
	c1 := CreateRandomBlock(RTMP_SIG_SIZE)
	for i := 0; i < 8; i++ {
		c1[i] = 0
	}
	bw.Write(c1)
	err = bw.Flush()
	CheckError(err, "Handshake() Flush C0+C1")
	// Read S0+S1+S2
	s0, err := br.ReadByte()
	CheckError(err, "Handshake() Read S0")
	if s0 != 0x03 {
		return errors.New(fmt.Sprintf("Handshake() Got S0: %x", s0))
	}
	s1 := make([]byte, RTMP_SIG_SIZE)
	_, err = io.ReadAtLeast(br, s1, RTMP_SIG_SIZE)
	CheckError(err, "Handshake() Read S1")
	bw.Write(s1)
	err = bw.Flush()
	CheckError(err, "Handshake() Flush C2")
	_, err = io.ReadAtLeast(br, s1, RTMP_SIG_SIZE)
	CheckError(err, "Handshake() Read S2")
	return
}

示例#11
文件: epaxosprotomarsh.go 项目: WIZARD-CXY/golang-devops-stuff

func (t *Commit) Unmarshal(rr io.Reader) error {
	var wire byteReader
	var ok bool
	if wire, ok = rr.(byteReader); !ok {
		wire = bufio.NewReader(rr)
	}
	var b [24]byte
	var bs []byte
	bs = b[:12]
	if _, err := io.ReadAtLeast(wire, bs, 12); err != nil {
		return err
	}
	t.LeaderId = int32((uint32(bs[0]) | (uint32(bs[1]) << 8) | (uint32(bs[2]) << 16) | (uint32(bs[3]) << 24)))
	t.Replica = int32((uint32(bs[4]) | (uint32(bs[5]) << 8) | (uint32(bs[6]) << 16) | (uint32(bs[7]) << 24)))
	t.Instance = int32((uint32(bs[8]) | (uint32(bs[9]) << 8) | (uint32(bs[10]) << 16) | (uint32(bs[11]) << 24)))
	alen1, err := binary.ReadVarint(wire)
	if err != nil {
		return err
	}
	t.Command = make([]state.Command, alen1)
	for i := int64(0); i < alen1; i++ {
		t.Command[i].Unmarshal(wire)
	}
	bs = b[:24]
	if _, err := io.ReadAtLeast(wire, bs, 24); err != nil {
		return err
	}
	t.Seq = int32((uint32(bs[0]) | (uint32(bs[1]) << 8) | (uint32(bs[2]) << 16) | (uint32(bs[3]) << 24)))
	t.Deps[0] = int32((uint32(bs[4]) | (uint32(bs[5]) << 8) | (uint32(bs[6]) << 16) | (uint32(bs[7]) << 24)))
	t.Deps[1] = int32((uint32(bs[8]) | (uint32(bs[9]) << 8) | (uint32(bs[10]) << 16) | (uint32(bs[11]) << 24)))
	t.Deps[2] = int32((uint32(bs[12]) | (uint32(bs[13]) << 8) | (uint32(bs[14]) << 16) | (uint32(bs[15]) << 24)))
	t.Deps[3] = int32((uint32(bs[16]) | (uint32(bs[17]) << 8) | (uint32(bs[18]) << 16) | (uint32(bs[19]) << 24)))
	t.Deps[4] = int32((uint32(bs[20]) | (uint32(bs[21]) << 8) | (uint32(bs[22]) << 16) | (uint32(bs[23]) << 24)))
	return nil
}

示例#12
文件: framer.go 项目: Cloven/minikube

// Read attempts to read an entire frame into data. If that is not possible, io.ErrShortBuffer
// is returned and subsequent calls will attempt to read the last frame. A frame is complete when
// err is nil.
func (r *lengthDelimitedFrameReader) Read(data []byte) (int, error) {
	if r.remaining <= 0 {
		header := [4]byte{}
		n, err := io.ReadAtLeast(r.r, header[:4], 4)
		if err != nil {
			return 0, err
		}
		if n != 4 {
			return 0, io.ErrUnexpectedEOF
		}
		frameLength := int(binary.BigEndian.Uint32(header[:]))
		r.remaining = frameLength
	}

	expect := r.remaining
	max := expect
	if max > len(data) {
		max = len(data)
	}
	n, err := io.ReadAtLeast(r.r, data[:max], int(max))
	r.remaining -= n
	if err == io.ErrShortBuffer || r.remaining > 0 {
		return n, io.ErrShortBuffer
	}
	if err != nil {
		return n, err
	}
	if n != expect {
		return n, io.ErrUnexpectedEOF
	}

	return n, nil
}

示例#13
文件: paxosprotomarsh.go 项目: pombredanne/qlease

func (t *Accept) Unmarshal(rr io.Reader) error {
	var wire byteReader
	var ok bool
	if wire, ok = rr.(byteReader); !ok {
		wire = bufio.NewReader(rr)
	}
	var b [12]byte
	var bs []byte
	bs = b[:12]
	if _, err := io.ReadAtLeast(wire, bs, 12); err != nil {
		return err
	}
	t.LeaderId = int32((uint32(bs[0]) | (uint32(bs[1]) << 8) | (uint32(bs[2]) << 16) | (uint32(bs[3]) << 24)))
	t.Instance = int32((uint32(bs[4]) | (uint32(bs[5]) << 8) | (uint32(bs[6]) << 16) | (uint32(bs[7]) << 24)))
	t.Ballot = int32((uint32(bs[8]) | (uint32(bs[9]) << 8) | (uint32(bs[10]) << 16) | (uint32(bs[11]) << 24)))
	alen1, err := binary.ReadVarint(wire)
	if err != nil {
		return err
	}
	t.Command = make([]state.Command, alen1)
	for i := int64(0); i < alen1; i++ {
		t.Command[i].Unmarshal(wire)
	}
	if _, err := io.ReadAtLeast(wire, bs, 12); err != nil {
		return err
	}
	t.LeaseInstance = int32((uint32(bs[0]) | (uint32(bs[1]) << 8) | (uint32(bs[2]) << 16) | (uint32(bs[3]) << 24)))
	t.OriginReplica = int32((uint32(bs[4]) | (uint32(bs[5]) << 8) | (uint32(bs[6]) << 16) | (uint32(bs[7]) << 24)))
	t.PropId = int32((uint32(bs[8]) | (uint32(bs[9]) << 8) | (uint32(bs[10]) << 16) | (uint32(bs[11]) << 24)))
	return nil
}

示例#14
文件: common_test.go 项目: cdecker/btcd

// loadUtxoView returns a utxo view loaded from a file.
func loadUtxoView(filename string) (*blockchain.UtxoViewpoint, error) {
	// The utxostore file format is:
	// <tx hash><serialized utxo len><serialized utxo>
	//
	// The serialized utxo len is a little endian uint32 and the serialized
	// utxo uses the format described in chainio.go.

	filename = filepath.Join("testdata", filename)
	fi, err := os.Open(filename)
	if err != nil {
		return nil, err
	}

	// Choose read based on whether the file is compressed or not.
	var r io.Reader
	if strings.HasSuffix(filename, ".bz2") {
		r = bzip2.NewReader(fi)
	} else {
		r = fi
	}
	defer fi.Close()

	view := blockchain.NewUtxoViewpoint()
	for {
		// Hash of the utxo entry.
		var hash wire.ShaHash
		_, err := io.ReadAtLeast(r, hash[:], len(hash[:]))
		if err != nil {
			// Expected EOF at the right offset.
			if err == io.EOF {
				break
			}
			return nil, err
		}

		// Num of serialize utxo entry bytes.
		var numBytes uint32
		err = binary.Read(r, binary.LittleEndian, &numBytes)
		if err != nil {
			return nil, err
		}

		// Serialized utxo entry.
		serialized := make([]byte, numBytes)
		_, err = io.ReadAtLeast(r, serialized, int(numBytes))
		if err != nil {
			return nil, err
		}

		// Deserialize it and add it to the view.
		utxoEntry, err := blockchain.TstDeserializeUtxoEntry(serialized)
		if err != nil {
			return nil, err
		}
		view.Entries()[hash] = utxoEntry
	}

	return view, nil
}

示例#15
文件: bson_stream.go 项目: devsaurin/mongo-tools

// LoadNext reads and returns the next BSON document in the stream. If the
// BSONSource was created with NewBSONSource then each returned []byte will be
// a slice of a single reused I/O buffer. If the BSONSource was created with
// NewBufferlessBSONSource then each returend []byte will be individually
// allocated
func (bs *BSONSource) LoadNext() []byte {
	var into []byte
	if bs.reusableBuf == nil {
		into = make([]byte, 4)
	} else {
		into = bs.reusableBuf
	}
	// read the bson object size (a 4 byte integer)
	_, err := io.ReadAtLeast(bs.Stream, into[0:4], 4)
	if err != nil {
		if err != io.EOF {
			bs.err = err
			return nil
		}
		// we hit EOF right away, so we're at the end of the stream.
		bs.err = nil
		return nil
	}

	bsonSize := int32(
		(uint32(into[0]) << 0) |
			(uint32(into[1]) << 8) |
			(uint32(into[2]) << 16) |
			(uint32(into[3]) << 24),
	)

	// Verify that the size of the BSON object we are about to read can
	// actually fit into the buffer that was provided. If not, either the BSON is
	// invalid, or the buffer passed in is too small.
	// Verify that we do not have an invalid BSON document with size < 5.
	if bsonSize > MaxBSONSize || bsonSize < 5 {
		bs.err = fmt.Errorf("invalid BSONSize: %v bytes", bsonSize)
		return nil
	}
	if int(bsonSize) > cap(into) {
		bigInto := make([]byte, bsonSize)
		copy(bigInto, into)
		into = bigInto
		if bs.reusableBuf != nil {
			bs.reusableBuf = bigInto
		}
	}
	into = into[:int(bsonSize)]
	_, err = io.ReadAtLeast(bs.Stream, into[4:], int(bsonSize-4))
	if err != nil {
		if err != io.EOF {
			bs.err = err
			return nil
		}
		// this case means we hit EOF but read a partial document,
		// so there's a broken doc in the stream. Treat this as error.
		bs.err = fmt.Errorf("invalid bson: %v", err)
		return nil
	}

	bs.err = nil
	return into
}

示例#16
文件: ricochet.go 项目: s-rah/go-ricochet

// Perform version negotiation on the connection, and create an OpenConnection if successful
func (r *Ricochet) negotiateVersion(conn net.Conn, outbound bool) (*OpenConnection, error) {
	versions := []byte{0x49, 0x4D, 0x01, 0x01}

	// Outbound side of the connection sends a list of supported versions
	if outbound {
		if n, err := conn.Write(versions); err != nil || n < len(versions) {
			return nil, err
		}

		res := make([]byte, 1)
		if _, err := io.ReadAtLeast(conn, res, len(res)); err != nil {
			return nil, err
		}

		if res[0] != 0x01 {
			return nil, errors.New("unsupported protocol version")
		}
	} else {
		// Read version response header
		header := make([]byte, 3)
		if _, err := io.ReadAtLeast(conn, header, len(header)); err != nil {
			return nil, err
		}

		if header[0] != versions[0] || header[1] != versions[1] || header[2] < 1 {
			return nil, errors.New("invalid protocol response")
		}

		// Read list of supported versions (which is header[2] bytes long)
		versionList := make([]byte, header[2])
		if _, err := io.ReadAtLeast(conn, versionList, len(versionList)); err != nil {
			return nil, err
		}

		selectedVersion := byte(0xff)
		for _, v := range versionList {
			if v == 0x01 {
				selectedVersion = v
				break
			}
		}

		if n, err := conn.Write([]byte{selectedVersion}); err != nil || n < 1 {
			return nil, err
		}

		if selectedVersion == 0xff {
			return nil, errors.New("no supported protocol version")
		}
	}

	oc := new(OpenConnection)
	oc.Init(outbound, conn)
	return oc, nil
}

示例#17
文件: demuxer.go 项目: henglinli/goserver

// read message
func (this *Demuxer) read(buffer []byte) {
	//
	defer close(this.forward)
	//
	header := NewTinyHeader()
	//
	var messageSize uint32
	var err error
	var readed int
	//
loop:
	for {
		log.Println("receiving...")
		// read header
		readed, err = io.ReadAtLeast(this.reader,
			header[:],
			len(header))

		if err != nil || readed != len(header) {
			log.Println("read header:", err.Error())
			break loop
		}
		// check maigc
		ok := header.CheckMagic()
		if ok != true {
			log.Println("*Inllegal client, magic:", header.GetMagic())
			break loop
		}
		// get size
		messageSize = header.GetSize()
		// check size
		if this.ValidSize(messageSize) == false {
			log.Println("Message size too big:", messageSize)
			break loop
		}
		// get buffer
		needed := len(buffer) - int(messageSize)
		if needed < 0 {
			log.Println("Growing buffer...")
			buffer = make([]byte, messageSize)
		}
		// get message
		readed, err = io.ReadAtLeast(this.reader, buffer, int(messageSize))
		if err != nil || readed < int(messageSize) {
			log.Println("read message:", err.Error())
			break loop
		}
		// handle message
		input := buffer[0:messageSize]
		output := this.handler.Handle(input, this.session)
		this.forward <- output
	}
	log.Println("Demuxer.Read done")
}

示例#18
文件: main.go 项目: GoesToEleven/golang-web

func main() {
	// unencrypted
	unencrypted := "some message that you want to store / send securely"
	fmt.Println("UNENCRYPTED")
	fmt.Println(unencrypted)
	fmt.Println()

	// encrypt
	var nonce [24]byte
	io.ReadAtLeast(rand.Reader, nonce[:], 24)
	var password [32]byte
	io.ReadAtLeast(rand.Reader, password[:], 32)
	encrypted := secretbox.Seal(nil, []byte(unencrypted), &nonce, &password)
	fmt.Println("ENCRYPTED")
	fmt.Println(encrypted)
	fmt.Println()

	// decrypt
	enHex := fmt.Sprintf("%x:%x", nonce[:], encrypted)
	fmt.Println("NONCE:ENCRYPTED")
	fmt.Println(enHex)
	fmt.Println()

	var nonce2 [24]byte
	parts := strings.SplitN(enHex, ":", 2)
	if len(parts) < 2 {
		fmt.Errorf("expected nonce")
	}
	bs, err := hex.DecodeString(parts[0])
	if err != nil || len(bs) != 24 {
		fmt.Errorf("invalid nonce")
	}
	copy(nonce2[:], bs)
	fmt.Println("NONCE")
	fmt.Println(nonce)
	fmt.Println("NONCE2")
	fmt.Println(nonce2)
	fmt.Println()

	// get message
	bs, err = hex.DecodeString(parts[1])
	if err != nil {
		fmt.Errorf("invalid message")
	}

	// you need the password to open the sealed secret box
	decrypted, ok := secretbox.Open(nil, bs, &nonce2, &password)
	if !ok {
		fmt.Errorf("invalid message")
	}
	fmt.Println("DECRYPTED")
	fmt.Println(string(decrypted))
}

示例#19
文件: session.go 项目: henglinli/goserver

// read message
func (this *AddrSession) read(buffer []byte) {
	//
	defer close(this.forward)
	//
	var messageSize uint32
	var err error
	var readed int
	//
loop:
	for {
		log.Println("receiving...")
		// read header
		readed, err = io.ReadAtLeast(this.reader,
			this.rheader[:],
			len(this.rheader))

		if err != nil || readed != len(this.rheader) {
			log.Println("read header:", err.Error())
			break loop
		}
		/*
			// check maigc
			ok := rheader.CheckMagic()
			if ok != true {
				break loop
			}
		*/
		// get size
		messageSize = this.rheader.GetSize()
		// check size
		if this.ValidSize(messageSize) == false {
			log.Println("Message size too big:", messageSize)
			break loop
		}
		// get buffer
		needed := len(buffer) - int(messageSize)
		if needed < 0 {
			log.Println("Growing buffer...")
			buffer = make([]byte, messageSize)
		}
		// get message
		readed, err = io.ReadAtLeast(this.reader, buffer, int(messageSize))
		if err != nil || readed < int(messageSize) {
			log.Println("read message:", err.Error())
			break loop
		}
		// handle message
		input := buffer[0:messageSize]
		this.forward <- this.handler.Handle(input, this)
	}
	log.Println("Session.Read done")
}

示例#20
文件: auth.go 项目: xiaokangwang/go-socks5

func (a UserPassAuthenticator) Authenticate(reader io.Reader, writer io.Writer) error {
	// Tell the client to use user/pass auth
	if _, err := writer.Write([]byte{socks5Version, userPassAuth}); err != nil {
		return err
	}

	// Get the version and username length
	header := []byte{0, 0}
	if _, err := io.ReadAtLeast(reader, header, 2); err != nil {
		return err
	}

	// Ensure we are compatible
	if header[0] != userAuthVersion {
		return fmt.Errorf("Unsupported auth version: %v", header[0])
	}

	// Get the user name
	userLen := int(header[1])
	user := make([]byte, userLen)
	if _, err := io.ReadAtLeast(reader, user, userLen); err != nil {
		return err
	}

	// Get the password length
	if _, err := reader.Read(header[:1]); err != nil {
		return err
	}

	// Get the password
	passLen := int(header[0])
	pass := make([]byte, passLen)
	if _, err := io.ReadAtLeast(reader, pass, passLen); err != nil {
		return err
	}

	// Verify the password
	if a.Credentials.Valid(string(user), string(pass)) {
		if _, err := writer.Write([]byte{userAuthVersion, authSuccess}); err != nil {
			return err
		}
	} else {
		if _, err := writer.Write([]byte{userAuthVersion, authFailure}); err != nil {
			return err
		}
		return UserAuthFailed
	}

	// Done
	return nil

}

示例#21
文件: test_client.go 项目: henglinli/goserver

func (this *Client) read(conn net.Conn) {
	defer close(this.incoming)
	defer conn.Close()
	//
	var messageSize uint32
	var err error
	var readed int
	var buffer []byte
	this.reader = bufio.NewReader(conn)
	//
loop:
	for {
		// wait cann recv
		<-this.incoming
		//
		log.Println("receiving...")
		// read boundary
		readed, err = io.ReadAtLeast(this.reader,
			this.rheader[:],
			len(this.rheader))
		if err != nil || readed < 4 {
			log.Println("read bondary:", err.Error())
			break loop
		}
		// get size and type
		messageSize = this.rheader.GetSize()
		log.Println("message size:", messageSize)
		// get buffer
		needed := len(buffer) - int(messageSize)
		if needed < 0 {
			log.Println("Growing buffer...")
			buffer = make([]byte, messageSize)
		}
		// get message
		readed, err = io.ReadAtLeast(this.reader, buffer, int(messageSize))
		if err != nil || readed < int(messageSize) {
			log.Println("read message:", err.Error())
			break loop
		}
		response := &message.Response{}
		message := buffer[0:readed]
		err := proto.Unmarshal(message, response)
		if err != nil {
			log.Println(err.Error())
		} else {
			log.Println(response.GetStatus())
		}
	}
	this.outgoing <- "closed"
}

示例#22
文件: util.go 项目: NetSys/quilt

// readerContains reports whether any of the subslices is within r.
func readerContainsAny(r io.Reader, subslices ...[]byte) bool {

	if r == nil || len(subslices) == 0 {
		return false
	}

	largestSlice := 0

	for _, sl := range subslices {
		if len(sl) > largestSlice {
			largestSlice = len(sl)
		}
	}

	if largestSlice == 0 {
		return false
	}

	bufflen := largestSlice * 4
	halflen := bufflen / 2
	buff := make([]byte, bufflen)
	var err error
	var n, i int

	for {
		i++
		if i == 1 {
			n, err = io.ReadAtLeast(r, buff[:halflen], halflen)
		} else {
			if i != 2 {
				// shift left to catch overlapping matches
				copy(buff[:], buff[halflen:])
			}
			n, err = io.ReadAtLeast(r, buff[halflen:], halflen)
		}

		if n > 0 {
			for _, sl := range subslices {
				if bytes.Contains(buff, sl) {
					return true
				}
			}
		}

		if err != nil {
			break
		}
	}
	return false
}

示例#23
文件: swaplabel.go 项目: qeedquan/misc_utilities

func main() {
	log.SetFlags(0)
	log.SetPrefix("swaplabel: ")

	flag.Usage = usage
	flag.Parse()
	if flag.NArg() < 1 {
		usage()
	}
	device := flag.Arg(0)

	f, err := os.OpenFile(device, os.O_RDWR, 0644)
	ck(err)
	defer f.Close()

	_, err = f.Seek(SWAP_MAGIC_OFFSET, io.SeekStart)
	ck(err)

	var magic [SWAP_MAGIC_LENGTH]byte
	_, err = io.ReadAtLeast(f, magic[:], len(magic))
	ck(err)

	if string(magic[:]) != SWAP_MAGIC1 && string(magic[:]) != SWAP_MAGIC2 {
		log.Fatalf("%s: is not a swap partition", device)
	}

	_, err = f.Seek(SWAP_LABEL_OFFSET, io.SeekStart)
	ck(err)

	if *label == "" {
		var buf [SWAP_LABEL_LENGTH]byte
		_, err = io.ReadAtLeast(f, buf[:], len(buf))
		ck(err)

		for i := range buf {
			if i == SWAP_LABEL_LENGTH-1 && buf[i] != 0 {
				log.Fatal("invalid label")
			}
		}
		fmt.Println(strings.TrimRight(string(buf[:]), "\x00"))
	} else {
		if len(*label)+1 > SWAP_LABEL_LENGTH {
			log.Fatal("label too long")
		}
		_, err = f.Write([]byte(*label + "\x00"))
		ck(err)
	}

	syscall.Fsync(int(f.Fd()))
}

示例#24
文件: main.go 项目: GoesToEleven/golang-web

func main() {
	decrypted := "some message that has not yet been encrypted."
	// the nonce must be unique for every message encrypted
	var nonce [24]byte
	io.ReadAtLeast(rand.Reader, nonce[:], 24)
	// the password must be unique for every message encrypted
	var password [32]byte
	io.ReadAtLeast(rand.Reader, password[:], 32)
	encrypted := secretbox.Seal(nil, []byte(decrypted), &nonce, &password)
	fmt.Println("-----DECRYPTED-----")
	fmt.Println(decrypted)
	fmt.Println("-----ENCRYPTED-----")
	fmt.Println("encrypted", encrypted)
}

示例#25
文件: request.go 项目: xiaokangwang/go-socks5

// readAddrSpec is used to read AddrSpec.
// Expects an address type byte, follwed by the address and port
func readAddrSpec(r io.Reader) (*AddrSpec, error) {
	d := &AddrSpec{}

	// Get the address type
	addrType := []byte{0}
	if _, err := r.Read(addrType); err != nil {
		return nil, err
	}

	// Handle on a per type basis
	switch addrType[0] {
	case ipv4Address:
		addr := make([]byte, 4)
		if _, err := io.ReadAtLeast(r, addr, len(addr)); err != nil {
			return nil, err
		}
		d.IP = net.IP(addr)

	case ipv6Address:
		addr := make([]byte, 16)
		if _, err := io.ReadAtLeast(r, addr, len(addr)); err != nil {
			return nil, err
		}
		d.IP = net.IP(addr)

	case fqdnAddress:
		if _, err := r.Read(addrType); err != nil {
			return nil, err
		}
		addrLen := int(addrType[0])
		fqdn := make([]byte, addrLen)
		if _, err := io.ReadAtLeast(r, fqdn, addrLen); err != nil {
			return nil, err
		}
		d.FQDN = string(fqdn)

	default:
		return nil, unrecognizedAddrType
	}

	// Read the port
	port := []byte{0, 0}
	if _, err := io.ReadAtLeast(r, port, 2); err != nil {
		return nil, err
	}
	d.Port = (int(port[0]) << 8) | int(port[1])

	return d, nil
}

示例#26
文件: decode.go 项目: MG-RAST/Shock

func (z *ioDecReader) readn(n int) (bs []byte) {
	bs = make([]byte, n)
	if _, err := io.ReadAtLeast(z.r, bs, n); err != nil {
		panic(err)
	}
	return
}

示例#27
文件: local.go 项目: stefanie924/shadowsocks-go-1

func handShake(conn net.Conn) (err error) {
	const (
		idVer     = 0
		idNmethod = 1
	)
	// version identification and method selection message in theory can have
	// at most 256 methods, plus version and nmethod field in total 258 bytes
	// the current rfc defines only 3 authentication methods (plus 2 reserved),
	// so it won't be such long in practice

	buf := make([]byte, 258)

	var n int
	// make sure we get the nmethod field
	if n, err = io.ReadAtLeast(conn, buf, idNmethod+1); err != nil {
		return
	}
	if buf[idVer] != socksVer5 {
		return errVer
	}
	nmethod := int(buf[idNmethod])
	msgLen := nmethod + 2
	if n == msgLen { // handshake done, common case
		// do nothing, jump directly to send confirmation
	} else if n < msgLen { // has more methods to read, rare case
		if _, err = io.ReadFull(conn, buf[n:msgLen]); err != nil {
			return
		}
	} else { // error, should not get extra data
		return errAuthExtraData
	}
	// send confirmation: version 5, no authentication required
	_, err = conn.Write([]byte{socksVer5, 0})
	return
}

示例#28
文件: dial.go 项目: billyboar/GCSolutions

// Dial generates a private/public key pair,
// connects to the server, perform the handshake
// and return a reader/writer.
func Dial(addr string) (io.ReadWriteCloser, error) {

	// Generate key pair for client
	cpub, cpriv, _ := box.GenerateKey(rand.Reader)

	// Attempt to connect to server
	conn, err := net.Dial("tcp", addr)
	if err != nil {
		log.Println("Could not make connection with server...")
		log.Fatal(err)
	}

	// Get server's public key
	var spub [32]byte
	_, err = io.ReadAtLeast(conn, spub[:], 32)
	if err != nil {
		log.Println("Could not get server's public key...")
		log.Fatal(err)
	}

	// Send client's public key
	key := [32]byte(*cpub)
	_, err = conn.Write(key[:])
	if err != nil {
		log.Println("Could not send public key to server...")
		log.Fatal(err)
	}

	// Return client a reader/writer
	r := NewSecureReader(conn, cpriv, &spub)
	w := NewSecureWriter(conn, cpriv, &spub)
	c := NewSecureCloser(conn)
	srwc := NewSecureReadWriteCloser(r, w, c)
	return srwc, err
}

示例#29
文件: prelude.go 项目: Machyne/mongo

// Read consumes and checks the magic number at the beginning of the archive,
// then it runs the parser with a Prelude as its consumer.
func (prelude *Prelude) Read(in io.Reader) error {
	readMagicNumberBuf := make([]byte, 4)
	_, err := io.ReadAtLeast(in, readMagicNumberBuf, 4)
	if err != nil {
		return fmt.Errorf("I/O failure reading beginning of archive: %v", err)
	}
	readMagicNumber := uint32(
		(uint32(readMagicNumberBuf[0]) << 0) |
			(uint32(readMagicNumberBuf[1]) << 8) |
			(uint32(readMagicNumberBuf[2]) << 16) |
			(uint32(readMagicNumberBuf[3]) << 24),
	)

	if readMagicNumber != MagicNumber {
		return fmt.Errorf("stream or file does not appear to be a mongodump archive")
	}

	if prelude.NamespaceMetadatasByDB != nil {
		prelude.NamespaceMetadatasByDB = make(map[string][]*CollectionMetadata, 0)
	}

	parser := Parser{In: in}
	parserConsumer := &preludeParserConsumer{prelude: prelude}
	return parser.ReadBlock(parserConsumer)
}

示例#30
文件: deflate.go 项目: GNA-SERVICES-INC/MoNGate

func (d *compressor) fillWindow(index int) (int, os.Error) {
	wSize := d.windowMask + 1
	if index >= wSize+wSize-(minMatchLength+maxMatchLength) {
		// shift the window by wSize
		copy(d.window, d.window[wSize:2*wSize])
		index -= wSize
		d.windowEnd -= wSize
		if d.blockStart >= wSize {
			d.blockStart -= wSize
		} else {
			d.blockStart = math.MaxInt32
		}
		for i, h := range d.hashHead {
			d.hashHead[i] = max(h-wSize, -1)
		}
		for i, h := range d.hashPrev {
			d.hashPrev[i] = max(h-wSize, -1)
		}
	}
	var count int
	var err os.Error
	count, err = io.ReadAtLeast(d.r, d.window[d.windowEnd:], 1)
	d.windowEnd += count
	if err == os.EOF {
		return index, nil
	}
	return index, err
}

展开阅读全文