decode.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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.TypeDescriptor()
  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. val = m.NewField(fd)
  190. if err := o.unmarshalMessage(input.Message(), val.Message()); err != nil {
  191. return err
  192. }
  193. default:
  194. var err error
  195. val, err = unmarshalScalar(input, fd)
  196. if err != nil {
  197. return err
  198. }
  199. }
  200. m.Set(fd, val)
  201. return nil
  202. }
  203. // unmarshalScalar converts the given text.Value to a scalar/enum protoreflect.Value specified in
  204. // the given FieldDescriptor. Caller should not pass in a FieldDescriptor for a message/group kind.
  205. func unmarshalScalar(input text.Value, fd pref.FieldDescriptor) (pref.Value, error) {
  206. const b32 = false
  207. const b64 = true
  208. switch kind := fd.Kind(); kind {
  209. case pref.BoolKind:
  210. if b, ok := input.Bool(); ok {
  211. return pref.ValueOf(bool(b)), nil
  212. }
  213. case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
  214. if n, ok := input.Int(b32); ok {
  215. return pref.ValueOf(int32(n)), nil
  216. }
  217. case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
  218. if n, ok := input.Int(b64); ok {
  219. return pref.ValueOf(int64(n)), nil
  220. }
  221. case pref.Uint32Kind, pref.Fixed32Kind:
  222. if n, ok := input.Uint(b32); ok {
  223. return pref.ValueOf(uint32(n)), nil
  224. }
  225. case pref.Uint64Kind, pref.Fixed64Kind:
  226. if n, ok := input.Uint(b64); ok {
  227. return pref.ValueOf(uint64(n)), nil
  228. }
  229. case pref.FloatKind:
  230. if n, ok := input.Float(b32); ok {
  231. return pref.ValueOf(float32(n)), nil
  232. }
  233. case pref.DoubleKind:
  234. if n, ok := input.Float(b64); ok {
  235. return pref.ValueOf(float64(n)), nil
  236. }
  237. case pref.StringKind:
  238. if input.Type() == text.String {
  239. s := input.String()
  240. if utf8.ValidString(s) {
  241. return pref.ValueOf(s), nil
  242. }
  243. return pref.Value{}, errors.InvalidUTF8(string(fd.FullName()))
  244. }
  245. case pref.BytesKind:
  246. if input.Type() == text.String {
  247. return pref.ValueOf([]byte(input.String())), nil
  248. }
  249. case pref.EnumKind:
  250. // If input is int32, use directly.
  251. if n, ok := input.Int(b32); ok {
  252. return pref.ValueOf(pref.EnumNumber(n)), nil
  253. }
  254. if name, ok := input.Name(); ok {
  255. // Lookup EnumNumber based on name.
  256. if enumVal := fd.Enum().Values().ByName(name); enumVal != nil {
  257. return pref.ValueOf(enumVal.Number()), nil
  258. }
  259. }
  260. default:
  261. panic(fmt.Sprintf("invalid scalar kind %v", kind))
  262. }
  263. return pref.Value{}, errors.New("%v contains invalid scalar value: %v", fd.FullName(), input)
  264. }
  265. // unmarshalList unmarshals given []text.Value into given protoreflect.List.
  266. func (o UnmarshalOptions) unmarshalList(inputList []text.Value, fd pref.FieldDescriptor, list pref.List) error {
  267. switch fd.Kind() {
  268. case pref.MessageKind, pref.GroupKind:
  269. for _, input := range inputList {
  270. if input.Type() != text.Message {
  271. return errors.New("%v contains invalid message/group value: %v", fd.FullName(), input)
  272. }
  273. val := list.NewElement()
  274. if err := o.unmarshalMessage(input.Message(), val.Message()); err != nil {
  275. return err
  276. }
  277. list.Append(val)
  278. }
  279. default:
  280. for _, input := range inputList {
  281. val, err := unmarshalScalar(input, fd)
  282. if err != nil {
  283. return err
  284. }
  285. list.Append(val)
  286. }
  287. }
  288. return nil
  289. }
  290. // unmarshalMap unmarshals given []text.Value into given protoreflect.Map.
  291. func (o UnmarshalOptions) unmarshalMap(input []text.Value, fd pref.FieldDescriptor, mmap pref.Map) error {
  292. // Determine ahead whether map entry is a scalar type or a message type in order to call the
  293. // appropriate unmarshalMapValue func inside the for loop below.
  294. unmarshalMapValue := unmarshalMapScalarValue
  295. switch fd.MapValue().Kind() {
  296. case pref.MessageKind, pref.GroupKind:
  297. unmarshalMapValue = o.unmarshalMapMessageValue
  298. }
  299. for _, entry := range input {
  300. if entry.Type() != text.Message {
  301. return errors.New("%v contains invalid map entry: %v", fd.FullName(), entry)
  302. }
  303. tkey, tval, err := parseMapEntry(entry.Message(), fd.FullName())
  304. if err != nil {
  305. return err
  306. }
  307. pkey, err := unmarshalMapKey(tkey, fd.MapKey())
  308. if err != nil {
  309. return err
  310. }
  311. err = unmarshalMapValue(tval, pkey, fd.MapValue(), mmap)
  312. if err != nil {
  313. return err
  314. }
  315. }
  316. return nil
  317. }
  318. // parseMapEntry parses [][2]text.Value for field names key and value, and return corresponding
  319. // field values. If there are duplicate field names, the value for the last field is returned. If
  320. // the field name does not exist, it will return the zero value of text.Value. It will return an
  321. // error if there are unknown field names.
  322. func parseMapEntry(mapEntry [][2]text.Value, name pref.FullName) (key text.Value, value text.Value, err error) {
  323. for _, field := range mapEntry {
  324. keyStr, ok := field[0].Name()
  325. if ok {
  326. switch keyStr {
  327. case "key":
  328. if key.Type() != 0 {
  329. return key, value, errors.New("%v contains duplicate key field", name)
  330. }
  331. key = field[1]
  332. case "value":
  333. if value.Type() != 0 {
  334. return key, value, errors.New("%v contains duplicate value field", name)
  335. }
  336. value = field[1]
  337. default:
  338. ok = false
  339. }
  340. }
  341. if !ok {
  342. // TODO: Do not return error if ignore unknown option is added and enabled.
  343. return key, value, errors.New("%v contains unknown map entry name: %v", name, field[0])
  344. }
  345. }
  346. return key, value, nil
  347. }
  348. // unmarshalMapKey converts given text.Value into a protoreflect.MapKey. A map key type is any
  349. // integral or string type.
  350. func unmarshalMapKey(input text.Value, fd pref.FieldDescriptor) (pref.MapKey, error) {
  351. // If input is not set, use the zero value.
  352. if input.Type() == 0 {
  353. return fd.Default().MapKey(), nil
  354. }
  355. val, err := unmarshalScalar(input, fd)
  356. if err != nil {
  357. return pref.MapKey{}, errors.New("%v contains invalid key: %v", fd.FullName(), input)
  358. }
  359. return val.MapKey(), nil
  360. }
  361. // unmarshalMapMessageValue unmarshals given message-type text.Value into a protoreflect.Map for
  362. // the given MapKey.
  363. func (o UnmarshalOptions) unmarshalMapMessageValue(input text.Value, pkey pref.MapKey, _ pref.FieldDescriptor, mmap pref.Map) error {
  364. var value [][2]text.Value
  365. if input.Type() != 0 {
  366. value = input.Message()
  367. }
  368. val := mmap.NewValue()
  369. if err := o.unmarshalMessage(value, val.Message()); err != nil {
  370. return err
  371. }
  372. mmap.Set(pkey, val)
  373. return nil
  374. }
  375. // unmarshalMapScalarValue unmarshals given scalar-type text.Value into a protoreflect.Map
  376. // for the given MapKey.
  377. func unmarshalMapScalarValue(input text.Value, pkey pref.MapKey, fd pref.FieldDescriptor, mmap pref.Map) error {
  378. var val pref.Value
  379. if input.Type() == 0 {
  380. val = fd.Default()
  381. } else {
  382. var err error
  383. val, err = unmarshalScalar(input, fd)
  384. if err != nil {
  385. return err
  386. }
  387. }
  388. mmap.Set(pkey, val)
  389. return nil
  390. }
  391. // isExpandedAny returns true if given [][2]text.Value may be an expanded Any that contains only one
  392. // field with key type of text.String type and value type of text.Message.
  393. func isExpandedAny(tmsg [][2]text.Value) bool {
  394. if len(tmsg) != 1 {
  395. return false
  396. }
  397. field := tmsg[0]
  398. return field[0].Type() == text.String && field[1].Type() == text.Message
  399. }
  400. // unmarshalAny unmarshals an expanded Any textproto. This method assumes that the given
  401. // tfield has key type of text.String and value type of text.Message.
  402. func (o UnmarshalOptions) unmarshalAny(tfield [2]text.Value, m pref.Message) error {
  403. typeURL := tfield[0].String()
  404. value := tfield[1].Message()
  405. mt, err := o.Resolver.FindMessageByURL(typeURL)
  406. if err != nil {
  407. return errors.New("unable to resolve message [%v]: %v", typeURL, err)
  408. }
  409. // Create new message for the embedded message type and unmarshal the
  410. // value into it.
  411. m2 := mt.New()
  412. if err := o.unmarshalMessage(value, m2); err != nil {
  413. return err
  414. }
  415. // Serialize the embedded message and assign the resulting bytes to the value field.
  416. b, err := proto.MarshalOptions{
  417. AllowPartial: true, // never check required fields inside an Any
  418. Deterministic: true,
  419. }.Marshal(m2.Interface())
  420. if err != nil {
  421. return err
  422. }
  423. fds := m.Descriptor().Fields()
  424. fdType := fds.ByNumber(fieldnum.Any_TypeUrl)
  425. fdValue := fds.ByNumber(fieldnum.Any_Value)
  426. m.Set(fdType, pref.ValueOf(typeURL))
  427. m.Set(fdValue, pref.ValueOf(b))
  428. return nil
  429. }