decode.go 14 KB

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