decode.go 15 KB

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