decode.go 14 KB

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