decode.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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/genid"
  10. "google.golang.org/protobuf/internal/pragma"
  11. "google.golang.org/protobuf/reflect/protoreflect"
  12. "google.golang.org/protobuf/reflect/protoregistry"
  13. "google.golang.org/protobuf/runtime/protoiface"
  14. )
  15. // UnmarshalOptions configures the unmarshaler.
  16. //
  17. // Example usage:
  18. //
  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. // RecursionLimit limits how deeply messages may be nested.
  39. // If zero, a default limit is applied.
  40. RecursionLimit int
  41. //
  42. // NoLazyDecoding turns off lazy decoding, which otherwise is enabled by
  43. // default. Lazy decoding only affects submessages (annotated with [lazy =
  44. // true] in the .proto file) within messages that use the Opaque API.
  45. NoLazyDecoding bool
  46. }
  47. // Unmarshal parses the wire-format message in b and places the result in m.
  48. // The provided message must be mutable (e.g., a non-nil pointer to a message).
  49. //
  50. // See the [UnmarshalOptions] type if you need more control.
  51. func Unmarshal(b []byte, m Message) error {
  52. _, err := UnmarshalOptions{RecursionLimit: protowire.DefaultRecursionLimit}.unmarshal(b, m.ProtoReflect())
  53. return err
  54. }
  55. // Unmarshal parses the wire-format message in b and places the result in m.
  56. // The provided message must be mutable (e.g., a non-nil pointer to a message).
  57. func (o UnmarshalOptions) Unmarshal(b []byte, m Message) error {
  58. if o.RecursionLimit == 0 {
  59. o.RecursionLimit = protowire.DefaultRecursionLimit
  60. }
  61. _, err := o.unmarshal(b, m.ProtoReflect())
  62. return err
  63. }
  64. // UnmarshalState parses a wire-format message and places the result in m.
  65. //
  66. // This method permits fine-grained control over the unmarshaler.
  67. // Most users should use [Unmarshal] instead.
  68. func (o UnmarshalOptions) UnmarshalState(in protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) {
  69. if o.RecursionLimit == 0 {
  70. o.RecursionLimit = protowire.DefaultRecursionLimit
  71. }
  72. return o.unmarshal(in.Buf, in.Message)
  73. }
  74. // unmarshal is a centralized function that all unmarshal operations go through.
  75. // For profiling purposes, avoid changing the name of this function or
  76. // introducing other code paths for unmarshal that do not go through this.
  77. func (o UnmarshalOptions) unmarshal(b []byte, m protoreflect.Message) (out protoiface.UnmarshalOutput, err error) {
  78. if o.Resolver == nil {
  79. o.Resolver = protoregistry.GlobalTypes
  80. }
  81. if !o.Merge {
  82. Reset(m.Interface())
  83. }
  84. allowPartial := o.AllowPartial
  85. o.Merge = true
  86. o.AllowPartial = true
  87. methods := protoMethods(m)
  88. if methods != nil && methods.Unmarshal != nil &&
  89. !(o.DiscardUnknown && methods.Flags&protoiface.SupportUnmarshalDiscardUnknown == 0) {
  90. in := protoiface.UnmarshalInput{
  91. Message: m,
  92. Buf: b,
  93. Resolver: o.Resolver,
  94. Depth: o.RecursionLimit,
  95. }
  96. if o.DiscardUnknown {
  97. in.Flags |= protoiface.UnmarshalDiscardUnknown
  98. }
  99. if !allowPartial {
  100. // This does not affect how current unmarshal functions work, it just allows them
  101. // to record this for lazy the decoding case.
  102. in.Flags |= protoiface.UnmarshalCheckRequired
  103. }
  104. if o.NoLazyDecoding {
  105. in.Flags |= protoiface.UnmarshalNoLazyDecoding
  106. }
  107. out, err = methods.Unmarshal(in)
  108. } else {
  109. o.RecursionLimit--
  110. if o.RecursionLimit < 0 {
  111. return out, errors.New("exceeded max recursion depth")
  112. }
  113. err = o.unmarshalMessageSlow(b, m)
  114. }
  115. if err != nil {
  116. return out, err
  117. }
  118. if allowPartial || (out.Flags&protoiface.UnmarshalInitialized != 0) {
  119. return out, nil
  120. }
  121. return out, checkInitialized(m)
  122. }
  123. func (o UnmarshalOptions) unmarshalMessage(b []byte, m protoreflect.Message) error {
  124. _, err := o.unmarshal(b, m)
  125. return err
  126. }
  127. func (o UnmarshalOptions) unmarshalMessageSlow(b []byte, m protoreflect.Message) error {
  128. md := m.Descriptor()
  129. if messageset.IsMessageSet(md) {
  130. return o.unmarshalMessageSet(b, m)
  131. }
  132. fields := md.Fields()
  133. for len(b) > 0 {
  134. // Parse the tag (field number and wire type).
  135. num, wtyp, tagLen := protowire.ConsumeTag(b)
  136. if tagLen < 0 {
  137. return errDecode
  138. }
  139. if num > protowire.MaxValidNumber {
  140. return errDecode
  141. }
  142. // Find the field descriptor for this field number.
  143. fd := fields.ByNumber(num)
  144. if fd == nil && md.ExtensionRanges().Has(num) {
  145. extType, err := o.Resolver.FindExtensionByNumber(md.FullName(), num)
  146. if err != nil && err != protoregistry.NotFound {
  147. return errors.New("%v: unable to resolve extension %v: %v", md.FullName(), num, err)
  148. }
  149. if extType != nil {
  150. fd = extType.TypeDescriptor()
  151. }
  152. }
  153. var err error
  154. if fd == nil {
  155. err = errUnknown
  156. }
  157. // Parse the field value.
  158. var valLen int
  159. switch {
  160. case err != nil:
  161. case fd.IsList():
  162. valLen, err = o.unmarshalList(b[tagLen:], wtyp, m.Mutable(fd).List(), fd)
  163. case fd.IsMap():
  164. valLen, err = o.unmarshalMap(b[tagLen:], wtyp, m.Mutable(fd).Map(), fd)
  165. default:
  166. valLen, err = o.unmarshalSingular(b[tagLen:], wtyp, m, fd)
  167. }
  168. if err != nil {
  169. if err != errUnknown {
  170. return err
  171. }
  172. valLen = protowire.ConsumeFieldValue(num, wtyp, b[tagLen:])
  173. if valLen < 0 {
  174. return errDecode
  175. }
  176. if !o.DiscardUnknown {
  177. m.SetUnknown(append(m.GetUnknown(), b[:tagLen+valLen]...))
  178. }
  179. }
  180. b = b[tagLen+valLen:]
  181. }
  182. return nil
  183. }
  184. func (o UnmarshalOptions) unmarshalSingular(b []byte, wtyp protowire.Type, m protoreflect.Message, fd protoreflect.FieldDescriptor) (n int, err error) {
  185. v, n, err := o.unmarshalScalar(b, wtyp, fd)
  186. if err != nil {
  187. return 0, err
  188. }
  189. switch fd.Kind() {
  190. case protoreflect.GroupKind, protoreflect.MessageKind:
  191. m2 := m.Mutable(fd).Message()
  192. if err := o.unmarshalMessage(v.Bytes(), m2); err != nil {
  193. return n, err
  194. }
  195. default:
  196. // Non-message scalars replace the previous value.
  197. m.Set(fd, v)
  198. }
  199. return n, nil
  200. }
  201. func (o UnmarshalOptions) unmarshalMap(b []byte, wtyp protowire.Type, mapv protoreflect.Map, fd protoreflect.FieldDescriptor) (n int, err error) {
  202. if wtyp != protowire.BytesType {
  203. return 0, errUnknown
  204. }
  205. b, n = protowire.ConsumeBytes(b)
  206. if n < 0 {
  207. return 0, errDecode
  208. }
  209. var (
  210. keyField = fd.MapKey()
  211. valField = fd.MapValue()
  212. key protoreflect.Value
  213. val protoreflect.Value
  214. haveKey bool
  215. haveVal bool
  216. )
  217. switch valField.Kind() {
  218. case protoreflect.GroupKind, protoreflect.MessageKind:
  219. val = mapv.NewValue()
  220. }
  221. // Map entries are represented as a two-element message with fields
  222. // containing the key and value.
  223. for len(b) > 0 {
  224. num, wtyp, n := protowire.ConsumeTag(b)
  225. if n < 0 {
  226. return 0, errDecode
  227. }
  228. if num > protowire.MaxValidNumber {
  229. return 0, errDecode
  230. }
  231. b = b[n:]
  232. err = errUnknown
  233. switch num {
  234. case genid.MapEntry_Key_field_number:
  235. key, n, err = o.unmarshalScalar(b, wtyp, keyField)
  236. if err != nil {
  237. break
  238. }
  239. haveKey = true
  240. case genid.MapEntry_Value_field_number:
  241. var v protoreflect.Value
  242. v, n, err = o.unmarshalScalar(b, wtyp, valField)
  243. if err != nil {
  244. break
  245. }
  246. switch valField.Kind() {
  247. case protoreflect.GroupKind, protoreflect.MessageKind:
  248. if err := o.unmarshalMessage(v.Bytes(), val.Message()); err != nil {
  249. return 0, err
  250. }
  251. default:
  252. val = v
  253. }
  254. haveVal = true
  255. }
  256. if err == errUnknown {
  257. n = protowire.ConsumeFieldValue(num, wtyp, b)
  258. if n < 0 {
  259. return 0, errDecode
  260. }
  261. } else if err != nil {
  262. return 0, err
  263. }
  264. b = b[n:]
  265. }
  266. // Every map entry should have entries for key and value, but this is not strictly required.
  267. if !haveKey {
  268. key = keyField.Default()
  269. }
  270. if !haveVal {
  271. switch valField.Kind() {
  272. case protoreflect.GroupKind, protoreflect.MessageKind:
  273. default:
  274. val = valField.Default()
  275. }
  276. }
  277. mapv.Set(key.MapKey(), val)
  278. return n, nil
  279. }
  280. // errUnknown is used internally to indicate fields which should be added
  281. // to the unknown field set of a message. It is never returned from an exported
  282. // function.
  283. var errUnknown = errors.New("BUG: internal error (unknown)")
  284. var errDecode = errors.New("cannot parse invalid wire-format data")