decode.go 15 KB

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