Beispiel #1
2
// bigIntToNetIPv6 is a helper function that correctly returns a net.IP with the
// correctly padded values.
func bigIntToNetIPv6(bi *big.Int) *net.IP {
	x := make(net.IP, IPv6len)
	ipv6Bytes := bi.Bytes()

	// It's possibe for ipv6Bytes to be less than IPv6len bytes in size.  If
	// they are different sizes we to pad the size of response.
	if len(ipv6Bytes) < IPv6len {
		buf := new(bytes.Buffer)
		buf.Grow(IPv6len)

		for i := len(ipv6Bytes); i < IPv6len; i++ {
			if err := binary.Write(buf, binary.BigEndian, byte(0)); err != nil {
				panic(fmt.Sprintf("Unable to pad byte %d of input %v: %v", i, bi, err))
			}
		}

		for _, b := range ipv6Bytes {
			if err := binary.Write(buf, binary.BigEndian, b); err != nil {
				panic(fmt.Sprintf("Unable to preserve endianness of input %v: %v", bi, err))
			}
		}

		ipv6Bytes = buf.Bytes()
	}
	i := copy(x, ipv6Bytes)
	if i != IPv6len {
		panic("IPv6 wrong size")
	}
	return &x
}
Beispiel #2
0
func (obj GCAddEffectPacket) Write(buf io.Writer, code uint8) error {

	binary.Write(buf, binary.LittleEndian, obj.ObjectID)
	binary.Write(buf, binary.LittleEndian, obj.EffectID)
	binary.Write(buf, binary.LittleEndian, obj.Duration)
	return nil
}
Beispiel #3
0
func (e *indexEntry) WriteTo(w io.Writer) (n int64, err error) {
	deleted := byte(0)
	if e.deleted {
		deleted = 1
	}

	if err = binary.Write(w, binary.BigEndian, deleted); err != nil {
		return 0, err
	}

	value_len := uint32(len(e.value))
	if err = binary.Write(w, binary.BigEndian, value_len); err != nil {
		return 0, err
	}

	if err = binary.Write(w, binary.BigEndian, []byte(e.value)); err != nil {
		return 0, err
	}

	if err = binary.Write(w, binary.BigEndian, e.id); err != nil {
		return 0, err
	}

	return int64(binary.Size(deleted) + binary.Size([]byte(e.value)) + binary.Size(e.id)), nil
}
Beispiel #4
0
func (client *Client) WriteEMessage(emsg *EMessage) []byte {
	buffer := new(bytes.Buffer)
	binary.Write(buffer, binary.BigEndian, emsg.msgid)
	binary.Write(buffer, binary.BigEndian, emsg.device_id)
	SendMessage(buffer, emsg.msg)
	return buffer.Bytes()
}
Beispiel #5
0
func serializeV1PrecertSCTSignatureInput(timestamp uint64, issuerKeyHash [issuerKeyHashLength]byte, tbs []byte, ext CTExtensions) ([]byte, error) {
	if err := checkCertificateFormat(tbs); err != nil {
		return nil, err
	}
	if err := checkExtensionsFormat(ext); err != nil {
		return nil, err
	}
	var buf bytes.Buffer
	if err := binary.Write(&buf, binary.BigEndian, V1); err != nil {
		return nil, err
	}
	if err := binary.Write(&buf, binary.BigEndian, CertificateTimestampSignatureType); err != nil {
		return nil, err
	}
	if err := binary.Write(&buf, binary.BigEndian, timestamp); err != nil {
		return nil, err
	}
	if err := binary.Write(&buf, binary.BigEndian, PrecertLogEntryType); err != nil {
		return nil, err
	}
	if _, err := buf.Write(issuerKeyHash[:]); err != nil {
		return nil, err
	}
	if err := writeVarBytes(&buf, tbs, CertificateLengthBytes); err != nil {
		return nil, err
	}
	if err := writeVarBytes(&buf, ext, ExtensionsLengthBytes); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}
Beispiel #6
0
// SerializeTimestampedEntry writes timestamped entry to Writer.
// In case of error, w may contain garbage.
func SerializeTimestampedEntry(w io.Writer, t *TimestampedEntry) error {
	if err := binary.Write(w, binary.BigEndian, t.Timestamp); err != nil {
		return err
	}
	if err := binary.Write(w, binary.BigEndian, t.EntryType); err != nil {
		return err
	}
	switch t.EntryType {
	case X509LogEntryType:
		if err := writeVarBytes(w, t.X509Entry, CertificateLengthBytes); err != nil {
			return err
		}
	case PrecertLogEntryType:
		if err := binary.Write(w, binary.BigEndian, t.PrecertEntry.IssuerKeyHash); err != nil {
			return err
		}
		if err := writeVarBytes(w, t.PrecertEntry.TBSCertificate, PreCertificateLengthBytes); err != nil {
			return err
		}
	case XJSONLogEntryType:
		// TODO: Pending google/certificate-transparency#1243, replace
		// with ObjectHash once supported by CT server.
		//jsonhash := objecthash.CommonJSONHash(string(t.JSONData))
		if err := writeVarBytes(w, []byte(t.JSONData), JSONLengthBytes); err != nil {
			return err
		}
	default:
		return fmt.Errorf("unknown EntryType: %d", t.EntryType)
	}
	writeVarBytes(w, t.Extensions, ExtensionsLengthBytes)
	return nil
}
Beispiel #7
0
func MarshalPacket(pack interface{}) ([]byte, error) {
	et := typetest(pack)
	if et < EncodingTypeNil || et > EncodingTypeMax {
		return nil, errors.New("MarshalPacket unkown data type")
	}

	if encodingArray[et] == nil {
		return nil, errors.New("MarshalPacket unkown data type")
	}

	data, err := encodingArray[et].Marshal(pack)
	if err != nil {
		return nil, fmt.Errorf("%v %v", pack, err.Error())
	}

	packetid, err := getPacketId(pack)
	if err != nil {
		return nil, fmt.Errorf("%v %v", pack, err.Error())
	}

	ph := PacketHeader{
		EncodeType: int16(et),
		PacketId:   int16(packetid),
	}

	w := bytes.NewBuffer(nil)
	binary.Write(w, binary.LittleEndian, &ph)
	binary.Write(w, binary.LittleEndian, data)
	return w.Bytes(), nil
}
Beispiel #8
0
func (this *DataPackage) Package() []byte {
	buf := new(bytes.Buffer)
	binary.Write(buf, binary.BigEndian, this.Head)
	binary.Write(buf, binary.BigEndian, this.Body)
	binary.Write(buf, binary.BigEndian, this.Tail)
	return buf.Bytes()
}
Beispiel #9
0
func cipherPacket(cmd uint8, data []byte) []byte {
	buf := new(bytes.Buffer)
	binary.Write(buf, binary.BigEndian, cmd)
	binary.Write(buf, binary.BigEndian, uint16(len(data)))
	buf.Write(data)
	return buf.Bytes()
}
Beispiel #10
0
func (w *Writer) flushIndex() error {
	w.trailer.DataIndexOffset = w.curOffset
	w.trailer.DataIndexCount = uint32(len(w.blocks))

	w.fp.Write(IndexMagic)
	w.curOffset += uint64(len(IndexMagic))

	for _, b := range w.blocks {
		if err := binary.Write(w.fp, binary.BigEndian, b.offset); err != nil {
			return err
		}
		w.curOffset += uint64(binary.Size(b.offset))

		if err := binary.Write(w.fp, binary.BigEndian, b.size); err != nil {
			return err
		}
		w.curOffset += uint64(binary.Size(b.size))

		if i, err := writeUvarint(w.fp, uint64(len(b.firstKeyBytes))); err != nil {
			return err
		} else {
			w.curOffset += uint64(i)
		}

		if i, err := w.fp.Write(b.firstKeyBytes); err != nil {
			return err
		} else {
			w.curOffset += uint64(i)
		}
	}

	return nil
}
func (space *Space) Call(procName string, returnTuple bool, args ...TupleField) (tuples [][][]byte, err error) {
	body := new(bytes.Buffer)
	flags := BoxFlags

	if returnTuple == true {
		flags |= BoxReturnTuple
	}

	err = binary.Write(body, binary.LittleEndian, flags)
	if err != nil {
		return
	}

	err = String(procName).Pack(body)
	if err != nil {
		return
	}

	err = binary.Write(body, binary.LittleEndian, int32(len(args)))
	if err != nil {
		return
	}

	for _, field := range args {
		field.Pack(body)
	}

	tuples, err = space.request(CallOp, body)
	return
}
// Refactor: same as Insert but Op number
func (space *Space) Delete(tuple []TupleField, returnTuple bool) (tuples [][][]byte, err error) {
	body := new(bytes.Buffer)
	flags := BoxFlags

	if returnTuple == true {
		flags |= BoxReturnTuple
	}

	requestBody := []int32{space.spaceNo, flags}
	err = binary.Write(body, binary.LittleEndian, requestBody)
	if err != nil {
		return
	}

	err = binary.Write(body, binary.LittleEndian, int32(len(tuple)))
	if err != nil {
		return
	}

	for _, field := range tuple {
		field.Pack(body)
	}

	tuples, err = space.request(DeleteOp, body)
	return
}
func (m *EntryBlockResponse) MarshalForSignature() ([]byte, error) {
	var buf primitives.Buffer

	binary.Write(&buf, binary.BigEndian, m.Type())

	t := m.GetTimestamp()
	data, err := t.MarshalBinary()
	if err != nil {
		return nil, err
	}
	buf.Write(data)

	m.EBlockCount = uint32(len(m.EBlocks))
	binary.Write(&buf, binary.BigEndian, m.EBlockCount)
	for _, eb := range m.EBlocks {
		bin, err := eb.MarshalBinary()
		if err != nil {
			return nil, err
		}
		buf.Write(bin)
	}

	m.EntryCount = uint32(len(m.Entries))
	binary.Write(&buf, binary.BigEndian, m.EntryCount)
	for _, e := range m.Entries {
		bin, err := e.MarshalBinary()
		if err != nil {
			return nil, err
		}
		buf.Write(bin)
	}

	return buf.DeepCopyBytes(), nil
}
Beispiel #14
0
func (move GCMovePacket) Write(buf io.Writer, code uint8) error {
	binary.Write(buf, binary.LittleEndian, move.ObjectID)
	binary.Write(buf, binary.LittleEndian, move.X)
	binary.Write(buf, binary.LittleEndian, move.Y)
	binary.Write(buf, binary.LittleEndian, move.Dir)
	return nil
}
Beispiel #15
0
func (failed *GCSkillFailed1Packet) Write(buf io.Writer, code uint8) error {

	binary.Write(buf, binary.LittleEndian, failed.SkillType)
	binary.Write(buf, binary.LittleEndian, failed.Grade)
	failed.Dump(buf)
	return nil
}
Beispiel #16
0
func writeNumber(b io.Writer, num int) (err error) {
	// The first two bits encode the size:
	// 00 = 1 byte
	// 01 = 2 bytes
	// 10 = 3 bytes
	// 11 = 4 bytes
	switch {
	case num < 64: // 2^(8-2)
		// Fits in one byte.
		binary.Write(b, binary.BigEndian, uint8(num))
	case num < 16384: // 2^(16-2)
		// Fits in two bytes.
		binary.Write(b, binary.BigEndian, uint16(num|0x4000)) // Set the size to 01.
	case num < 4194304: // 2^(24-2)
		// Fits in three bytes.
		// Drop the two least significant bytes and set the size to 10.
		binary.Write(b, binary.BigEndian, uint8((num>>16)|0x80))
		// Drop the two most significant bytes.
		binary.Write(b, binary.BigEndian, uint16(num&0xffff))
	case num < 1073741824: // 2^(32-2):
		// Fits in four bytes.
		// Set the size to 11.
		binary.Write(b, binary.BigEndian, uint32(num|0xc0000000))
	default:
		err = fmt.Errorf("Number is too big: %d", num)
	}
	return err
}
Beispiel #17
0
// Writes the tny_page to the specified writer.  We want to do this
// in Go so that we can write a page to local disk, Hadoop, S3, etc
func (self *TnyPage) WritePage(writer *bufio.Writer) {
	// Lets write out the page...

	// fmt.Printf("Writing page for %s (ptr: %p, len: %d):\n", self.Column.Name, self.cptr, self.Length())

	if err := binary.Write(writer, binary.LittleEndian, int32(self.Depth())); err != nil {
		panic("Unable to write page header (depth) (" + err.Error() + ")")
	}

	if err := binary.Write(writer, binary.LittleEndian, int32(self.Length())); err != nil {
		panic("Unable to write page header (length) (" + err.Error() + ")")
	}

	// fmt.Printf("Wrote header, writing data now...\n")

	for d := 0; d < int(self.Depth()); d++ {
		bmp := self.BitmapAtDepth(d)
		bmpSlice := bmp.Slice()

		// fmt.Printf("\t%s\n", bmp.BitString(100))

		// fmt.Printf("Writing slice %d...\n", d)

		if err := binary.Write(writer, binary.LittleEndian, bmpSlice); err != nil {
			panic("Unable to write page (" + err.Error() + ")")
		}

	}
	// fmt.Printf("Write Page (%d): ", depth)
	// for i := 0; i < 10; i++ {
	// 	fmt.Printf("%d, ", self.Access(i))
	// }
	// fmt.Printf("\n")
}
Beispiel #18
0
func (m *JointTrajectory) Serialize(w io.Writer) (err error) {
	if err = ros.SerializeMessageField(w, "Header", &m.Header); err != nil {
		return err
	}

	// Write size little endian
	err = binary.Write(w, binary.LittleEndian, uint32(len(m.JointNames)))
	if err != nil {
		return fmt.Errorf("could not write array length: %s", err)
	}
	for _, elem := range m.JointNames {
		if err = ros.SerializeMessageField(w, "string", &elem); err != nil {
			return err
		}
	}

	// Write size little endian
	err = binary.Write(w, binary.LittleEndian, uint32(len(m.Points)))
	if err != nil {
		return fmt.Errorf("could not write array length: %s", err)
	}
	for _, elem := range m.Points {
		if err = ros.SerializeMessageField(w, "JointTrajectoryPoint", &elem); err != nil {
			return err
		}
	}

	return
}
Beispiel #19
0
// 打包
func PackageData(head PkgHead, body []byte, tail InnerPkgTail) *bytes.Buffer {
	buf := new(bytes.Buffer)
	binary.Write(buf, binary.BigEndian, head)
	binary.Write(buf, binary.BigEndian, body)
	binary.Write(buf, binary.BigEndian, tail)
	return buf
}
Beispiel #20
0
func NewSprite(vertices []float32, program *gg.Program, texture *gg.Texture) (*Sprite, error) {
	buf := new(bytes.Buffer)
	if err := binary.Write(buf, binary.LittleEndian, vertices); err != nil {
		return nil, err
	}
	pvbo := gg.CreateBuffer()
	gg.BindBuffer(gg.ARRAY_BUFFER, pvbo)
	gg.BufferData(gg.ARRAY_BUFFER, buf.Bytes(), gg.STATIC_DRAW)

	texVertices := []float32{
		0, 0,
		0, 1,
		1, 1,
		1, 0,
	}
	buf.Reset()
	if err := binary.Write(buf, binary.LittleEndian, texVertices); err != nil {
		return nil, err
	}
	tvbo := gg.CreateBuffer()
	gg.BindBuffer(gg.ARRAY_BUFFER, tvbo)
	gg.BufferData(gg.ARRAY_BUFFER, buf.Bytes(), gg.STATIC_DRAW)

	return &Sprite{
		pvbo:    pvbo,
		tvbo:    tvbo,
		program: program,
		tex:     texture,
	}, nil
}
Beispiel #21
0
func decryptAES(src, key, privParam []byte, engineBoots, engineTime int32) (
	dst []byte, err error) {

	if len(privParam) != 8 {
		err = ArgumentError{
			Value:   len(privParam),
			Message: "Invalid AES PrivParameter length",
		}
		return
	}

	block, err := aes.NewCipher(key[:16])
	if err != nil {
		return
	}

	var buf bytes.Buffer
	binary.Write(&buf, binary.BigEndian, engineBoots)
	binary.Write(&buf, binary.BigEndian, engineTime)
	iv := append(buf.Bytes(), privParam...)

	dst = make([]byte, len(src))

	mode := cipher.NewCFBDecrypter(block, iv)
	mode.XORKeyStream(dst, src)
	return
}
Beispiel #22
0
func (e *Entry) MarshalBinary() ([]byte, error) {
	buf := new(bytes.Buffer)

	// 1 byte Version
	if err := binary.Write(buf, binary.BigEndian, e.Version); err != nil {
		return buf.Bytes(), err
	}

	// 32 byte ChainID
	buf.Write(e.ChainID.Bytes())

	// ExtIDs
	if ext, err := e.MarshalExtIDsBinary(); err != nil {
		return buf.Bytes(), err
	} else {
		// 2 byte size of ExtIDs
		if err := binary.Write(buf, binary.BigEndian, int16(len(ext))); err != nil {
			return buf.Bytes(), err
		}

		// binary ExtIDs
		buf.Write(ext)
	}

	// Content
	buf.Write(e.Content)

	return buf.Bytes(), nil
}
Beispiel #23
0
func serializeV1CertSCTSignatureInput(timestamp uint64, cert ASN1Cert, ext CTExtensions) ([]byte, error) {
	if err := checkCertificateFormat(cert); err != nil {
		return nil, err
	}
	if err := checkExtensionsFormat(ext); err != nil {
		return nil, err
	}
	var buf bytes.Buffer
	if err := binary.Write(&buf, binary.BigEndian, V1); err != nil {
		return nil, err
	}
	if err := binary.Write(&buf, binary.BigEndian, CertificateTimestampSignatureType); err != nil {
		return nil, err
	}
	if err := binary.Write(&buf, binary.BigEndian, timestamp); err != nil {
		return nil, err
	}
	if err := binary.Write(&buf, binary.BigEndian, X509LogEntryType); err != nil {
		return nil, err
	}
	if err := writeVarBytes(&buf, cert, CertificateLengthBytes); err != nil {
		return nil, err
	}
	if err := writeVarBytes(&buf, ext, ExtensionsLengthBytes); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}
Beispiel #24
0
func (pack *TxPack) Serialize() ([]byte, error) {
	var buff bytes.Buffer
	var err error
	err = binary.Write(&buff, binary.LittleEndian, pack.Time)
	if err != nil {
		return nil, err
	}

	err = binary.Write(&buff, binary.LittleEndian, pack.Height)
	if err != nil {
		return nil, err
	}

	err = binary.Write(&buff, binary.LittleEndian, uint32(len(pack.Txs)))
	if err != nil {
		return nil, err
	}

	for _, tx := range pack.Txs {
		var b bytes.Buffer
		tx.MsgTx().Serialize(&b)

		err = binary.Write(&buff, binary.LittleEndian, uint32(b.Len()))
		if err != nil {
			return nil, err
		}

		err = binary.Write(&buff, binary.LittleEndian, b.Bytes())
		if err != nil {
			return nil, err
		}

	}
	return buff.Bytes(), nil
}
Beispiel #25
0
func serializeV1STHSignatureInput(sth SignedTreeHead) ([]byte, error) {
	if sth.Version != V1 {
		return nil, fmt.Errorf("invalid STH version %d", sth.Version)
	}
	if sth.TreeSize < 0 {
		return nil, fmt.Errorf("invalid tree size %d", sth.TreeSize)
	}
	if len(sth.SHA256RootHash) != crypto.SHA256.Size() {
		return nil, fmt.Errorf("invalid TreeHash length, got %d expected %d", len(sth.SHA256RootHash), crypto.SHA256.Size())
	}

	var buf bytes.Buffer
	if err := binary.Write(&buf, binary.BigEndian, V1); err != nil {
		return nil, err
	}
	if err := binary.Write(&buf, binary.BigEndian, TreeHashSignatureType); err != nil {
		return nil, err
	}
	if err := binary.Write(&buf, binary.BigEndian, sth.Timestamp); err != nil {
		return nil, err
	}
	if err := binary.Write(&buf, binary.BigEndian, sth.TreeSize); err != nil {
		return nil, err
	}
	if err := binary.Write(&buf, binary.BigEndian, sth.SHA256RootHash); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}
Beispiel #26
0
// MultiPublish creates a new Command to write more than one message to a given topic.
// This is useful for high-throughput situations to avoid roundtrips and saturate the pipe.
func MultiPublish(topic string, bodies [][]byte) (*Command, error) {
	var params = [][]byte{[]byte(topic)}

	num := uint32(len(bodies))
	bodySize := 4
	for _, b := range bodies {
		bodySize += len(b) + 4
	}
	body := make([]byte, 0, bodySize)
	buf := bytes.NewBuffer(body)

	err := binary.Write(buf, binary.BigEndian, &num)
	if err != nil {
		return nil, err
	}
	for _, b := range bodies {
		err = binary.Write(buf, binary.BigEndian, int32(len(b)))
		if err != nil {
			return nil, err
		}
		_, err = buf.Write(b)
		if err != nil {
			return nil, err
		}
	}

	return &Command{[]byte("MPUB"), params, buf.Bytes()}, nil
}
Beispiel #27
0
func (client *Client) HandleLoadGroupOffline(lh *LoadGroupOffline) {
	messages := storage.LoadGroupOfflineMessage(lh.appid, lh.gid, lh.uid, lh.device_id, GROUP_OFFLINE_LIMIT)
	result := &MessageResult{status: 0}
	buffer := new(bytes.Buffer)

	var count int16 = 0
	for _, emsg := range messages {
		if emsg.msg.cmd == MSG_GROUP_IM {
			im := emsg.msg.body.(*IMMessage)
			if im.sender == lh.uid && emsg.device_id == lh.device_id {
				continue
			}
		}
		count += 1
	}
	binary.Write(buffer, binary.BigEndian, count)
	for _, emsg := range messages {
		if emsg.msg.cmd == MSG_GROUP_IM {
			im := emsg.msg.body.(*IMMessage)
			if im.sender == lh.uid && emsg.device_id == lh.device_id {
				continue
			}
		}
		ebuf := client.WriteEMessage(emsg)
		var size int16 = int16(len(ebuf))
		binary.Write(buffer, binary.BigEndian, size)
		buffer.Write(ebuf)
	}
	result.content = buffer.Bytes()
	msg := &Message{cmd: MSG_RESULT, body: result}
	SendMessage(client.conn, msg)
}
Beispiel #28
0
func (m *Bounce) MarshalForSignature() ([]byte, error) {
	var buf primitives.Buffer

	binary.Write(&buf, binary.BigEndian, m.Type())

	var buff [32]byte

	copy(buff[:32], []byte(fmt.Sprintf("%32s", m.Name)))
	buf.Write(buff[:])

	binary.Write(&buf, binary.BigEndian, m.Number)

	t := m.GetTimestamp()
	data, err := t.MarshalBinary()
	if err != nil {
		return nil, err
	}
	buf.Write(data)

	binary.Write(&buf, binary.BigEndian, int32(len(m.Stamps)))

	for _, ts := range m.Stamps {
		data, err := ts.MarshalBinary()
		if err != nil {
			return nil, err
		}
		buf.Write(data)
	}

	return buf.DeepCopyBytes(), nil
}
Beispiel #29
0
func writeAllHeaders(w io.Writer, headers []headerStruct) (err error) {
	// calculatint total length
	var totallen uint32 = 4
	for _, hdr := range headers {
		totallen += 4 + 2 + uint32(len(hdr.data))
	}
	// writing
	err = binary.Write(w, binary.LittleEndian, totallen)
	if err != nil {
		return err
	}
	for _, hdr := range headers {
		var headerlen uint32 = 4 + 2 + uint32(len(hdr.data))
		err = binary.Write(w, binary.LittleEndian, headerlen)
		if err != nil {
			return err
		}
		err = binary.Write(w, binary.LittleEndian, hdr.hdrtype)
		if err != nil {
			return err
		}
		_, err = w.Write(hdr.data)
		if err != nil {
			return err
		}
	}
	return nil
}
Beispiel #30
0
// body is the binary serializable request body. trailer is optional data
// following it, such as for BEP 41.
func (c *udpClient) write(h *RequestHeader, body interface{}, trailer []byte) (err error) {
	var buf bytes.Buffer
	err = binary.Write(&buf, binary.BigEndian, h)
	if err != nil {
		panic(err)
	}
	if body != nil {
		err = binary.Write(&buf, binary.BigEndian, body)
		if err != nil {
			panic(err)
		}
	}
	_, err = buf.Write(trailer)
	if err != nil {
		return
	}
	n, err := c.socket.Write(buf.Bytes())
	if err != nil {
		return
	}
	if n != buf.Len() {
		panic("write should send all or error")
	}
	return
}