decode.go 15 KB

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