decode.go 14 KB

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