decode.go 15 KB

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