1 // Copyright 2009 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.
16 // A forkableWriter is an in-memory buffer that can be
17 // 'forked' to create new forkableWriters that bracket the
19 // pre, post := w.fork();
20 // the overall sequence of bytes represented is logically w+pre+post.
21 type forkableWriter struct {
23 pre, post *forkableWriter
26 func newForkableWriter() *forkableWriter {
27 return &forkableWriter{bytes.NewBuffer(nil), nil, nil}
30 func (f *forkableWriter) fork() (pre, post *forkableWriter) {
31 if f.pre != nil || f.post != nil {
32 panic("have already forked")
34 f.pre = newForkableWriter()
35 f.post = newForkableWriter()
39 func (f *forkableWriter) Len() (l int) {
50 func (f *forkableWriter) writeTo(out io.Writer) (n int, err error) {
51 n, err = out.Write(f.Bytes())
59 nn, err = f.pre.writeTo(out)
67 nn, err = f.post.writeTo(out)
73 func marshalBase128Int(out *forkableWriter, n int64) (err error) {
75 err = out.WriteByte(0)
80 for i := n; i > 0; i >>= 7 {
84 for i := l - 1; i >= 0; i-- {
85 o := byte(n >> uint(i*7))
90 err = out.WriteByte(o)
99 func marshalInt64(out *forkableWriter, i int64) (err error) {
103 err = out.WriteByte(byte(i >> uint((n-1)*8)))
112 func int64Length(i int64) (numBytes int) {
128 func marshalBigInt(out *forkableWriter, n *big.Int) (err error) {
130 // A negative number has to be converted to two's-complement
131 // form. So we'll subtract 1 and invert. If the
132 // most-significant-bit isn't set then we'll need to pad the
133 // beginning with 0xff in order to keep the number negative.
134 nMinus1 := new(big.Int).Neg(n)
135 nMinus1.Sub(nMinus1, bigOne)
136 bytes := nMinus1.Bytes()
137 for i := range bytes {
140 if len(bytes) == 0 || bytes[0]&0x80 == 0 {
141 err = out.WriteByte(0xff)
146 _, err = out.Write(bytes)
147 } else if n.Sign() == 0 {
148 // Zero is written as a single 0 zero rather than no bytes.
149 err = out.WriteByte(0x00)
152 if len(bytes) > 0 && bytes[0]&0x80 != 0 {
153 // We'll have to pad this with 0x00 in order to stop it
154 // looking like a negative number.
155 err = out.WriteByte(0)
160 _, err = out.Write(bytes)
165 func marshalLength(out *forkableWriter, i int) (err error) {
169 err = out.WriteByte(byte(i >> uint((n-1)*8)))
178 func lengthLength(i int) (numBytes int) {
187 func marshalTagAndLength(out *forkableWriter, t tagAndLength) (err error) {
188 b := uint8(t.class) << 6
194 err = out.WriteByte(b)
198 err = marshalBase128Int(out, int64(t.tag))
204 err = out.WriteByte(b)
211 l := lengthLength(t.length)
212 err = out.WriteByte(0x80 | byte(l))
216 err = marshalLength(out, t.length)
221 err = out.WriteByte(byte(t.length))
230 func marshalBitString(out *forkableWriter, b BitString) (err error) {
231 paddingBits := byte((8 - b.BitLength%8) % 8)
232 err = out.WriteByte(paddingBits)
236 _, err = out.Write(b.Bytes)
240 func marshalObjectIdentifier(out *forkableWriter, oid []int) (err error) {
241 if len(oid) < 2 || oid[0] > 6 || oid[1] >= 40 {
242 return StructuralError{"invalid object identifier"}
245 err = out.WriteByte(byte(oid[0]*40 + oid[1]))
249 for i := 2; i < len(oid); i++ {
250 err = marshalBase128Int(out, int64(oid[i]))
259 func marshalPrintableString(out *forkableWriter, s string) (err error) {
261 for _, c := range b {
263 return StructuralError{"PrintableString contains invalid character"}
267 _, err = out.Write(b)
271 func marshalIA5String(out *forkableWriter, s string) (err error) {
273 for _, c := range b {
275 return StructuralError{"IA5String contains invalid character"}
279 _, err = out.Write(b)
283 func marshalTwoDigits(out *forkableWriter, v int) (err error) {
284 err = out.WriteByte(byte('0' + (v/10)%10))
288 return out.WriteByte(byte('0' + v%10))
291 func marshalUTCTime(out *forkableWriter, t *time.Time) (err error) {
293 case 1950 <= t.Year && t.Year < 2000:
294 err = marshalTwoDigits(out, int(t.Year-1900))
295 case 2000 <= t.Year && t.Year < 2050:
296 err = marshalTwoDigits(out, int(t.Year-2000))
298 return StructuralError{"Cannot represent time as UTCTime"}
305 err = marshalTwoDigits(out, t.Month)
310 err = marshalTwoDigits(out, t.Day)
315 err = marshalTwoDigits(out, t.Hour)
320 err = marshalTwoDigits(out, t.Minute)
325 err = marshalTwoDigits(out, t.Second)
331 case t.ZoneOffset/60 == 0:
332 err = out.WriteByte('Z')
334 case t.ZoneOffset > 0:
335 err = out.WriteByte('+')
336 case t.ZoneOffset < 0:
337 err = out.WriteByte('-')
344 offsetMinutes := t.ZoneOffset / 60
345 if offsetMinutes < 0 {
346 offsetMinutes = -offsetMinutes
349 err = marshalTwoDigits(out, offsetMinutes/60)
354 err = marshalTwoDigits(out, offsetMinutes%60)
358 func stripTagAndLength(in []byte) []byte {
359 _, offset, err := parseTagAndLength(in, 0)
366 func marshalBody(out *forkableWriter, value reflect.Value, params fieldParameters) (err error) {
367 switch value.Type() {
369 return marshalUTCTime(out, value.Interface().(*time.Time))
371 return marshalBitString(out, value.Interface().(BitString))
372 case objectIdentifierType:
373 return marshalObjectIdentifier(out, value.Interface().(ObjectIdentifier))
375 return marshalBigInt(out, value.Interface().(*big.Int))
378 switch v := value; v.Kind() {
381 return out.WriteByte(255)
383 return out.WriteByte(0)
385 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
386 return marshalInt64(out, int64(v.Int()))
392 // If the first element of the structure is a non-empty
393 // RawContents, then we don't bother serializing the rest.
394 if t.NumField() > 0 && t.Field(0).Type == rawContentsType {
397 bytes := make([]byte, s.Len())
398 for i := 0; i < s.Len(); i++ {
399 bytes[i] = uint8(s.Index(i).Uint())
401 /* The RawContents will contain the tag and
402 * length fields but we'll also be writing
403 * those ourselves, so we strip them out of
405 _, err = out.Write(stripTagAndLength(bytes))
412 for i := startingField; i < t.NumField(); i++ {
413 var pre *forkableWriter
414 pre, out = out.fork()
415 err = marshalField(pre, v.Field(i), parseFieldParameters(t.Field(i).Tag.Get("asn1")))
422 sliceType := v.Type()
423 if sliceType.Elem().Kind() == reflect.Uint8 {
424 bytes := make([]byte, v.Len())
425 for i := 0; i < v.Len(); i++ {
426 bytes[i] = uint8(v.Index(i).Uint())
428 _, err = out.Write(bytes)
432 var params fieldParameters
433 for i := 0; i < v.Len(); i++ {
434 var pre *forkableWriter
435 pre, out = out.fork()
436 err = marshalField(pre, v.Index(i), params)
443 if params.stringType == tagIA5String {
444 return marshalIA5String(out, v.String())
446 return marshalPrintableString(out, v.String())
451 return StructuralError{"unknown Go type"}
454 func marshalField(out *forkableWriter, v reflect.Value, params fieldParameters) (err error) {
455 // If the field is an interface{} then recurse into it.
456 if v.Kind() == reflect.Interface && v.Type().NumMethod() == 0 {
457 return marshalField(out, v.Elem(), params)
460 if params.optional && reflect.DeepEqual(v.Interface(), reflect.Zero(v.Type()).Interface()) {
464 if v.Type() == rawValueType {
465 rv := v.Interface().(RawValue)
466 if len(rv.FullBytes) != 0 {
467 _, err = out.Write(rv.FullBytes)
469 err = marshalTagAndLength(out, tagAndLength{rv.Class, rv.Tag, len(rv.Bytes), rv.IsCompound})
473 _, err = out.Write(rv.Bytes)
478 tag, isCompound, ok := getUniversalType(v.Type())
480 err = StructuralError{fmt.Sprintf("unknown Go type: %v", v.Type())}
483 class := classUniversal
485 if params.stringType != 0 {
486 if tag != tagPrintableString {
487 return StructuralError{"Explicit string type given to non-string member"}
489 tag = params.stringType
493 if tag != tagSequence {
494 return StructuralError{"Non sequence tagged as set"}
499 tags, body := out.fork()
501 err = marshalBody(body, v, params)
506 bodyLen := body.Len()
508 var explicitTag *forkableWriter
510 explicitTag, tags = tags.fork()
513 if !params.explicit && params.tag != nil {
516 class = classContextSpecific
519 err = marshalTagAndLength(tags, tagAndLength{class, tag, bodyLen, isCompound})
525 err = marshalTagAndLength(explicitTag, tagAndLength{
526 class: classContextSpecific,
528 length: bodyLen + tags.Len(),
536 // Marshal returns the ASN.1 encoding of val.
537 func Marshal(val interface{}) ([]byte, error) {
539 v := reflect.ValueOf(val)
540 f := newForkableWriter()
541 err := marshalField(f, v, fieldParameters{})
545 _, err = f.writeTo(&out)
546 return out.Bytes(), nil