github.com/braveheart12/insolar-09-08-19@v0.8.7/network/transport/packet/packet.go (about)

     1  /*
     2   * The Clear BSD License
     3   *
     4   * Copyright (c) 2019 Insolar Technologies
     5   *
     6   * All rights reserved.
     7   *
     8   * Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met:
     9   *
    10   *  Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    11   *  Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    12   *  Neither the name of Insolar Technologies nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
    13   *
    14   * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    15   *
    16   */
    17  
    18  package packet
    19  
    20  import (
    21  	"bytes"
    22  	"encoding/binary"
    23  	"encoding/gob"
    24  	"io"
    25  
    26  	"github.com/insolar/insolar/log"
    27  	"github.com/insolar/insolar/network"
    28  	"github.com/insolar/insolar/network/transport/host"
    29  	"github.com/insolar/insolar/network/transport/packet/types"
    30  	"github.com/pkg/errors"
    31  )
    32  
    33  // Packet is DHT packet object.
    34  type Packet struct {
    35  	Sender        *host.Host
    36  	Receiver      *host.Host
    37  	Type          types.PacketType
    38  	RequestID     network.RequestID
    39  	RemoteAddress string
    40  
    41  	TraceID    string
    42  	Data       interface{}
    43  	Error      error
    44  	IsResponse bool
    45  }
    46  
    47  // SerializePacket converts packet to byte slice.
    48  func SerializePacket(q *Packet) ([]byte, error) {
    49  	var msgBuffer bytes.Buffer
    50  	enc := gob.NewEncoder(&msgBuffer)
    51  	err := enc.Encode(q)
    52  	if err != nil {
    53  		return nil, errors.Wrap(err, "Failed to serialize packet")
    54  	}
    55  
    56  	length := msgBuffer.Len()
    57  
    58  	var lengthBytes [8]byte
    59  	binary.PutUvarint(lengthBytes[:], uint64(length))
    60  
    61  	var result []byte
    62  	result = append(result, lengthBytes[:]...)
    63  	result = append(result, msgBuffer.Bytes()...)
    64  
    65  	return result, nil
    66  }
    67  
    68  // DeserializePacket reads packet from io.Reader.
    69  func DeserializePacket(conn io.Reader) (*Packet, error) {
    70  
    71  	lengthBytes := make([]byte, 8)
    72  	if _, err := io.ReadFull(conn, lengthBytes); err != nil {
    73  		return nil, err
    74  	}
    75  	lengthReader := bytes.NewBuffer(lengthBytes)
    76  	length, err := binary.ReadUvarint(lengthReader)
    77  	if err != nil {
    78  		return nil, io.ErrUnexpectedEOF
    79  	}
    80  
    81  	log.Debugf("[ DeserializePacket ] packet length %d", length)
    82  	buf := make([]byte, length)
    83  	if _, err := io.ReadFull(conn, buf); err != nil {
    84  		log.Error("[ DeserializePacket ] couldn't read packet: ", err)
    85  		return nil, err
    86  	}
    87  	log.Debugf("[ DeserializePacket ] read packet")
    88  
    89  	msg := &Packet{}
    90  	dec := gob.NewDecoder(bytes.NewReader(buf))
    91  
    92  	err = dec.Decode(msg)
    93  	if err != nil {
    94  		log.Error("[ DeserializePacket ] couldn't decode packet: ", err)
    95  		return nil, err
    96  	}
    97  
    98  	log.Debugf("[ DeserializePacket ] decoded packet to %#v", msg)
    99  
   100  	return msg, nil
   101  }
   102  
   103  func init() {
   104  	gob.Register(&RequestPulse{})
   105  	gob.Register(&RequestGetRandomHosts{})
   106  
   107  	gob.Register(&ResponsePulse{})
   108  	gob.Register(&ResponseGetRandomHosts{})
   109  }