decode.go 15 KB

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