decode.go 8.5 KB

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