decode.go 15 KB

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