jsonpb.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242
  1. // Copyright 2015 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 jsonpb provides marshaling and unmarshaling between protocol buffers and JSON.
  5. // It follows the specification at https://developers.google.com/protocol-buffers/docs/proto3#json.
  6. //
  7. // This package produces a different output than the standard "encoding/json" package,
  8. // which does not operate correctly on protocol buffers.
  9. package jsonpb
  10. import (
  11. "bytes"
  12. "encoding/json"
  13. "errors"
  14. "fmt"
  15. "io"
  16. "math"
  17. "reflect"
  18. "sort"
  19. "strconv"
  20. "strings"
  21. "time"
  22. "github.com/golang/protobuf/proto"
  23. stpb "github.com/golang/protobuf/ptypes/struct"
  24. )
  25. const secondInNanos = int64(time.Second / time.Nanosecond)
  26. // Marshaler is a configurable object for converting between
  27. // protocol buffer objects and a JSON representation for them.
  28. type Marshaler struct {
  29. // Whether to render enum values as integers, as opposed to string values.
  30. EnumsAsInts bool
  31. // Whether to render fields with zero values.
  32. EmitDefaults bool
  33. // A string to indent each level by. The presence of this field will
  34. // also cause a space to appear between the field separator and
  35. // value, and for newlines to be appear between fields and array
  36. // elements.
  37. Indent string
  38. // Whether to use the original (.proto) name for fields.
  39. OrigName bool
  40. // A custom URL resolver to use when marshaling Any messages to JSON.
  41. // If unset, the default resolution strategy is to extract the
  42. // fully-qualified type name from the type URL and pass that to
  43. // proto.MessageType(string).
  44. AnyResolver AnyResolver
  45. }
  46. // AnyResolver takes a type URL, present in an Any message, and resolves it into
  47. // an instance of the associated message.
  48. type AnyResolver interface {
  49. Resolve(typeUrl string) (proto.Message, error)
  50. }
  51. func defaultResolveAny(typeUrl string) (proto.Message, error) {
  52. // Only the part of typeUrl after the last slash is relevant.
  53. mname := typeUrl
  54. if slash := strings.LastIndex(mname, "/"); slash >= 0 {
  55. mname = mname[slash+1:]
  56. }
  57. mt := proto.MessageType(mname)
  58. if mt == nil {
  59. return nil, fmt.Errorf("unknown message type %q", mname)
  60. }
  61. return reflect.New(mt.Elem()).Interface().(proto.Message), nil
  62. }
  63. // JSONPBMarshaler is implemented by protobuf messages that customize the
  64. // way they are marshaled to JSON. Messages that implement this should
  65. // also implement JSONPBUnmarshaler so that the custom format can be
  66. // parsed.
  67. //
  68. // The JSON marshaling must follow the proto to JSON specification:
  69. // https://developers.google.com/protocol-buffers/docs/proto3#json
  70. type JSONPBMarshaler interface {
  71. MarshalJSONPB(*Marshaler) ([]byte, error)
  72. }
  73. // JSONPBUnmarshaler is implemented by protobuf messages that customize
  74. // the way they are unmarshaled from JSON. Messages that implement this
  75. // should also implement JSONPBMarshaler so that the custom format can be
  76. // produced.
  77. //
  78. // The JSON unmarshaling must follow the JSON to proto specification:
  79. // https://developers.google.com/protocol-buffers/docs/proto3#json
  80. type JSONPBUnmarshaler interface {
  81. UnmarshalJSONPB(*Unmarshaler, []byte) error
  82. }
  83. // Marshal marshals a protocol buffer into JSON.
  84. func (m *Marshaler) Marshal(out io.Writer, pb proto.Message) error {
  85. v := reflect.ValueOf(pb)
  86. if pb == nil || (v.Kind() == reflect.Ptr && v.IsNil()) {
  87. return errors.New("Marshal called with nil")
  88. }
  89. // Check for unset required fields first.
  90. if err := checkRequiredFields(pb); err != nil {
  91. return err
  92. }
  93. writer := &errWriter{writer: out}
  94. return m.marshalObject(writer, pb, "", "")
  95. }
  96. // MarshalToString converts a protocol buffer object to JSON string.
  97. func (m *Marshaler) MarshalToString(pb proto.Message) (string, error) {
  98. var buf bytes.Buffer
  99. if err := m.Marshal(&buf, pb); err != nil {
  100. return "", err
  101. }
  102. return buf.String(), nil
  103. }
  104. type int32Slice []int32
  105. var nonFinite = map[string]float64{
  106. `"NaN"`: math.NaN(),
  107. `"Infinity"`: math.Inf(1),
  108. `"-Infinity"`: math.Inf(-1),
  109. }
  110. // For sorting extensions ids to ensure stable output.
  111. func (s int32Slice) Len() int { return len(s) }
  112. func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] }
  113. func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  114. type wkt interface {
  115. XXX_WellKnownType() string
  116. }
  117. // marshalObject writes a struct to the Writer.
  118. func (m *Marshaler) marshalObject(out *errWriter, v proto.Message, indent, typeURL string) error {
  119. if jsm, ok := v.(JSONPBMarshaler); ok {
  120. b, err := jsm.MarshalJSONPB(m)
  121. if err != nil {
  122. return err
  123. }
  124. if typeURL != "" {
  125. // we are marshaling this object to an Any type
  126. var js map[string]*json.RawMessage
  127. if err = json.Unmarshal(b, &js); err != nil {
  128. return fmt.Errorf("type %T produced invalid JSON: %v", v, err)
  129. }
  130. turl, err := json.Marshal(typeURL)
  131. if err != nil {
  132. return fmt.Errorf("failed to marshal type URL %q to JSON: %v", typeURL, err)
  133. }
  134. js["@type"] = (*json.RawMessage)(&turl)
  135. if b, err = json.Marshal(js); err != nil {
  136. return err
  137. }
  138. }
  139. out.write(string(b))
  140. return out.err
  141. }
  142. s := reflect.ValueOf(v).Elem()
  143. // Handle well-known types.
  144. if wkt, ok := v.(wkt); ok {
  145. switch wkt.XXX_WellKnownType() {
  146. case "DoubleValue", "FloatValue", "Int64Value", "UInt64Value",
  147. "Int32Value", "UInt32Value", "BoolValue", "StringValue", "BytesValue":
  148. // "Wrappers use the same representation in JSON
  149. // as the wrapped primitive type, ..."
  150. sprop := proto.GetProperties(s.Type())
  151. return m.marshalValue(out, sprop.Prop[0], s.Field(0), indent)
  152. case "Any":
  153. // Any is a bit more involved.
  154. return m.marshalAny(out, v, indent)
  155. case "Duration":
  156. // "Generated output always contains 0, 3, 6, or 9 fractional digits,
  157. // depending on required precision."
  158. s, ns := s.Field(0).Int(), s.Field(1).Int()
  159. if ns <= -secondInNanos || ns >= secondInNanos {
  160. return fmt.Errorf("ns out of range (%v, %v)", -secondInNanos, secondInNanos)
  161. }
  162. if (s > 0 && ns < 0) || (s < 0 && ns > 0) {
  163. return errors.New("signs of seconds and nanos do not match")
  164. }
  165. if s < 0 {
  166. ns = -ns
  167. }
  168. x := fmt.Sprintf("%d.%09d", s, ns)
  169. x = strings.TrimSuffix(x, "000")
  170. x = strings.TrimSuffix(x, "000")
  171. x = strings.TrimSuffix(x, ".000")
  172. out.write(`"`)
  173. out.write(x)
  174. out.write(`s"`)
  175. return out.err
  176. case "Struct", "ListValue":
  177. // Let marshalValue handle the `Struct.fields` map or the `ListValue.values` slice.
  178. // TODO: pass the correct Properties if needed.
  179. return m.marshalValue(out, &proto.Properties{}, s.Field(0), indent)
  180. case "Timestamp":
  181. // "RFC 3339, where generated output will always be Z-normalized
  182. // and uses 0, 3, 6 or 9 fractional digits."
  183. s, ns := s.Field(0).Int(), s.Field(1).Int()
  184. if ns < 0 || ns >= secondInNanos {
  185. return fmt.Errorf("ns out of range [0, %v)", secondInNanos)
  186. }
  187. t := time.Unix(s, ns).UTC()
  188. // time.RFC3339Nano isn't exactly right (we need to get 3/6/9 fractional digits).
  189. x := t.Format("2006-01-02T15:04:05.000000000")
  190. x = strings.TrimSuffix(x, "000")
  191. x = strings.TrimSuffix(x, "000")
  192. x = strings.TrimSuffix(x, ".000")
  193. out.write(`"`)
  194. out.write(x)
  195. out.write(`Z"`)
  196. return out.err
  197. case "Value":
  198. // Value has a single oneof.
  199. kind := s.Field(0)
  200. if kind.IsNil() {
  201. // "absence of any variant indicates an error"
  202. return errors.New("nil Value")
  203. }
  204. // oneof -> *T -> T -> T.F
  205. x := kind.Elem().Elem().Field(0)
  206. // TODO: pass the correct Properties if needed.
  207. return m.marshalValue(out, &proto.Properties{}, x, indent)
  208. }
  209. }
  210. out.write("{")
  211. if m.Indent != "" {
  212. out.write("\n")
  213. }
  214. firstField := true
  215. if typeURL != "" {
  216. if err := m.marshalTypeURL(out, indent, typeURL); err != nil {
  217. return err
  218. }
  219. firstField = false
  220. }
  221. for i := 0; i < s.NumField(); i++ {
  222. value := s.Field(i)
  223. valueField := s.Type().Field(i)
  224. if strings.HasPrefix(valueField.Name, "XXX_") {
  225. continue
  226. }
  227. // IsNil will panic on most value kinds.
  228. switch value.Kind() {
  229. case reflect.Chan, reflect.Func, reflect.Interface:
  230. if value.IsNil() {
  231. continue
  232. }
  233. }
  234. if !m.EmitDefaults {
  235. switch value.Kind() {
  236. case reflect.Bool:
  237. if !value.Bool() {
  238. continue
  239. }
  240. case reflect.Int32, reflect.Int64:
  241. if value.Int() == 0 {
  242. continue
  243. }
  244. case reflect.Uint32, reflect.Uint64:
  245. if value.Uint() == 0 {
  246. continue
  247. }
  248. case reflect.Float32, reflect.Float64:
  249. if value.Float() == 0 {
  250. continue
  251. }
  252. case reflect.String:
  253. if value.Len() == 0 {
  254. continue
  255. }
  256. case reflect.Map, reflect.Ptr, reflect.Slice:
  257. if value.IsNil() {
  258. continue
  259. }
  260. }
  261. }
  262. // Oneof fields need special handling.
  263. if valueField.Tag.Get("protobuf_oneof") != "" {
  264. // value is an interface containing &T{real_value}.
  265. sv := value.Elem().Elem() // interface -> *T -> T
  266. value = sv.Field(0)
  267. valueField = sv.Type().Field(0)
  268. }
  269. prop := jsonProperties(valueField, m.OrigName)
  270. if !firstField {
  271. m.writeSep(out)
  272. }
  273. if err := m.marshalField(out, prop, value, indent); err != nil {
  274. return err
  275. }
  276. firstField = false
  277. }
  278. // Handle proto2 extensions.
  279. if ep, ok := v.(proto.Message); ok {
  280. extensions := proto.RegisteredExtensions(v)
  281. // Sort extensions for stable output.
  282. ids := make([]int32, 0, len(extensions))
  283. for id, desc := range extensions {
  284. if !proto.HasExtension(ep, desc) {
  285. continue
  286. }
  287. ids = append(ids, id)
  288. }
  289. sort.Sort(int32Slice(ids))
  290. for _, id := range ids {
  291. desc := extensions[id]
  292. if desc == nil {
  293. // unknown extension
  294. continue
  295. }
  296. ext, extErr := proto.GetExtension(ep, desc)
  297. if extErr != nil {
  298. return extErr
  299. }
  300. value := reflect.ValueOf(ext)
  301. var prop proto.Properties
  302. prop.Parse(desc.Tag)
  303. prop.JSONName = fmt.Sprintf("[%s]", desc.Name)
  304. if !firstField {
  305. m.writeSep(out)
  306. }
  307. if err := m.marshalField(out, &prop, value, indent); err != nil {
  308. return err
  309. }
  310. firstField = false
  311. }
  312. }
  313. if m.Indent != "" {
  314. out.write("\n")
  315. out.write(indent)
  316. }
  317. out.write("}")
  318. return out.err
  319. }
  320. func (m *Marshaler) writeSep(out *errWriter) {
  321. if m.Indent != "" {
  322. out.write(",\n")
  323. } else {
  324. out.write(",")
  325. }
  326. }
  327. func (m *Marshaler) marshalAny(out *errWriter, any proto.Message, indent string) error {
  328. // "If the Any contains a value that has a special JSON mapping,
  329. // it will be converted as follows: {"@type": xxx, "value": yyy}.
  330. // Otherwise, the value will be converted into a JSON object,
  331. // and the "@type" field will be inserted to indicate the actual data type."
  332. v := reflect.ValueOf(any).Elem()
  333. turl := v.Field(0).String()
  334. val := v.Field(1).Bytes()
  335. var msg proto.Message
  336. var err error
  337. if m.AnyResolver != nil {
  338. msg, err = m.AnyResolver.Resolve(turl)
  339. } else {
  340. msg, err = defaultResolveAny(turl)
  341. }
  342. if err != nil {
  343. return err
  344. }
  345. if err := proto.Unmarshal(val, msg); err != nil {
  346. return err
  347. }
  348. if _, ok := msg.(wkt); ok {
  349. out.write("{")
  350. if m.Indent != "" {
  351. out.write("\n")
  352. }
  353. if err := m.marshalTypeURL(out, indent, turl); err != nil {
  354. return err
  355. }
  356. m.writeSep(out)
  357. if m.Indent != "" {
  358. out.write(indent)
  359. out.write(m.Indent)
  360. out.write(`"value": `)
  361. } else {
  362. out.write(`"value":`)
  363. }
  364. if err := m.marshalObject(out, msg, indent+m.Indent, ""); err != nil {
  365. return err
  366. }
  367. if m.Indent != "" {
  368. out.write("\n")
  369. out.write(indent)
  370. }
  371. out.write("}")
  372. return out.err
  373. }
  374. return m.marshalObject(out, msg, indent, turl)
  375. }
  376. func (m *Marshaler) marshalTypeURL(out *errWriter, indent, typeURL string) error {
  377. if m.Indent != "" {
  378. out.write(indent)
  379. out.write(m.Indent)
  380. }
  381. out.write(`"@type":`)
  382. if m.Indent != "" {
  383. out.write(" ")
  384. }
  385. b, err := json.Marshal(typeURL)
  386. if err != nil {
  387. return err
  388. }
  389. out.write(string(b))
  390. return out.err
  391. }
  392. // marshalField writes field description and value to the Writer.
  393. func (m *Marshaler) marshalField(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error {
  394. if m.Indent != "" {
  395. out.write(indent)
  396. out.write(m.Indent)
  397. }
  398. out.write(`"`)
  399. out.write(prop.JSONName)
  400. out.write(`":`)
  401. if m.Indent != "" {
  402. out.write(" ")
  403. }
  404. if err := m.marshalValue(out, prop, v, indent); err != nil {
  405. return err
  406. }
  407. return nil
  408. }
  409. // marshalValue writes the value to the Writer.
  410. func (m *Marshaler) marshalValue(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error {
  411. var err error
  412. v = reflect.Indirect(v)
  413. // Handle nil pointer
  414. if v.Kind() == reflect.Invalid {
  415. out.write("null")
  416. return out.err
  417. }
  418. // Handle repeated elements.
  419. if v.Kind() == reflect.Slice && v.Type().Elem().Kind() != reflect.Uint8 {
  420. out.write("[")
  421. comma := ""
  422. for i := 0; i < v.Len(); i++ {
  423. sliceVal := v.Index(i)
  424. out.write(comma)
  425. if m.Indent != "" {
  426. out.write("\n")
  427. out.write(indent)
  428. out.write(m.Indent)
  429. out.write(m.Indent)
  430. }
  431. if err := m.marshalValue(out, prop, sliceVal, indent+m.Indent); err != nil {
  432. return err
  433. }
  434. comma = ","
  435. }
  436. if m.Indent != "" {
  437. out.write("\n")
  438. out.write(indent)
  439. out.write(m.Indent)
  440. }
  441. out.write("]")
  442. return out.err
  443. }
  444. // Handle well-known types.
  445. // Most are handled up in marshalObject (because 99% are messages).
  446. if wkt, ok := v.Interface().(wkt); ok {
  447. switch wkt.XXX_WellKnownType() {
  448. case "NullValue":
  449. out.write("null")
  450. return out.err
  451. }
  452. }
  453. // Handle enumerations.
  454. if !m.EnumsAsInts && prop.Enum != "" {
  455. // Unknown enum values will are stringified by the proto library as their
  456. // value. Such values should _not_ be quoted or they will be interpreted
  457. // as an enum string instead of their value.
  458. enumStr := v.Interface().(fmt.Stringer).String()
  459. var valStr string
  460. if v.Kind() == reflect.Ptr {
  461. valStr = strconv.Itoa(int(v.Elem().Int()))
  462. } else {
  463. valStr = strconv.Itoa(int(v.Int()))
  464. }
  465. isKnownEnum := enumStr != valStr
  466. if isKnownEnum {
  467. out.write(`"`)
  468. }
  469. out.write(enumStr)
  470. if isKnownEnum {
  471. out.write(`"`)
  472. }
  473. return out.err
  474. }
  475. // Handle nested messages.
  476. if v.Kind() == reflect.Struct {
  477. return m.marshalObject(out, v.Addr().Interface().(proto.Message), indent+m.Indent, "")
  478. }
  479. // Handle maps.
  480. // Since Go randomizes map iteration, we sort keys for stable output.
  481. if v.Kind() == reflect.Map {
  482. out.write(`{`)
  483. keys := v.MapKeys()
  484. sort.Sort(mapKeys(keys))
  485. for i, k := range keys {
  486. if i > 0 {
  487. out.write(`,`)
  488. }
  489. if m.Indent != "" {
  490. out.write("\n")
  491. out.write(indent)
  492. out.write(m.Indent)
  493. out.write(m.Indent)
  494. }
  495. // TODO handle map key prop properly
  496. b, err := json.Marshal(k.Interface())
  497. if err != nil {
  498. return err
  499. }
  500. s := string(b)
  501. // If the JSON is not a string value, encode it again to make it one.
  502. if !strings.HasPrefix(s, `"`) {
  503. b, err := json.Marshal(s)
  504. if err != nil {
  505. return err
  506. }
  507. s = string(b)
  508. }
  509. out.write(s)
  510. out.write(`:`)
  511. if m.Indent != "" {
  512. out.write(` `)
  513. }
  514. vprop := prop
  515. if prop != nil && prop.MapValProp != nil {
  516. vprop = prop.MapValProp
  517. }
  518. if err := m.marshalValue(out, vprop, v.MapIndex(k), indent+m.Indent); err != nil {
  519. return err
  520. }
  521. }
  522. if m.Indent != "" {
  523. out.write("\n")
  524. out.write(indent)
  525. out.write(m.Indent)
  526. }
  527. out.write(`}`)
  528. return out.err
  529. }
  530. // Handle non-finite floats, e.g. NaN, Infinity and -Infinity.
  531. if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 {
  532. f := v.Float()
  533. var sval string
  534. switch {
  535. case math.IsInf(f, 1):
  536. sval = `"Infinity"`
  537. case math.IsInf(f, -1):
  538. sval = `"-Infinity"`
  539. case math.IsNaN(f):
  540. sval = `"NaN"`
  541. }
  542. if sval != "" {
  543. out.write(sval)
  544. return out.err
  545. }
  546. }
  547. // Default handling defers to the encoding/json library.
  548. b, err := json.Marshal(v.Interface())
  549. if err != nil {
  550. return err
  551. }
  552. needToQuote := string(b[0]) != `"` && (v.Kind() == reflect.Int64 || v.Kind() == reflect.Uint64)
  553. if needToQuote {
  554. out.write(`"`)
  555. }
  556. out.write(string(b))
  557. if needToQuote {
  558. out.write(`"`)
  559. }
  560. return out.err
  561. }
  562. // Unmarshaler is a configurable object for converting from a JSON
  563. // representation to a protocol buffer object.
  564. type Unmarshaler struct {
  565. // Whether to allow messages to contain unknown fields, as opposed to
  566. // failing to unmarshal.
  567. AllowUnknownFields bool
  568. // A custom URL resolver to use when unmarshaling Any messages from JSON.
  569. // If unset, the default resolution strategy is to extract the
  570. // fully-qualified type name from the type URL and pass that to
  571. // proto.MessageType(string).
  572. AnyResolver AnyResolver
  573. }
  574. // UnmarshalNext unmarshals the next protocol buffer from a JSON object stream.
  575. // This function is lenient and will decode any options permutations of the
  576. // related Marshaler.
  577. func (u *Unmarshaler) UnmarshalNext(dec *json.Decoder, pb proto.Message) error {
  578. inputValue := json.RawMessage{}
  579. if err := dec.Decode(&inputValue); err != nil {
  580. return err
  581. }
  582. if err := u.unmarshalValue(reflect.ValueOf(pb).Elem(), inputValue, nil); err != nil {
  583. return err
  584. }
  585. return checkRequiredFields(pb)
  586. }
  587. // Unmarshal unmarshals a JSON object stream into a protocol
  588. // buffer. This function is lenient and will decode any options
  589. // permutations of the related Marshaler.
  590. func (u *Unmarshaler) Unmarshal(r io.Reader, pb proto.Message) error {
  591. dec := json.NewDecoder(r)
  592. return u.UnmarshalNext(dec, pb)
  593. }
  594. // UnmarshalNext unmarshals the next protocol buffer from a JSON object stream.
  595. // This function is lenient and will decode any options permutations of the
  596. // related Marshaler.
  597. func UnmarshalNext(dec *json.Decoder, pb proto.Message) error {
  598. return new(Unmarshaler).UnmarshalNext(dec, pb)
  599. }
  600. // Unmarshal unmarshals a JSON object stream into a protocol
  601. // buffer. This function is lenient and will decode any options
  602. // permutations of the related Marshaler.
  603. func Unmarshal(r io.Reader, pb proto.Message) error {
  604. return new(Unmarshaler).Unmarshal(r, pb)
  605. }
  606. // UnmarshalString will populate the fields of a protocol buffer based
  607. // on a JSON string. This function is lenient and will decode any options
  608. // permutations of the related Marshaler.
  609. func UnmarshalString(str string, pb proto.Message) error {
  610. return new(Unmarshaler).Unmarshal(strings.NewReader(str), pb)
  611. }
  612. // unmarshalValue converts/copies a value into the target.
  613. // prop may be nil.
  614. func (u *Unmarshaler) unmarshalValue(target reflect.Value, inputValue json.RawMessage, prop *proto.Properties) error {
  615. targetType := target.Type()
  616. // Allocate memory for pointer fields.
  617. if targetType.Kind() == reflect.Ptr {
  618. // If input value is "null" and target is a pointer type, then the field should be treated as not set
  619. // UNLESS the target is structpb.Value, in which case it should be set to structpb.NullValue.
  620. _, isJSONPBUnmarshaler := target.Interface().(JSONPBUnmarshaler)
  621. if string(inputValue) == "null" && targetType != reflect.TypeOf(&stpb.Value{}) && !isJSONPBUnmarshaler {
  622. return nil
  623. }
  624. target.Set(reflect.New(targetType.Elem()))
  625. return u.unmarshalValue(target.Elem(), inputValue, prop)
  626. }
  627. if jsu, ok := target.Addr().Interface().(JSONPBUnmarshaler); ok {
  628. return jsu.UnmarshalJSONPB(u, []byte(inputValue))
  629. }
  630. // Handle well-known types that are not pointers.
  631. if w, ok := target.Addr().Interface().(wkt); ok {
  632. switch w.XXX_WellKnownType() {
  633. case "DoubleValue", "FloatValue", "Int64Value", "UInt64Value",
  634. "Int32Value", "UInt32Value", "BoolValue", "StringValue", "BytesValue":
  635. return u.unmarshalValue(target.Field(0), inputValue, prop)
  636. case "Any":
  637. // Use json.RawMessage pointer type instead of value to support pre-1.8 version.
  638. // 1.8 changed RawMessage.MarshalJSON from pointer type to value type, see
  639. // https://github.com/golang/go/issues/14493
  640. var jsonFields map[string]*json.RawMessage
  641. if err := json.Unmarshal(inputValue, &jsonFields); err != nil {
  642. return err
  643. }
  644. val, ok := jsonFields["@type"]
  645. if !ok || val == nil {
  646. return errors.New("Any JSON doesn't have '@type'")
  647. }
  648. var turl string
  649. if err := json.Unmarshal([]byte(*val), &turl); err != nil {
  650. return fmt.Errorf("can't unmarshal Any's '@type': %q", *val)
  651. }
  652. target.Field(0).SetString(turl)
  653. var m proto.Message
  654. var err error
  655. if u.AnyResolver != nil {
  656. m, err = u.AnyResolver.Resolve(turl)
  657. } else {
  658. m, err = defaultResolveAny(turl)
  659. }
  660. if err != nil {
  661. return err
  662. }
  663. if _, ok := m.(wkt); ok {
  664. val, ok := jsonFields["value"]
  665. if !ok {
  666. return errors.New("Any JSON doesn't have 'value'")
  667. }
  668. if err := u.unmarshalValue(reflect.ValueOf(m).Elem(), *val, nil); err != nil {
  669. return fmt.Errorf("can't unmarshal Any nested proto %T: %v", m, err)
  670. }
  671. } else {
  672. delete(jsonFields, "@type")
  673. nestedProto, err := json.Marshal(jsonFields)
  674. if err != nil {
  675. return fmt.Errorf("can't generate JSON for Any's nested proto to be unmarshaled: %v", err)
  676. }
  677. if err = u.unmarshalValue(reflect.ValueOf(m).Elem(), nestedProto, nil); err != nil {
  678. return fmt.Errorf("can't unmarshal Any nested proto %T: %v", m, err)
  679. }
  680. }
  681. b, err := proto.Marshal(m)
  682. if err != nil {
  683. return fmt.Errorf("can't marshal proto %T into Any.Value: %v", m, err)
  684. }
  685. target.Field(1).SetBytes(b)
  686. return nil
  687. case "Duration":
  688. unq, err := unquote(string(inputValue))
  689. if err != nil {
  690. return err
  691. }
  692. d, err := time.ParseDuration(unq)
  693. if err != nil {
  694. return fmt.Errorf("bad Duration: %v", err)
  695. }
  696. ns := d.Nanoseconds()
  697. s := ns / 1e9
  698. ns %= 1e9
  699. target.Field(0).SetInt(s)
  700. target.Field(1).SetInt(ns)
  701. return nil
  702. case "Timestamp":
  703. unq, err := unquote(string(inputValue))
  704. if err != nil {
  705. return err
  706. }
  707. t, err := time.Parse(time.RFC3339Nano, unq)
  708. if err != nil {
  709. return fmt.Errorf("bad Timestamp: %v", err)
  710. }
  711. target.Field(0).SetInt(t.Unix())
  712. target.Field(1).SetInt(int64(t.Nanosecond()))
  713. return nil
  714. case "Struct":
  715. var m map[string]json.RawMessage
  716. if err := json.Unmarshal(inputValue, &m); err != nil {
  717. return fmt.Errorf("bad StructValue: %v", err)
  718. }
  719. target.Field(0).Set(reflect.ValueOf(map[string]*stpb.Value{}))
  720. for k, jv := range m {
  721. pv := &stpb.Value{}
  722. if err := u.unmarshalValue(reflect.ValueOf(pv).Elem(), jv, prop); err != nil {
  723. return fmt.Errorf("bad value in StructValue for key %q: %v", k, err)
  724. }
  725. target.Field(0).SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(pv))
  726. }
  727. return nil
  728. case "ListValue":
  729. var s []json.RawMessage
  730. if err := json.Unmarshal(inputValue, &s); err != nil {
  731. return fmt.Errorf("bad ListValue: %v", err)
  732. }
  733. target.Field(0).Set(reflect.ValueOf(make([]*stpb.Value, len(s))))
  734. for i, sv := range s {
  735. if err := u.unmarshalValue(target.Field(0).Index(i), sv, prop); err != nil {
  736. return err
  737. }
  738. }
  739. return nil
  740. case "Value":
  741. ivStr := string(inputValue)
  742. if ivStr == "null" {
  743. target.Field(0).Set(reflect.ValueOf(&stpb.Value_NullValue{}))
  744. } else if v, err := strconv.ParseFloat(ivStr, 0); err == nil {
  745. target.Field(0).Set(reflect.ValueOf(&stpb.Value_NumberValue{v}))
  746. } else if v, err := unquote(ivStr); err == nil {
  747. target.Field(0).Set(reflect.ValueOf(&stpb.Value_StringValue{v}))
  748. } else if v, err := strconv.ParseBool(ivStr); err == nil {
  749. target.Field(0).Set(reflect.ValueOf(&stpb.Value_BoolValue{v}))
  750. } else if err := json.Unmarshal(inputValue, &[]json.RawMessage{}); err == nil {
  751. lv := &stpb.ListValue{}
  752. target.Field(0).Set(reflect.ValueOf(&stpb.Value_ListValue{lv}))
  753. return u.unmarshalValue(reflect.ValueOf(lv).Elem(), inputValue, prop)
  754. } else if err := json.Unmarshal(inputValue, &map[string]json.RawMessage{}); err == nil {
  755. sv := &stpb.Struct{}
  756. target.Field(0).Set(reflect.ValueOf(&stpb.Value_StructValue{sv}))
  757. return u.unmarshalValue(reflect.ValueOf(sv).Elem(), inputValue, prop)
  758. } else {
  759. return fmt.Errorf("unrecognized type for Value %q", ivStr)
  760. }
  761. return nil
  762. }
  763. }
  764. // Handle enums, which have an underlying type of int32,
  765. // and may appear as strings.
  766. // The case of an enum appearing as a number is handled
  767. // at the bottom of this function.
  768. if inputValue[0] == '"' && prop != nil && prop.Enum != "" {
  769. vmap := proto.EnumValueMap(prop.Enum)
  770. // Don't need to do unquoting; valid enum names
  771. // are from a limited character set.
  772. s := inputValue[1 : len(inputValue)-1]
  773. n, ok := vmap[string(s)]
  774. if !ok {
  775. return fmt.Errorf("unknown value %q for enum %s", s, prop.Enum)
  776. }
  777. if target.Kind() == reflect.Ptr { // proto2
  778. target.Set(reflect.New(targetType.Elem()))
  779. target = target.Elem()
  780. }
  781. if targetType.Kind() != reflect.Int32 {
  782. return fmt.Errorf("invalid target %q for enum %s", targetType.Kind(), prop.Enum)
  783. }
  784. target.SetInt(int64(n))
  785. return nil
  786. }
  787. // Handle nested messages.
  788. if targetType.Kind() == reflect.Struct {
  789. var jsonFields map[string]json.RawMessage
  790. if err := json.Unmarshal(inputValue, &jsonFields); err != nil {
  791. return err
  792. }
  793. consumeField := func(prop *proto.Properties) (json.RawMessage, bool) {
  794. // Be liberal in what names we accept; both orig_name and camelName are okay.
  795. fieldNames := acceptedJSONFieldNames(prop)
  796. vOrig, okOrig := jsonFields[fieldNames.orig]
  797. vCamel, okCamel := jsonFields[fieldNames.camel]
  798. if !okOrig && !okCamel {
  799. return nil, false
  800. }
  801. // If, for some reason, both are present in the data, favour the camelName.
  802. var raw json.RawMessage
  803. if okOrig {
  804. raw = vOrig
  805. delete(jsonFields, fieldNames.orig)
  806. }
  807. if okCamel {
  808. raw = vCamel
  809. delete(jsonFields, fieldNames.camel)
  810. }
  811. return raw, true
  812. }
  813. sprops := proto.GetProperties(targetType)
  814. for i := 0; i < target.NumField(); i++ {
  815. ft := target.Type().Field(i)
  816. if strings.HasPrefix(ft.Name, "XXX_") {
  817. continue
  818. }
  819. valueForField, ok := consumeField(sprops.Prop[i])
  820. if !ok {
  821. continue
  822. }
  823. if err := u.unmarshalValue(target.Field(i), valueForField, sprops.Prop[i]); err != nil {
  824. return err
  825. }
  826. }
  827. // Check for any oneof fields.
  828. if len(jsonFields) > 0 {
  829. for _, oop := range sprops.OneofTypes {
  830. raw, ok := consumeField(oop.Prop)
  831. if !ok {
  832. continue
  833. }
  834. nv := reflect.New(oop.Type.Elem())
  835. target.Field(oop.Field).Set(nv)
  836. if err := u.unmarshalValue(nv.Elem().Field(0), raw, oop.Prop); err != nil {
  837. return err
  838. }
  839. }
  840. }
  841. // Handle proto2 extensions.
  842. if len(jsonFields) > 0 {
  843. if ep, ok := target.Addr().Interface().(proto.Message); ok {
  844. for _, ext := range proto.RegisteredExtensions(ep) {
  845. name := fmt.Sprintf("[%s]", ext.Name)
  846. raw, ok := jsonFields[name]
  847. if !ok {
  848. continue
  849. }
  850. delete(jsonFields, name)
  851. nv := reflect.New(reflect.TypeOf(ext.ExtensionType).Elem())
  852. if err := u.unmarshalValue(nv.Elem(), raw, nil); err != nil {
  853. return err
  854. }
  855. if err := proto.SetExtension(ep, ext, nv.Interface()); err != nil {
  856. return err
  857. }
  858. }
  859. }
  860. }
  861. if !u.AllowUnknownFields && len(jsonFields) > 0 {
  862. // Pick any field to be the scapegoat.
  863. var f string
  864. for fname := range jsonFields {
  865. f = fname
  866. break
  867. }
  868. return fmt.Errorf("unknown field %q in %v", f, targetType)
  869. }
  870. return nil
  871. }
  872. // Handle arrays (which aren't encoded bytes)
  873. if targetType.Kind() == reflect.Slice && targetType.Elem().Kind() != reflect.Uint8 {
  874. var slc []json.RawMessage
  875. if err := json.Unmarshal(inputValue, &slc); err != nil {
  876. return err
  877. }
  878. if slc != nil {
  879. l := len(slc)
  880. target.Set(reflect.MakeSlice(targetType, l, l))
  881. for i := 0; i < l; i++ {
  882. if err := u.unmarshalValue(target.Index(i), slc[i], prop); err != nil {
  883. return err
  884. }
  885. }
  886. }
  887. return nil
  888. }
  889. // Handle maps (whose keys are always strings)
  890. if targetType.Kind() == reflect.Map {
  891. var mp map[string]json.RawMessage
  892. if err := json.Unmarshal(inputValue, &mp); err != nil {
  893. return err
  894. }
  895. if mp != nil {
  896. target.Set(reflect.MakeMap(targetType))
  897. for ks, raw := range mp {
  898. // Unmarshal map key. The core json library already decoded the key into a
  899. // string, so we handle that specially. Other types were quoted post-serialization.
  900. var k reflect.Value
  901. if targetType.Key().Kind() == reflect.String {
  902. k = reflect.ValueOf(ks)
  903. } else {
  904. k = reflect.New(targetType.Key()).Elem()
  905. var kprop *proto.Properties
  906. if prop != nil && prop.MapKeyProp != nil {
  907. kprop = prop.MapKeyProp
  908. }
  909. if err := u.unmarshalValue(k, json.RawMessage(ks), kprop); err != nil {
  910. return err
  911. }
  912. }
  913. // Unmarshal map value.
  914. v := reflect.New(targetType.Elem()).Elem()
  915. var vprop *proto.Properties
  916. if prop != nil && prop.MapValProp != nil {
  917. vprop = prop.MapValProp
  918. }
  919. if err := u.unmarshalValue(v, raw, vprop); err != nil {
  920. return err
  921. }
  922. target.SetMapIndex(k, v)
  923. }
  924. }
  925. return nil
  926. }
  927. // Non-finite numbers can be encoded as strings.
  928. isFloat := targetType.Kind() == reflect.Float32 || targetType.Kind() == reflect.Float64
  929. if isFloat {
  930. if num, ok := nonFinite[string(inputValue)]; ok {
  931. target.SetFloat(num)
  932. return nil
  933. }
  934. }
  935. // integers & floats can be encoded as strings. In this case we drop
  936. // the quotes and proceed as normal.
  937. isNum := targetType.Kind() == reflect.Int64 || targetType.Kind() == reflect.Uint64 ||
  938. targetType.Kind() == reflect.Int32 || targetType.Kind() == reflect.Uint32 ||
  939. targetType.Kind() == reflect.Float32 || targetType.Kind() == reflect.Float64
  940. if isNum && strings.HasPrefix(string(inputValue), `"`) {
  941. inputValue = inputValue[1 : len(inputValue)-1]
  942. }
  943. // Use the encoding/json for parsing other value types.
  944. return json.Unmarshal(inputValue, target.Addr().Interface())
  945. }
  946. func unquote(s string) (string, error) {
  947. var ret string
  948. err := json.Unmarshal([]byte(s), &ret)
  949. return ret, err
  950. }
  951. // jsonProperties returns parsed proto.Properties for the field and corrects JSONName attribute.
  952. func jsonProperties(f reflect.StructField, origName bool) *proto.Properties {
  953. var prop proto.Properties
  954. prop.Init(f.Type, f.Name, f.Tag.Get("protobuf"), &f)
  955. if origName || prop.JSONName == "" {
  956. prop.JSONName = prop.OrigName
  957. }
  958. return &prop
  959. }
  960. type fieldNames struct {
  961. orig, camel string
  962. }
  963. func acceptedJSONFieldNames(prop *proto.Properties) fieldNames {
  964. opts := fieldNames{orig: prop.OrigName, camel: prop.OrigName}
  965. if prop.JSONName != "" {
  966. opts.camel = prop.JSONName
  967. }
  968. return opts
  969. }
  970. // Writer wrapper inspired by https://blog.golang.org/errors-are-values
  971. type errWriter struct {
  972. writer io.Writer
  973. err error
  974. }
  975. func (w *errWriter) write(str string) {
  976. if w.err != nil {
  977. return
  978. }
  979. _, w.err = w.writer.Write([]byte(str))
  980. }
  981. // Map fields may have key types of non-float scalars, strings and enums.
  982. // The easiest way to sort them in some deterministic order is to use fmt.
  983. // If this turns out to be inefficient we can always consider other options,
  984. // such as doing a Schwartzian transform.
  985. //
  986. // Numeric keys are sorted in numeric order per
  987. // https://developers.google.com/protocol-buffers/docs/proto#maps.
  988. type mapKeys []reflect.Value
  989. func (s mapKeys) Len() int { return len(s) }
  990. func (s mapKeys) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  991. func (s mapKeys) Less(i, j int) bool {
  992. if k := s[i].Kind(); k == s[j].Kind() {
  993. switch k {
  994. case reflect.String:
  995. return s[i].String() < s[j].String()
  996. case reflect.Int32, reflect.Int64:
  997. return s[i].Int() < s[j].Int()
  998. case reflect.Uint32, reflect.Uint64:
  999. return s[i].Uint() < s[j].Uint()
  1000. }
  1001. }
  1002. return fmt.Sprint(s[i].Interface()) < fmt.Sprint(s[j].Interface())
  1003. }
  1004. // checkRequiredFields returns an error if any required field in the given proto message is not set.
  1005. // This function is used by both Marshal and Unmarshal. While required fields only exist in a
  1006. // proto2 message, a proto3 message can contain proto2 message(s).
  1007. func checkRequiredFields(pb proto.Message) error {
  1008. // Most well-known type messages do not contain required fields. The "Any" type may contain
  1009. // a message that has required fields.
  1010. //
  1011. // When an Any message is being marshaled, the code will invoked proto.Unmarshal on Any.Value
  1012. // field in order to transform that into JSON, and that should have returned an error if a
  1013. // required field is not set in the embedded message.
  1014. //
  1015. // When an Any message is being unmarshaled, the code will have invoked proto.Marshal on the
  1016. // embedded message to store the serialized message in Any.Value field, and that should have
  1017. // returned an error if a required field is not set.
  1018. if _, ok := pb.(wkt); ok {
  1019. return nil
  1020. }
  1021. v := reflect.ValueOf(pb)
  1022. // Skip message if it is not a struct pointer.
  1023. if v.Kind() != reflect.Ptr {
  1024. return nil
  1025. }
  1026. v = v.Elem()
  1027. if v.Kind() != reflect.Struct {
  1028. return nil
  1029. }
  1030. for i := 0; i < v.NumField(); i++ {
  1031. field := v.Field(i)
  1032. sfield := v.Type().Field(i)
  1033. if sfield.PkgPath != "" {
  1034. // blank PkgPath means the field is exported; skip if not exported
  1035. continue
  1036. }
  1037. if strings.HasPrefix(sfield.Name, "XXX_") {
  1038. continue
  1039. }
  1040. // Oneof field is an interface implemented by wrapper structs containing the actual oneof
  1041. // field, i.e. an interface containing &T{real_value}.
  1042. if sfield.Tag.Get("protobuf_oneof") != "" {
  1043. if field.Kind() != reflect.Interface {
  1044. continue
  1045. }
  1046. v := field.Elem()
  1047. if v.Kind() != reflect.Ptr || v.IsNil() {
  1048. continue
  1049. }
  1050. v = v.Elem()
  1051. if v.Kind() != reflect.Struct || v.NumField() < 1 {
  1052. continue
  1053. }
  1054. field = v.Field(0)
  1055. sfield = v.Type().Field(0)
  1056. }
  1057. protoTag := sfield.Tag.Get("protobuf")
  1058. if protoTag == "" {
  1059. continue
  1060. }
  1061. var prop proto.Properties
  1062. prop.Init(sfield.Type, sfield.Name, protoTag, &sfield)
  1063. switch field.Kind() {
  1064. case reflect.Map:
  1065. if field.IsNil() {
  1066. continue
  1067. }
  1068. // Check each map value.
  1069. keys := field.MapKeys()
  1070. for _, k := range keys {
  1071. v := field.MapIndex(k)
  1072. if err := checkRequiredFieldsInValue(v); err != nil {
  1073. return err
  1074. }
  1075. }
  1076. case reflect.Slice:
  1077. // Handle non-repeated type, e.g. bytes.
  1078. if !prop.Repeated {
  1079. if prop.Required && field.IsNil() {
  1080. return fmt.Errorf("required field %q is not set", prop.Name)
  1081. }
  1082. continue
  1083. }
  1084. // Handle repeated type.
  1085. if field.IsNil() {
  1086. continue
  1087. }
  1088. // Check each slice item.
  1089. for i := 0; i < field.Len(); i++ {
  1090. v := field.Index(i)
  1091. if err := checkRequiredFieldsInValue(v); err != nil {
  1092. return err
  1093. }
  1094. }
  1095. case reflect.Ptr:
  1096. if field.IsNil() {
  1097. if prop.Required {
  1098. return fmt.Errorf("required field %q is not set", prop.Name)
  1099. }
  1100. continue
  1101. }
  1102. if err := checkRequiredFieldsInValue(field); err != nil {
  1103. return err
  1104. }
  1105. }
  1106. }
  1107. // Handle proto2 extensions.
  1108. for _, ext := range proto.RegisteredExtensions(pb) {
  1109. if !proto.HasExtension(pb, ext) {
  1110. continue
  1111. }
  1112. ep, err := proto.GetExtension(pb, ext)
  1113. if err != nil {
  1114. return err
  1115. }
  1116. err = checkRequiredFieldsInValue(reflect.ValueOf(ep))
  1117. if err != nil {
  1118. return err
  1119. }
  1120. }
  1121. return nil
  1122. }
  1123. func checkRequiredFieldsInValue(v reflect.Value) error {
  1124. if pm, ok := v.Interface().(proto.Message); ok {
  1125. return checkRequiredFields(pm)
  1126. }
  1127. return nil
  1128. }