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