File: payload.go

package info (click to toggle)
golang-github-farsightsec-go-nmsg 0.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid, trixie
  • size: 500 kB
  • sloc: sh: 21; makefile: 3
file content (73 lines) | stat: -rw-r--r-- 1,783 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
 * Copyright (c) 2017 by Farsight Security, Inc.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

package nmsg

import (
	"encoding/binary"
	"time"

	"google.golang.org/protobuf/proto"
)

// Payload encapsulates an nmsg message in a NmsgPayload, suitable for sending to
// an Output
func Payload(m Message) (*NmsgPayload, error) {
	mbytes, err := proto.Marshal(m)
	if err != nil {
		return nil, err
	}
	now := time.Now().UnixNano()
	return &NmsgPayload{
		Vid:      proto.Uint32(m.GetVid()),
		Msgtype:  proto.Uint32(m.GetMsgtype()),
		TimeSec:  proto.Int64(now / 1000000000),
		TimeNsec: proto.Uint32(uint32(now % 1000000000)),
		Payload:  mbytes,
	}, nil
}

// SetSource sets the NmsgPayload source identifier.
func (p *NmsgPayload) SetSource(s uint32) {
	p.Source = proto.Uint32(s)
}

// SetOperator sets the NmsgPayload operator identifier.
func (p *NmsgPayload) SetOperator(o uint32) {
	p.Operator = proto.Uint32(o)
}

// SetGroup sets the NmsgPayload group identifier.
func (p *NmsgPayload) SetGroup(g uint32) {
	p.Group = proto.Uint32(g)
}

// Message returns the message encapsulated in the NmsgPayload,
// Unmarshaled
func (p *NmsgPayload) Message() (Message, error) {
	m, err := NewMessage(*p.Vid, *p.Msgtype)
	if err != nil {
		return nil, err
	}
	err = proto.Unmarshal(p.Payload, m)
	if err != nil {
		return nil, err
	}
	return m, nil
}

func (p *NmsgPayload) payloadSize() int {
	var ibuf [binary.MaxVarintLen64]byte

	psiz := proto.Size(p)
	// tag + varint length of encoded p
	psiz += 1 + binary.PutUvarint(ibuf[:], uint64(psiz))
	// tag + varint CRC32
	psiz += 1 + binary.MaxVarintLen32
	return psiz
}