decode.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. // Copyright 2018 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. package proto
  5. import (
  6. "google.golang.org/protobuf/encoding/protowire"
  7. "google.golang.org/protobuf/internal/encoding/messageset"
  8. "google.golang.org/protobuf/internal/errors"
  9. "google.golang.org/protobuf/internal/flags"
  10. "google.golang.org/protobuf/internal/genid"
  11. "google.golang.org/protobuf/internal/pragma"
  12. "google.golang.org/protobuf/reflect/protoreflect"
  13. "google.golang.org/protobuf/reflect/protoregistry"
  14. "google.golang.org/protobuf/runtime/protoiface"
  15. )
  16. // UnmarshalOptions configures the unmarshaler.
  17. //
  18. // Example usage:
  19. // err := UnmarshalOptions{DiscardUnknown: true}.Unmarshal(b, m)
  20. type UnmarshalOptions struct {
  21. pragma.NoUnkeyedLiterals
  22. // Merge merges the input into the destination message.
  23. // The default behavior is to always reset the message before unmarshaling,
  24. // unless Merge is specified.
  25. Merge bool
  26. // AllowPartial accepts input for messages that will result in missing
  27. // required fields. If AllowPartial is false (the default), Unmarshal will
  28. // return an error if there are any missing required fields.
  29. AllowPartial bool
  30. // If DiscardUnknown is set, unknown fields are ignored.
  31. DiscardUnknown bool
  32. // Resolver is used for looking up types when unmarshaling extension fields.
  33. // If nil, this defaults to using protoregistry.GlobalTypes.
  34. Resolver interface {
  35. FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error)
  36. FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error)
  37. }
  38. }
  39. // Unmarshal parses the wire-format message in b and places the result in m.
  40. // The provided message must be mutable (e.g., a non-nil pointer to a message).
  41. func Unmarshal(b []byte, m Message) error {
  42. _, err := UnmarshalOptions{}.unmarshal(b, m.ProtoReflect())
  43. return err
  44. }
  45. // Unmarshal parses the wire-format message in b and places the result in m.
  46. // The provided message must be mutable (e.g., a non-nil pointer to a message).
  47. func (o UnmarshalOptions) Unmarshal(b []byte, m Message) error {
  48. _, err := o.unmarshal(b, m.ProtoReflect())
  49. return err
  50. }
  51. // UnmarshalState parses a wire-format message and places the result in m.
  52. //
  53. // This method permits fine-grained control over the unmarshaler.
  54. // Most users should use Unmarshal instead.
  55. func (o UnmarshalOptions) UnmarshalState(in protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) {
  56. return o.unmarshal(in.Buf, in.Message)
  57. }
  58. // unmarshal is a centralized function that all unmarshal operations go through.
  59. // For profiling purposes, avoid changing the name of this function or
  60. // introducing other code paths for unmarshal that do not go through this.
  61. func (o UnmarshalOptions) unmarshal(b []byte, m protoreflect.Message) (out protoiface.UnmarshalOutput, err error) {
  62. if o.Resolver == nil {
  63. o.Resolver = protoregistry.GlobalTypes
  64. }
  65. if !o.Merge {
  66. Reset(m.Interface())
  67. }
  68. allowPartial := o.AllowPartial
  69. o.Merge = true
  70. o.AllowPartial = true
  71. methods := protoMethods(m)
  72. if methods != nil && methods.Unmarshal != nil &&
  73. !(o.DiscardUnknown && methods.Flags&protoiface.SupportUnmarshalDiscardUnknown == 0) {
  74. in := protoiface.UnmarshalInput{
  75. Message: m,
  76. Buf: b,
  77. Resolver: o.Resolver,
  78. }
  79. if o.DiscardUnknown {
  80. in.Flags |= protoiface.UnmarshalDiscardUnknown
  81. }
  82. out, err = methods.Unmarshal(in)
  83. } else {
  84. err = o.unmarshalMessageSlow(b, m)
  85. }
  86. if err != nil {
  87. return out, err
  88. }
  89. if allowPartial || (out.Flags&protoiface.UnmarshalInitialized != 0) {
  90. return out, nil
  91. }
  92. return out, checkInitialized(m)
  93. }
  94. func (o UnmarshalOptions) unmarshalMessage(b []byte, m protoreflect.Message) error {
  95. _, err := o.unmarshal(b, m)
  96. return err
  97. }
  98. func (o UnmarshalOptions) unmarshalMessageSlow(b []byte, m protoreflect.Message) error {
  99. md := m.Descriptor()
  100. if messageset.IsMessageSet(md) {
  101. return o.unmarshalMessageSet(b, m)
  102. }
  103. fields := md.Fields()
  104. for len(b) > 0 {
  105. // Parse the tag (field number and wire type).
  106. num, wtyp, tagLen := protowire.ConsumeTag(b)
  107. if tagLen < 0 {
  108. return errDecode
  109. }
  110. if num > protowire.MaxValidNumber {
  111. return errDecode
  112. }
  113. // Find the field descriptor for this field number.
  114. fd := fields.ByNumber(num)
  115. if fd == nil && md.ExtensionRanges().Has(num) {
  116. extType, err := o.Resolver.FindExtensionByNumber(md.FullName(), num)
  117. if err != nil && err != protoregistry.NotFound {
  118. return errors.New("%v: unable to resolve extension %v: %v", md.FullName(), num, err)
  119. }
  120. if extType != nil {
  121. fd = extType.TypeDescriptor()
  122. }
  123. }
  124. var err error
  125. if fd == nil {
  126. err = errUnknown
  127. } else if flags.ProtoLegacy {
  128. if fd.IsWeak() && fd.Message().IsPlaceholder() {
  129. err = errUnknown // weak referent is not linked in
  130. }
  131. }
  132. // Parse the field value.
  133. var valLen int
  134. switch {
  135. case err != nil:
  136. case fd.IsList():
  137. valLen, err = o.unmarshalList(b[tagLen:], wtyp, m.Mutable(fd).List(), fd)
  138. case fd.IsMap():
  139. valLen, err = o.unmarshalMap(b[tagLen:], wtyp, m.Mutable(fd).Map(), fd)
  140. default:
  141. valLen, err = o.unmarshalSingular(b[tagLen:], wtyp, m, fd)
  142. }
  143. if err != nil {
  144. if err != errUnknown {
  145. return err
  146. }
  147. valLen = protowire.ConsumeFieldValue(num, wtyp, b[tagLen:])
  148. if valLen < 0 {
  149. return errDecode
  150. }
  151. if !o.DiscardUnknown {
  152. m.SetUnknown(append(m.GetUnknown(), b[:tagLen+valLen]...))
  153. }
  154. }
  155. b = b[tagLen+valLen:]
  156. }
  157. return nil
  158. }
  159. func (o UnmarshalOptions) unmarshalSingular(b []byte, wtyp protowire.Type, m protoreflect.Message, fd protoreflect.FieldDescriptor) (n int, err error) {
  160. v, n, err := o.unmarshalScalar(b, wtyp, fd)
  161. if err != nil {
  162. return 0, err
  163. }
  164. switch fd.Kind() {
  165. case protoreflect.GroupKind, protoreflect.MessageKind:
  166. m2 := m.Mutable(fd).Message()
  167. if err := o.unmarshalMessage(v.Bytes(), m2); err != nil {
  168. return n, err
  169. }
  170. default:
  171. // Non-message scalars replace the previous value.
  172. m.Set(fd, v)
  173. }
  174. return n, nil
  175. }
  176. func (o UnmarshalOptions) unmarshalMap(b []byte, wtyp protowire.Type, mapv protoreflect.Map, fd protoreflect.FieldDescriptor) (n int, err error) {
  177. if wtyp != protowire.BytesType {
  178. return 0, errUnknown
  179. }
  180. b, n = protowire.ConsumeBytes(b)
  181. if n < 0 {
  182. return 0, errDecode
  183. }
  184. var (
  185. keyField = fd.MapKey()
  186. valField = fd.MapValue()
  187. key protoreflect.Value
  188. val protoreflect.Value
  189. haveKey bool
  190. haveVal bool
  191. )
  192. switch valField.Kind() {
  193. case protoreflect.GroupKind, protoreflect.MessageKind:
  194. val = mapv.NewValue()
  195. }
  196. // Map entries are represented as a two-element message with fields
  197. // containing the key and value.
  198. for len(b) > 0 {
  199. num, wtyp, n := protowire.ConsumeTag(b)
  200. if n < 0 {
  201. return 0, errDecode
  202. }
  203. if num > protowire.MaxValidNumber {
  204. return 0, errDecode
  205. }
  206. b = b[n:]
  207. err = errUnknown
  208. switch num {
  209. case genid.MapEntry_Key_field_number:
  210. key, n, err = o.unmarshalScalar(b, wtyp, keyField)
  211. if err != nil {
  212. break
  213. }
  214. haveKey = true
  215. case genid.MapEntry_Value_field_number:
  216. var v protoreflect.Value
  217. v, n, err = o.unmarshalScalar(b, wtyp, valField)
  218. if err != nil {
  219. break
  220. }
  221. switch valField.Kind() {
  222. case protoreflect.GroupKind, protoreflect.MessageKind:
  223. if err := o.unmarshalMessage(v.Bytes(), val.Message()); err != nil {
  224. return 0, err
  225. }
  226. default:
  227. val = v
  228. }
  229. haveVal = true
  230. }
  231. if err == errUnknown {
  232. n = protowire.ConsumeFieldValue(num, wtyp, b)
  233. if n < 0 {
  234. return 0, errDecode
  235. }
  236. } else if err != nil {
  237. return 0, err
  238. }
  239. b = b[n:]
  240. }
  241. // Every map entry should have entries for key and value, but this is not strictly required.
  242. if !haveKey {
  243. key = keyField.Default()
  244. }
  245. if !haveVal {
  246. switch valField.Kind() {
  247. case protoreflect.GroupKind, protoreflect.MessageKind:
  248. default:
  249. val = valField.Default()
  250. }
  251. }
  252. mapv.Set(key.MapKey(), val)
  253. return n, nil
  254. }
  255. // errUnknown is used internally to indicate fields which should be added
  256. // to the unknown field set of a message. It is never returned from an exported
  257. // function.
  258. var errUnknown = errors.New("BUG: internal error (unknown)")
  259. var errDecode = errors.New("cannot parse invalid wire-format data")