podman
242 строки · 7.4 Кб
1// Copyright 2019 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5// Package messageset encodes and decodes the obsolete MessageSet wire format.
6package messageset
7
8import (
9"math"
10
11"google.golang.org/protobuf/encoding/protowire"
12"google.golang.org/protobuf/internal/errors"
13"google.golang.org/protobuf/reflect/protoreflect"
14)
15
16// The MessageSet wire format is equivalent to a message defined as follows,
17// where each Item defines an extension field with a field number of 'type_id'
18// and content of 'message'. MessageSet extensions must be non-repeated message
19// fields.
20//
21// message MessageSet {
22// repeated group Item = 1 {
23// required int32 type_id = 2;
24// required string message = 3;
25// }
26// }
27const (
28FieldItem = protowire.Number(1)
29FieldTypeID = protowire.Number(2)
30FieldMessage = protowire.Number(3)
31)
32
33// ExtensionName is the field name for extensions of MessageSet.
34//
35// A valid MessageSet extension must be of the form:
36//
37// message MyMessage {
38// extend proto2.bridge.MessageSet {
39// optional MyMessage message_set_extension = 1234;
40// }
41// ...
42// }
43const ExtensionName = "message_set_extension"
44
45// IsMessageSet returns whether the message uses the MessageSet wire format.
46func IsMessageSet(md protoreflect.MessageDescriptor) bool {
47xmd, ok := md.(interface{ IsMessageSet() bool })
48return ok && xmd.IsMessageSet()
49}
50
51// IsMessageSetExtension reports this field properly extends a MessageSet.
52func IsMessageSetExtension(fd protoreflect.FieldDescriptor) bool {
53switch {
54case fd.Name() != ExtensionName:
55return false
56case !IsMessageSet(fd.ContainingMessage()):
57return false
58case fd.FullName().Parent() != fd.Message().FullName():
59return false
60}
61return true
62}
63
64// SizeField returns the size of a MessageSet item field containing an extension
65// with the given field number, not counting the contents of the message subfield.
66func SizeField(num protowire.Number) int {
67return 2*protowire.SizeTag(FieldItem) + protowire.SizeTag(FieldTypeID) + protowire.SizeVarint(uint64(num))
68}
69
70// Unmarshal parses a MessageSet.
71//
72// It calls fn with the type ID and value of each item in the MessageSet.
73// Unknown fields are discarded.
74//
75// If wantLen is true, the item values include the varint length prefix.
76// This is ugly, but simplifies the fast-path decoder in internal/impl.
77func Unmarshal(b []byte, wantLen bool, fn func(typeID protowire.Number, value []byte) error) error {
78for len(b) > 0 {
79num, wtyp, n := protowire.ConsumeTag(b)
80if n < 0 {
81return protowire.ParseError(n)
82}
83b = b[n:]
84if num != FieldItem || wtyp != protowire.StartGroupType {
85n := protowire.ConsumeFieldValue(num, wtyp, b)
86if n < 0 {
87return protowire.ParseError(n)
88}
89b = b[n:]
90continue
91}
92typeID, value, n, err := ConsumeFieldValue(b, wantLen)
93if err != nil {
94return err
95}
96b = b[n:]
97if typeID == 0 {
98continue
99}
100if err := fn(typeID, value); err != nil {
101return err
102}
103}
104return nil
105}
106
107// ConsumeFieldValue parses b as a MessageSet item field value until and including
108// the trailing end group marker. It assumes the start group tag has already been parsed.
109// It returns the contents of the type_id and message subfields and the total
110// item length.
111//
112// If wantLen is true, the returned message value includes the length prefix.
113func ConsumeFieldValue(b []byte, wantLen bool) (typeid protowire.Number, message []byte, n int, err error) {
114ilen := len(b)
115for {
116num, wtyp, n := protowire.ConsumeTag(b)
117if n < 0 {
118return 0, nil, 0, protowire.ParseError(n)
119}
120b = b[n:]
121switch {
122case num == FieldItem && wtyp == protowire.EndGroupType:
123if wantLen && len(message) == 0 {
124// The message field was missing, which should never happen.
125// Be prepared for this case anyway.
126message = protowire.AppendVarint(message, 0)
127}
128return typeid, message, ilen - len(b), nil
129case num == FieldTypeID && wtyp == protowire.VarintType:
130v, n := protowire.ConsumeVarint(b)
131if n < 0 {
132return 0, nil, 0, protowire.ParseError(n)
133}
134b = b[n:]
135if v < 1 || v > math.MaxInt32 {
136return 0, nil, 0, errors.New("invalid type_id in message set")
137}
138typeid = protowire.Number(v)
139case num == FieldMessage && wtyp == protowire.BytesType:
140m, n := protowire.ConsumeBytes(b)
141if n < 0 {
142return 0, nil, 0, protowire.ParseError(n)
143}
144if message == nil {
145if wantLen {
146message = b[:n:n]
147} else {
148message = m[:len(m):len(m)]
149}
150} else {
151// This case should never happen in practice, but handle it for
152// correctness: The MessageSet item contains multiple message
153// fields, which need to be merged.
154//
155// In the case where we're returning the length, this becomes
156// quite inefficient since we need to strip the length off
157// the existing data and reconstruct it with the combined length.
158if wantLen {
159_, nn := protowire.ConsumeVarint(message)
160m0 := message[nn:]
161message = nil
162message = protowire.AppendVarint(message, uint64(len(m0)+len(m)))
163message = append(message, m0...)
164message = append(message, m...)
165} else {
166message = append(message, m...)
167}
168}
169b = b[n:]
170default:
171// We have no place to put it, so we just ignore unknown fields.
172n := protowire.ConsumeFieldValue(num, wtyp, b)
173if n < 0 {
174return 0, nil, 0, protowire.ParseError(n)
175}
176b = b[n:]
177}
178}
179}
180
181// AppendFieldStart appends the start of a MessageSet item field containing
182// an extension with the given number. The caller must add the message
183// subfield (including the tag).
184func AppendFieldStart(b []byte, num protowire.Number) []byte {
185b = protowire.AppendTag(b, FieldItem, protowire.StartGroupType)
186b = protowire.AppendTag(b, FieldTypeID, protowire.VarintType)
187b = protowire.AppendVarint(b, uint64(num))
188return b
189}
190
191// AppendFieldEnd appends the trailing end group marker for a MessageSet item field.
192func AppendFieldEnd(b []byte) []byte {
193return protowire.AppendTag(b, FieldItem, protowire.EndGroupType)
194}
195
196// SizeUnknown returns the size of an unknown fields section in MessageSet format.
197//
198// See AppendUnknown.
199func SizeUnknown(unknown []byte) (size int) {
200for len(unknown) > 0 {
201num, typ, n := protowire.ConsumeTag(unknown)
202if n < 0 || typ != protowire.BytesType {
203return 0
204}
205unknown = unknown[n:]
206_, n = protowire.ConsumeBytes(unknown)
207if n < 0 {
208return 0
209}
210unknown = unknown[n:]
211size += SizeField(num) + protowire.SizeTag(FieldMessage) + n
212}
213return size
214}
215
216// AppendUnknown appends unknown fields to b in MessageSet format.
217//
218// For historic reasons, unresolved items in a MessageSet are stored in a
219// message's unknown fields section in non-MessageSet format. That is, an
220// unknown item with typeID T and value V appears in the unknown fields as
221// a field with number T and value V.
222//
223// This function converts the unknown fields back into MessageSet form.
224func AppendUnknown(b, unknown []byte) ([]byte, error) {
225for len(unknown) > 0 {
226num, typ, n := protowire.ConsumeTag(unknown)
227if n < 0 || typ != protowire.BytesType {
228return nil, errors.New("invalid data in message set unknown fields")
229}
230unknown = unknown[n:]
231_, n = protowire.ConsumeBytes(unknown)
232if n < 0 {
233return nil, errors.New("invalid data in message set unknown fields")
234}
235b = AppendFieldStart(b, num)
236b = protowire.AppendTag(b, FieldMessage, protowire.BytesType)
237b = append(b, unknown[:n]...)
238b = AppendFieldEnd(b)
239unknown = unknown[n:]
240}
241return b, nil
242}
243