decode.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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 textpb
  5. import (
  6. "fmt"
  7. "strings"
  8. "github.com/golang/protobuf/v2/internal/encoding/text"
  9. "github.com/golang/protobuf/v2/internal/errors"
  10. "github.com/golang/protobuf/v2/internal/pragma"
  11. "github.com/golang/protobuf/v2/internal/set"
  12. "github.com/golang/protobuf/v2/proto"
  13. pref "github.com/golang/protobuf/v2/reflect/protoreflect"
  14. "github.com/golang/protobuf/v2/reflect/protoregistry"
  15. )
  16. // Unmarshal reads the given []byte into the given proto.Message.
  17. // TODO: may want to describe when Unmarshal returns error.
  18. func Unmarshal(m proto.Message, b []byte) error {
  19. return UnmarshalOptions{}.Unmarshal(m, b)
  20. }
  21. // UnmarshalOptions is a configurable textproto format parser.
  22. type UnmarshalOptions struct {
  23. pragma.NoUnkeyedLiterals
  24. // Resolver is the registry used for type lookups when unmarshaling extensions
  25. // and processing Any. If Resolver is not set, unmarshaling will default to
  26. // using protoregistry.GlobalTypes.
  27. Resolver *protoregistry.Types
  28. }
  29. // Unmarshal reads the given []byte and populates the given proto.Message using options in
  30. // UnmarshalOptions object.
  31. func (o UnmarshalOptions) Unmarshal(m proto.Message, b []byte) error {
  32. var nerr errors.NonFatal
  33. mr := m.ProtoReflect()
  34. // Clear all fields before populating it.
  35. // TODO: Determine if this needs to be consistent with jsonpb and binary unmarshal where
  36. // behavior is to merge values into existing message. If decision is to not clear the fields
  37. // ahead, code will need to be updated properly when merging nested messages.
  38. resetMessage(mr)
  39. // Parse into text.Value of message type.
  40. val, err := text.Unmarshal(b)
  41. if !nerr.Merge(err) {
  42. return err
  43. }
  44. if o.Resolver == nil {
  45. o.Resolver = protoregistry.GlobalTypes
  46. }
  47. err = o.unmarshalMessage(val.Message(), mr)
  48. if !nerr.Merge(err) {
  49. return err
  50. }
  51. return nerr.E
  52. }
  53. // resetMessage clears all fields of given protoreflect.Message.
  54. // TODO: This should go into the proto package.
  55. func resetMessage(m pref.Message) {
  56. knownFields := m.KnownFields()
  57. knownFields.Range(func(num pref.FieldNumber, _ pref.Value) bool {
  58. knownFields.Clear(num)
  59. return true
  60. })
  61. unknownFields := m.UnknownFields()
  62. unknownFields.Range(func(num pref.FieldNumber, _ pref.RawFields) bool {
  63. unknownFields.Set(num, nil)
  64. return true
  65. })
  66. extTypes := knownFields.ExtensionTypes()
  67. extTypes.Range(func(xt pref.ExtensionType) bool {
  68. extTypes.Remove(xt)
  69. return true
  70. })
  71. }
  72. // unmarshalMessage unmarshals a [][2]text.Value message into the given protoreflect.Message.
  73. func (o UnmarshalOptions) unmarshalMessage(tmsg [][2]text.Value, m pref.Message) error {
  74. var nerr errors.NonFatal
  75. msgType := m.Type()
  76. knownFields := m.KnownFields()
  77. // Handle expanded Any message.
  78. if msgType.FullName() == "google.protobuf.Any" && isExpandedAny(tmsg) {
  79. return o.unmarshalAny(tmsg[0], knownFields)
  80. }
  81. fieldDescs := msgType.Fields()
  82. reservedNames := msgType.ReservedNames()
  83. xtTypes := knownFields.ExtensionTypes()
  84. var reqNums set.Ints
  85. var seenNums set.Ints
  86. for _, tfield := range tmsg {
  87. tkey := tfield[0]
  88. tval := tfield[1]
  89. var fd pref.FieldDescriptor
  90. var name pref.Name
  91. switch tkey.Type() {
  92. case text.Name:
  93. name, _ = tkey.Name()
  94. fd = fieldDescs.ByName(name)
  95. if fd == nil {
  96. // Check if this is a group field.
  97. fd = fieldDescs.ByName(pref.Name(strings.ToLower(string(name))))
  98. }
  99. case text.String:
  100. // Handle extensions only. This code path is not for Any.
  101. if msgType.FullName() == "google.protobuf.Any" {
  102. break
  103. }
  104. // Extensions have to be registered first in the message's
  105. // ExtensionTypes before setting a value to it.
  106. xtName := pref.FullName(tkey.String())
  107. // Check first if it is already registered. This is the case for
  108. // repeated fields.
  109. xt := xtTypes.ByName(xtName)
  110. if xt == nil {
  111. var err error
  112. xt, err = o.findExtension(xtName)
  113. if err != nil && err != protoregistry.NotFound {
  114. return errors.New("unable to resolve [%v]: %v", xtName, err)
  115. }
  116. if xt != nil {
  117. xtTypes.Register(xt)
  118. }
  119. }
  120. fd = xt
  121. }
  122. if fd == nil {
  123. // Ignore reserved names.
  124. if reservedNames.Has(name) {
  125. continue
  126. }
  127. // TODO: Can provide option to ignore unknown message fields.
  128. return errors.New("%v contains unknown field: %v", msgType.FullName(), tkey)
  129. }
  130. if cardinality := fd.Cardinality(); cardinality == pref.Repeated {
  131. // Map or list fields have cardinality of repeated.
  132. if err := o.unmarshalRepeated(tval, fd, knownFields); !nerr.Merge(err) {
  133. return err
  134. }
  135. } else {
  136. // Required or optional fields.
  137. num := uint64(fd.Number())
  138. if seenNums.Has(num) {
  139. return errors.New("non-repeated field %v is repeated", fd.FullName())
  140. }
  141. if err := o.unmarshalSingular(tval, fd, knownFields); !nerr.Merge(err) {
  142. return err
  143. }
  144. if cardinality == pref.Required {
  145. reqNums.Set(num)
  146. }
  147. seenNums.Set(num)
  148. }
  149. }
  150. // Check for any missing required fields.
  151. allReqNums := msgType.RequiredNumbers()
  152. if reqNums.Len() != allReqNums.Len() {
  153. for i := 0; i < allReqNums.Len(); i++ {
  154. if num := allReqNums.Get(i); !reqNums.Has(uint64(num)) {
  155. nerr.AppendRequiredNotSet(string(fieldDescs.ByNumber(num).FullName()))
  156. }
  157. }
  158. }
  159. return nerr.E
  160. }
  161. // findExtension returns protoreflect.ExtensionType from the Resolver if found.
  162. func (o UnmarshalOptions) findExtension(xtName pref.FullName) (pref.ExtensionType, error) {
  163. xt, err := o.Resolver.FindExtensionByName(xtName)
  164. if err == nil {
  165. return xt, nil
  166. }
  167. // Check if this is a MessageSet extension field.
  168. xt, err = o.Resolver.FindExtensionByName(xtName + ".message_set_extension")
  169. if err == nil && isMessageSetExtension(xt) {
  170. return xt, nil
  171. }
  172. return nil, protoregistry.NotFound
  173. }
  174. // unmarshalSingular unmarshals given text.Value into the non-repeated field.
  175. func (o UnmarshalOptions) unmarshalSingular(input text.Value, fd pref.FieldDescriptor, knownFields pref.KnownFields) error {
  176. num := fd.Number()
  177. var nerr errors.NonFatal
  178. var val pref.Value
  179. switch fd.Kind() {
  180. case pref.MessageKind, pref.GroupKind:
  181. if input.Type() != text.Message {
  182. return errors.New("%v contains invalid message/group value: %v", fd.FullName(), input)
  183. }
  184. m := knownFields.NewMessage(num)
  185. if err := o.unmarshalMessage(input.Message(), m); !nerr.Merge(err) {
  186. return err
  187. }
  188. val = pref.ValueOf(m)
  189. default:
  190. var err error
  191. val, err = unmarshalScalar(input, fd)
  192. if !nerr.Merge(err) {
  193. return err
  194. }
  195. }
  196. knownFields.Set(num, val)
  197. return nerr.E
  198. }
  199. // unmarshalRepeated unmarshals given text.Value into a repeated field. Caller should only
  200. // call this for cardinality=repeated.
  201. func (o UnmarshalOptions) unmarshalRepeated(input text.Value, fd pref.FieldDescriptor, knownFields pref.KnownFields) error {
  202. var items []text.Value
  203. // If input is not a list, turn it into a list.
  204. if input.Type() != text.List {
  205. items = []text.Value{input}
  206. } else {
  207. items = input.List()
  208. }
  209. var nerr errors.NonFatal
  210. num := fd.Number()
  211. val := knownFields.Get(num)
  212. if !fd.IsMap() {
  213. if err := o.unmarshalList(items, fd, val.List()); !nerr.Merge(err) {
  214. return err
  215. }
  216. } else {
  217. if err := o.unmarshalMap(items, fd, val.Map()); !nerr.Merge(err) {
  218. return err
  219. }
  220. }
  221. return nerr.E
  222. }
  223. // unmarshalScalar converts the given text.Value to a scalar/enum protoreflect.Value specified in
  224. // the given FieldDescriptor. Caller should not pass in a FieldDescriptor for a message/group kind.
  225. func unmarshalScalar(input text.Value, fd pref.FieldDescriptor) (pref.Value, error) {
  226. const b32 = false
  227. const b64 = true
  228. switch kind := fd.Kind(); kind {
  229. case pref.BoolKind:
  230. if b, ok := input.Bool(); ok {
  231. return pref.ValueOf(bool(b)), nil
  232. }
  233. case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
  234. if n, ok := input.Int(b32); ok {
  235. return pref.ValueOf(int32(n)), nil
  236. }
  237. case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
  238. if n, ok := input.Int(b64); ok {
  239. return pref.ValueOf(int64(n)), nil
  240. }
  241. case pref.Uint32Kind, pref.Fixed32Kind:
  242. if n, ok := input.Uint(b32); ok {
  243. return pref.ValueOf(uint32(n)), nil
  244. }
  245. case pref.Uint64Kind, pref.Fixed64Kind:
  246. if n, ok := input.Uint(b64); ok {
  247. return pref.ValueOf(uint64(n)), nil
  248. }
  249. case pref.FloatKind:
  250. if n, ok := input.Float(b32); ok {
  251. return pref.ValueOf(float32(n)), nil
  252. }
  253. case pref.DoubleKind:
  254. if n, ok := input.Float(b64); ok {
  255. return pref.ValueOf(float64(n)), nil
  256. }
  257. case pref.StringKind:
  258. if input.Type() == text.String {
  259. return pref.ValueOf(string(input.String())), nil
  260. }
  261. case pref.BytesKind:
  262. if input.Type() == text.String {
  263. return pref.ValueOf([]byte(input.String())), nil
  264. }
  265. case pref.EnumKind:
  266. // If input is int32, use directly.
  267. if n, ok := input.Int(b32); ok {
  268. return pref.ValueOf(pref.EnumNumber(n)), nil
  269. }
  270. if name, ok := input.Name(); ok {
  271. // Lookup EnumNumber based on name.
  272. if enumVal := fd.EnumType().Values().ByName(name); enumVal != nil {
  273. return pref.ValueOf(enumVal.Number()), nil
  274. }
  275. }
  276. default:
  277. panic(fmt.Sprintf("invalid scalar kind %v", kind))
  278. }
  279. return pref.Value{}, errors.New("%v contains invalid scalar value: %v", fd.FullName(), input)
  280. }
  281. // unmarshalList unmarshals given []text.Value into given protoreflect.List.
  282. func (o UnmarshalOptions) unmarshalList(inputList []text.Value, fd pref.FieldDescriptor, list pref.List) error {
  283. var nerr errors.NonFatal
  284. switch fd.Kind() {
  285. case pref.MessageKind, pref.GroupKind:
  286. for _, input := range inputList {
  287. if input.Type() != text.Message {
  288. return errors.New("%v contains invalid message/group value: %v", fd.FullName(), input)
  289. }
  290. m := list.NewMessage()
  291. if err := o.unmarshalMessage(input.Message(), m); !nerr.Merge(err) {
  292. return err
  293. }
  294. list.Append(pref.ValueOf(m))
  295. }
  296. default:
  297. for _, input := range inputList {
  298. val, err := unmarshalScalar(input, fd)
  299. if !nerr.Merge(err) {
  300. return err
  301. }
  302. list.Append(val)
  303. }
  304. }
  305. return nerr.E
  306. }
  307. // unmarshalMap unmarshals given []text.Value into given protoreflect.Map.
  308. func (o UnmarshalOptions) unmarshalMap(input []text.Value, fd pref.FieldDescriptor, mmap pref.Map) error {
  309. var nerr errors.NonFatal
  310. fields := fd.MessageType().Fields()
  311. keyDesc := fields.ByNumber(1)
  312. valDesc := fields.ByNumber(2)
  313. // Determine ahead whether map entry is a scalar type or a message type in order to call the
  314. // appropriate unmarshalMapValue func inside the for loop below.
  315. unmarshalMapValue := unmarshalMapScalarValue
  316. switch valDesc.Kind() {
  317. case pref.MessageKind, pref.GroupKind:
  318. unmarshalMapValue = o.unmarshalMapMessageValue
  319. }
  320. for _, entry := range input {
  321. if entry.Type() != text.Message {
  322. return errors.New("%v contains invalid map entry: %v", fd.FullName(), entry)
  323. }
  324. tkey, tval, err := parseMapEntry(entry.Message(), fd.FullName())
  325. if !nerr.Merge(err) {
  326. return err
  327. }
  328. pkey, err := unmarshalMapKey(tkey, keyDesc)
  329. if !nerr.Merge(err) {
  330. return err
  331. }
  332. err = unmarshalMapValue(tval, pkey, valDesc, mmap)
  333. if !nerr.Merge(err) {
  334. return err
  335. }
  336. }
  337. return nerr.E
  338. }
  339. // parseMapEntry parses [][2]text.Value for field names key and value, and return corresponding
  340. // field values. If there are duplicate field names, the value for the last field is returned. If
  341. // the field name does not exist, it will return the zero value of text.Value. It will return an
  342. // error if there are unknown field names.
  343. func parseMapEntry(mapEntry [][2]text.Value, name pref.FullName) (key text.Value, value text.Value, err error) {
  344. for _, field := range mapEntry {
  345. keyStr, ok := field[0].Name()
  346. if ok {
  347. switch keyStr {
  348. case "key":
  349. if key.Type() != 0 {
  350. return key, value, errors.New("%v contains duplicate key field", name)
  351. }
  352. key = field[1]
  353. case "value":
  354. if value.Type() != 0 {
  355. return key, value, errors.New("%v contains duplicate value field", name)
  356. }
  357. value = field[1]
  358. default:
  359. ok = false
  360. }
  361. }
  362. if !ok {
  363. // TODO: Do not return error if ignore unknown option is added and enabled.
  364. return key, value, errors.New("%v contains unknown map entry name: %v", name, field[0])
  365. }
  366. }
  367. return key, value, nil
  368. }
  369. // unmarshalMapKey converts given text.Value into a protoreflect.MapKey. A map key type is any
  370. // integral or string type.
  371. func unmarshalMapKey(input text.Value, fd pref.FieldDescriptor) (pref.MapKey, error) {
  372. // If input is not set, use the zero value.
  373. if input.Type() == 0 {
  374. return fd.Default().MapKey(), nil
  375. }
  376. val, err := unmarshalScalar(input, fd)
  377. if err != nil {
  378. return pref.MapKey{}, errors.New("%v contains invalid key: %v", fd.FullName(), input)
  379. }
  380. return val.MapKey(), nil
  381. }
  382. // unmarshalMapMessageValue unmarshals given message-type text.Value into a protoreflect.Map for
  383. // the given MapKey.
  384. func (o UnmarshalOptions) unmarshalMapMessageValue(input text.Value, pkey pref.MapKey, _ pref.FieldDescriptor, mmap pref.Map) error {
  385. var nerr errors.NonFatal
  386. var value [][2]text.Value
  387. if input.Type() != 0 {
  388. value = input.Message()
  389. }
  390. m := mmap.NewMessage()
  391. if err := o.unmarshalMessage(value, m); !nerr.Merge(err) {
  392. return err
  393. }
  394. mmap.Set(pkey, pref.ValueOf(m))
  395. return nerr.E
  396. }
  397. // unmarshalMapScalarValue unmarshals given scalar-type text.Value into a protoreflect.Map
  398. // for the given MapKey.
  399. func unmarshalMapScalarValue(input text.Value, pkey pref.MapKey, fd pref.FieldDescriptor, mmap pref.Map) error {
  400. var val pref.Value
  401. if input.Type() == 0 {
  402. val = fd.Default()
  403. } else {
  404. var err error
  405. val, err = unmarshalScalar(input, fd)
  406. if err != nil {
  407. return err
  408. }
  409. }
  410. mmap.Set(pkey, val)
  411. return nil
  412. }
  413. // isExpandedAny returns true if given [][2]text.Value may be an expanded Any that contains only one
  414. // field with key type of text.String type and value type of text.Message.
  415. func isExpandedAny(tmsg [][2]text.Value) bool {
  416. if len(tmsg) != 1 {
  417. return false
  418. }
  419. field := tmsg[0]
  420. return field[0].Type() == text.String && field[1].Type() == text.Message
  421. }
  422. // unmarshalAny unmarshals an expanded Any textproto. This method assumes that the given
  423. // tfield has key type of text.String and value type of text.Message.
  424. func (o UnmarshalOptions) unmarshalAny(tfield [2]text.Value, knownFields pref.KnownFields) error {
  425. var nerr errors.NonFatal
  426. typeURL := tfield[0].String()
  427. value := tfield[1].Message()
  428. mt, err := o.Resolver.FindMessageByURL(typeURL)
  429. if !nerr.Merge(err) {
  430. return errors.New("unable to resolve message [%v]: %v", typeURL, err)
  431. }
  432. // Create new message for the embedded message type and unmarshal the
  433. // value into it.
  434. m := mt.New()
  435. if err := o.unmarshalMessage(value, m); !nerr.Merge(err) {
  436. return err
  437. }
  438. // Serialize the embedded message and assign the resulting bytes to the value field.
  439. b, err := proto.MarshalOptions{Deterministic: true}.Marshal(m.Interface())
  440. if !nerr.Merge(err) {
  441. return err
  442. }
  443. knownFields.Set(pref.FieldNumber(1), pref.ValueOf(typeURL))
  444. knownFields.Set(pref.FieldNumber(2), pref.ValueOf(b))
  445. return nerr.E
  446. }