decode.go 15 KB

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